diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 85729167d..ed4d591b5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -482,6 +482,18 @@ jobs: git diff --exit-code -- app/src/main/rust/stores/Cargo.lock \ || { echo "::error::Cargo.lock changed during the build; commit the regenerated lockfile (uploaded as stores-cargo-lock)"; exit 1; } + - name: Store engines host unit tests + # The crate's #[test] functions are pure host-side logic (manifest parsing, chunk plans, + # assembly from a cache, hashes), so a plain `cargo test` on the runner's own architecture + # runs them; the Android build above compiles none of them. Informational on this first + # run - the point is to learn whether they pass - and bounded so a hang can never hold + # the apk. Make it blocking once it is known green. + timeout-minutes: 10 + continue-on-error: true + run: | + cd app/src/main/rust/stores + cargo test --locked 2>&1 | tail -60 + - name: Upload the regenerated Cargo.lock if: failure() uses: actions/upload-artifact@v4 diff --git a/app/src/main/rust/stores/JNI.md b/app/src/main/rust/stores/JNI.md index ab969483e..447088741 100644 --- a/app/src/main/rust/stores/JNI.md +++ b/app/src/main/rust/stores/JNI.md @@ -111,57 +111,117 @@ On-disk protocol (what a resumed run, by either engine, relies on): a file is as ## `com.droiddeck.launcher.stores.epic.EpicNative` -The chunk-fetch inner loop of an Epic install: fills `/.chunks/` with verified, -decompressed chunks for the files the manager says are pending. The Kotlin manager still fetches -and parses the manifest API JSON, downloads the manifest, selects files (install tags), runs the -delta/verify pass, assembles files from the chunk cache and does every post-install step. The -engine re-parses the same manifest bytes (ChunksV4 binary or legacy JSON), rebuilds the chunk plan -for the pending files, skips chunks already in the cache, and writes verified chunks with a -`.part` + rename protocol, so the on-disk state is the same whichever side fetched. +Two runs make up the native half of an Epic install: + +1. **Fetch** (`nativeStart`): fills the chunk cache with verified, decompressed chunks for the + files the manager says are pending. The Kotlin manager still fetches and parses the manifest + API JSON, downloads the manifest, selects files (install tags), runs the delta/verify pass and + does every post-install step. The engine re-parses the same manifest bytes (ChunksV4 binary + or legacy JSON), rebuilds the chunk plan for the pending files, skips chunks already in the + cache, and writes verified chunks with a `.part` + rename protocol, so the on-disk state is the + same whichever side fetched. +2. **Assemble** (`nativeAssemble`): writes the pending files from the cache, one sequential write + per file, SHA-1 checked as the bytes go out when the manifest hashes the file. This is the + same loop the Kotlin manager runs today (`for part in file.parts: write(chunk[offset..+size])`, + same "Missing chunk X for Y" wording); the Kotlin loop remains a valid fallback. + +**The chunk cache directory** is the `chunkCacheDir` parameter of both calls (always pass the +same value to both for one install): + +- `""` — today's behaviour: the cache is `/.chunks`. The fetch leaves it in place; + `nativeAssemble` removes it whole at the end of a successful run (as the Kotlin loop's + `deleteDir(.chunks)` does), and never deletes a chunk early. +- any other absolute path — a **scratch cache**, meant for internal storage when the game + installs to an SD card (each byte then hits the card once instead of twice; the card's write + speed stops starving the fetchers). The fetch fills it exactly like `.chunks`. The assembler + reference-counts chunk GUIDs across the files it was given and **deletes each cached chunk as + soon as the last file that uses it has been written and verified**, then removes the directory + at the end of a successful run. A cancelled or failed run (fetch or assembly) leaves the cache + exactly as it stands, for resume: the next run's delta pass skips finished files and the next + fetch skips chunks still cached. The directory is created by the fetch if it does not exist; + give each install its own (e.g. `/epic/`), since a successful assembly + removes it. | Method | JNI signature | Symbol | |---|---|---| -| `nativeStart(...)`: Long | `([BLjava/lang/String;[Ljava/lang/String;[IIJLjava/lang/String;IILjava/lang/Object;)J` (last parameter is the listener) | `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStart` | +| `nativeStart(...)`: Long | `([BLjava/lang/String;Ljava/lang/String;[Ljava/lang/String;[IIJLjava/lang/String;IILjava/lang/Object;)J` (last parameter is the listener) | `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStart` | +| `nativeAssemble(...)`: Long | `([BLjava/lang/String;Ljava/lang/String;[ILjava/lang/Object;)J` (last parameter is the listener) | `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeAssemble` | | `nativeCancel(handle: Long)` | `(J)V` | `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeCancel` | | `nativeRelease(handle: Long)` | `(J)V` | `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeRelease` | -There is no `nativeProbe`; Bannerlator probes by catching the `Throwable` from `loadLibrary` / -the first `nativeStart`. +`nativeCancel` / `nativeRelease` take the handle of either run. There is no `nativeProbe`; +Bannerlator probes by catching the `Throwable` from `loadLibrary` / the first `nativeStart`. -`nativeStart` parameters, in order: +```kotlin +@JvmStatic private external fun nativeStart( + manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array, + pendingFileIdx: IntArray, expectedChunks: Int, expectedBytes: Long, caBundlePath: String, + maxWorkers: Int, processWorkers: Int, listener: Listener, +): Long +@JvmStatic private external fun nativeAssemble( + manifest: ByteArray, installDir: String, chunkCacheDir: String, fileIdx: IntArray, listener: Listener, +): Long +``` + +### `nativeStart` parameters, in order | # | Parameter | Meaning | |---|---|---| | 1 | `manifest: ByteArray` | the raw manifest bytes the manager downloaded (binary ChunksV4 or JSON) | -| 2 | `installDir: String` | absolute install directory; the chunk cache is `/.chunks` | -| 3 | `cdnPrefixes: Array` | the CDN base URLs from the manifest API answer (`.../ChunksV4//` style); one or many, distinct hosts widen the window | -| 4 | `pendingFileIdx: IntArray` | indices into the manifest's file list of the files still to fetch (the manager's delta/verify result) | -| 5 | `expectedChunks: Int` | the manager's own needed-chunk count for a cross-check; `-1` = no cross-check | -| 6 | `expectedBytes: Long` | the manager's `Σ max(fileSize, 1)` for a cross-check; `-1` = no cross-check | -| 7 | `caBundlePath: String` | see conventions | -| 8 | `maxWorkers: Int` | window ceiling (Bannerlator: 8) | -| 9 | `processWorkers: Int` | inflate/verify/write threads | -| 10 | `listener` | see below | +| 2 | `installDir: String` | absolute install directory | +| 3 | `chunkCacheDir: String` | `""` = `/.chunks`; else the scratch cache directory (see above) | +| 4 | `cdnPrefixes: Array` | the CDN base URLs from the manifest API answer (`.../ChunksV4//` style); one or many, distinct hosts widen the window | +| 5 | `pendingFileIdx: IntArray` | indices into the manifest's file list of the files still to fetch (the manager's delta/verify result) | +| 6 | `expectedChunks: Int` | the manager's own needed-chunk count for a cross-check; `-1` = no cross-check | +| 7 | `expectedBytes: Long` | the manager's `Σ max(fileSize, 1)` for a cross-check; `-1` = no cross-check | +| 8 | `caBundlePath: String` | see conventions | +| 9 | `maxWorkers: Int` | window ceiling (Bannerlator: 8) | +| 10 | `processWorkers: Int` | inflate/verify/write threads | +| 11 | `listener` | see below | Planning (manifest parse + plan + cross-check) runs synchronously on the calling thread, so a plan failure returns `0` BEFORE any fetch; the manager then runs its own fallback loop. On `0`, `onComplete(false, reason, 0)` has already been called synchronously (except for a null listener). On success, `onPlan` has been called synchronously before `nativeStart` returns, then the fetch -runs on a new thread. +runs on a new thread. The engine's `plan` log line names the cache: +`plan chunk_dir=ChunksV4 cache_dir= scratch= files_pending=… chunks=… bytes=… …`. -Suggested listener: `com.droiddeck.launcher.stores.epic.EpicNative.Listener` (nested interface, -as in Bannerlator). +### `nativeAssemble` parameters, in order + +| # | Parameter | Meaning | +|---|---|---| +| 1 | `manifest: ByteArray` | the same manifest bytes as the fetch | +| 2 | `installDir: String` | absolute install directory (files are written at `installDir/`) | +| 3 | `chunkCacheDir: String` | the same value the fetch was given (`""` or the scratch directory) | +| 4 | `fileIdx: IntArray` | indices into the manifest's file list of the files to write — the fetch's `pendingFileIdx`, in one call | +| 5 | `listener` | see below | + +Parse + plan run on the calling thread: an unparsable manifest, an index out of range or an +empty `installDir` returns `0` after a synchronous `onComplete(false, reason, 0)` and nothing is +written. Otherwise the assembly runs on a new thread. Each file is created fresh and written in +part order; on any error (missing chunk, short chunk, I/O error, SHA-1 mismatch) the file being +written is deleted, the run fails with that error, no further files are touched and the cache is +left as it is. A manifest SHA-1 of all zeros (and a JSON manifest, which has none) means no hash +check — the Kotlin delta pass treats those the same way. The run's log lines: +`assemble cache_dir=… scratch=… files=… bytes=… chunks_referenced=…`, then `cache removed …` / +`cache not removed …: ` (not fatal) and `assembled files=… bytes=… chunks_removed_early=…`. + +### Listener + +Suggested: `com.droiddeck.launcher.stores.epic.EpicNative.Listener` (nested interface, as in +Bannerlator). One interface serves both runs. | Listener method | JNI signature | When | |---|---|---| -| `onPlan(chunksTotal: Int, bytesTotal: Long, chunkDir: String)` | `(IJLjava/lang/String;)V` | once, synchronously inside `nativeStart`, before any fetch: the plan the engine derived | -| `onProgress(bytesDone: Long, bytesTotal: Long, chunksDone: Int, chunksTotal: Int)` | `(JJII)V` | per accounted chunk (cached-skip or fetched); process-pool thread | -| `onLog(line: String)` | `(Ljava/lang/String;)V` | engine log line, already in logcat under `EpicNative`; any native thread (also synchronously from `nativeStart` for the start line) | -| `onComplete(success: Boolean, error: String, bytesCredited: Long)` | `(ZLjava/lang/String;J)V` | terminal, exactly once (worker thread; or synchronously when `nativeStart` returns `0`) | +| `onPlan(chunksTotal: Int, bytesTotal: Long, chunkDir: String)` | `(IJLjava/lang/String;)V` | fetch only: once, synchronously inside `nativeStart`, before any fetch: the plan the engine derived (`chunkDir` is the manifest's, e.g. `ChunksV4`, not the cache directory) | +| `onProgress(bytesDone: Long, bytesTotal: Long, done: Int, total: Int)` | `(JJII)V` | fetch: per accounted chunk (cached-skip or fetched), `done`/`total` = chunks; assembly: after each file written, `bytesDone` = bytes written so far, `done`/`total` = files. Native threads. | +| `onLog(line: String)` | `(Ljava/lang/String;)V` | engine log line, already in logcat under `EpicNative`; any native thread (also synchronously from `nativeStart`/`nativeAssemble` for the start line) | +| `onComplete(success: Boolean, error: String, bytes: Long)` | `(ZLjava/lang/String;J)V` | terminal, exactly once (worker thread; or synchronously when the call returns `0`). Fetch: `bytes` = credited bytes (cached-skip + fetched). Assembly: `bytes` = bytes written. `error` is `"cancelled"` on cancel. | -Bannerlator's `BlEpicDownload.run(...)` wraps this in a blocking call that polls an +Bannerlator's `BlEpicDownload.run(...)` wraps `nativeStart` in a blocking call that polls an `AtomicBoolean` cancel flag every 250 ms, calls `nativeCancel` on cancel, waits up to 5 s for -`onComplete`, then `nativeRelease` in `finally`. That shape is worth keeping. +`onComplete`, then `nativeRelease` in `finally`. The same wrapper shape fits `nativeAssemble` +(cancel is honoured between files; a multi-GB file finishes before the run stops). ## `com.droiddeck.launcher.stores.amazon.AmazonNative` diff --git a/app/src/main/rust/stores/src/epic.rs b/app/src/main/rust/stores/src/epic.rs index ccd871704..258c273b9 100644 --- a/app/src/main/rust/stores/src/epic.rs +++ b/app/src/main/rust/stores/src/epic.rs @@ -15,6 +15,9 @@ //! - [`plan`] — install-tag selection, unique-chunk plan, chunk paths / CDN URLs. //! - [`chunk`] — chunk header parse, zlib inflate, SHA-1 verify, cache write. //! - [`driver`] — plan → `FetchItem`s → `fetch_core::run_fetch` with the chunk-cache sink. +//! - [`assemble`] — the files from the cache, one sequential write each, SHA-1 checked as they +//! are written; with a scratch cache (one the caller placed apart from the install) each chunk +//! is deleted as soon as the last file that uses it is done. //! - [`jni`] — `Java_com_droiddeck_launcher_stores_epic_EpicNative_native*` exports. //! //! The selective-install-tag, delta/resume and chunk verification rules mirrored here were ported @@ -22,6 +25,7 @@ //! `manifest/ManifestUtils.kt`), itself derived from Legendary; both are GPL-3.0 and this crate //! carries the same licence (see `Cargo.toml`). +pub mod assemble; pub mod chunk; pub mod driver; pub mod jni; diff --git a/app/src/main/rust/stores/src/epic/assemble.rs b/app/src/main/rust/stores/src/epic/assemble.rs new file mode 100644 index 000000000..8b3e891c3 --- /dev/null +++ b/app/src/main/rust/stores/src/epic/assemble.rs @@ -0,0 +1,522 @@ +//! Files from the chunk cache: the last stage of an Epic install, as a native run. +//! +//! The Kotlin manager's own loop does this too (`EpicDownloadManager.install`, after the chunk +//! fetch): for every pending file, open it, and for every part read the cached chunk and write +//! `chunk[offset..offset+size]`. This module does the same thing, in the same order, with the +//! same wording on a missing chunk, plus what the Kotlin loop cannot do without re-reading the +//! finished file from a slow card: +//! +//! - the file's SHA-1 is computed from the bytes as they are written (no extra I/O) and compared +//! with the manifest's, when the manifest has one; a mismatch deletes the file and fails the +//! run, so a bad assembly can never pass the next delta pass by size alone; +//! - with a scratch cache — one the caller placed apart from the install directory — every chunk +//! is reference-counted across the pending files and deleted the moment the last file that +//! needs it is written and verified, so the cache never holds more than what is still owed. +//! +//! The cache directory itself goes at the end of a successful run, scratch or not, which is what +//! the Kotlin loop does with `/.chunks`. Cancellation and failure leave the cache +//! exactly as it stands, so the next run's delta pass skips the finished files and the fetch +//! skips the chunks still cached — on either engine. +//! +//! Why the cache may live elsewhere at all: an install to an SD card wrote every byte twice to +//! the card (chunk cache, then assembled file). With the cache on internal storage the card sees +//! each byte once, and the fetchers stop waiting on the card's write speed. + +use std::collections::HashMap; +use std::fs::{self, File}; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; + +use sha1::{Digest, Sha1}; + +use super::manifest::{parse_manifest, FileInfo, Manifest}; +use super::plan::resolve_cache_dir; + +/// Everything the JNI layer hands over for one assembly run. +pub struct AssembleRequest { + pub manifest_bytes: Vec, + pub install_dir: String, + /// `""` = `/.chunks` (no scratch semantics); anything else = scratch cache. + pub chunk_cache_dir: String, + /// Indices into `manifest.files` of the files to assemble, in order. + pub file_indices: Vec, +} + +/// Terminal result of an assembly run. +#[derive(Clone, Debug, Default)] +pub struct AssembleOutcome { + pub success: bool, + pub cancelled: bool, + pub error: String, + /// Bytes written into assembled files this run. + pub bytes_written: u64, + pub files_done: u64, + pub files_total: u64, + pub bytes_total: u64, + /// Chunk files deleted early because no remaining file needed them (scratch cache only). + pub chunks_removed: u64, +} + +/// The parsed plan: manifest, the files to write, and how many of them still need each chunk. +/// Built up front so a bad index fails before anything is written. +pub struct AssemblePlan { + pub manifest: Manifest, + pub install_dir: PathBuf, + pub cache_dir: PathBuf, + pub scratch_cache: bool, + pub files: Vec, + pub bytes_total: u64, + /// GUID → number of files in `files` whose parts reference it (a file counts once per GUID, + /// however many of its parts use the chunk). + pub refs: HashMap, +} + +/// Parse + plan. `Err` = nothing was written. +pub fn build_assemble_plan(req: &AssembleRequest) -> Result { + if req.install_dir.is_empty() { + return Err("assemble: empty install dir".to_string()); + } + let manifest = parse_manifest(&req.manifest_bytes).map_err(|e| format!("assemble: {e}"))?; + for &i in &req.file_indices { + if i >= manifest.files.len() { + return Err(format!( + "assemble: file index {i} out of range ({} files)", + manifest.files.len() + )); + } + } + let refs = chunk_refs(&manifest, &req.file_indices); + let bytes_total = req + .file_indices + .iter() + .map(|&i| manifest.files[i].file_size()) + .sum(); + Ok(AssemblePlan { + install_dir: PathBuf::from(&req.install_dir), + cache_dir: resolve_cache_dir(&req.install_dir, &req.chunk_cache_dir), + scratch_cache: !req.chunk_cache_dir.is_empty(), + files: req.file_indices.clone(), + bytes_total, + refs, + manifest, + }) +} + +/// How many of `file_indices` reference each chunk GUID. +pub fn chunk_refs(m: &Manifest, file_indices: &[usize]) -> HashMap { + let mut refs: HashMap = HashMap::new(); + for &fi in file_indices { + let Some(f) = m.files.get(fi) else { + continue; + }; + for g in distinct_guids(f) { + *refs.entry(g).or_insert(0) += 1; + } + } + refs +} + +/// The GUIDs a file's parts reference, each once, in first-seen order. +fn distinct_guids(f: &FileInfo) -> Vec { + let mut out: Vec = Vec::with_capacity(f.parts.len()); + for p in &f.parts { + let g = p.guid_str(); + if !out.contains(&g) { + out.push(g); + } + } + out +} + +/// The manifest's relative path with Windows separators normalised, as the Kotlin loop does +/// (`filename.replace("\\", "/")`). +pub fn relative_path(f: &FileInfo) -> String { + f.filename.replace('\\', "/") +} + +/// A manifest SHA-1 that is all zero means "none" (the Kotlin delta pass treats it the same way). +fn expected_sha1(f: &FileInfo) -> Option<&[u8; 20]> { + f.sha1.as_ref().filter(|h| h.iter().any(|&b| b != 0)) +} + +/// Chunk bytes, read whole, with the last chunk kept: consecutive parts of one file usually come +/// from the same chunk, and a file's parts are the only place a chunk is read. +struct ChunkReader { + cache_dir: PathBuf, + last: Option<(String, Vec)>, +} + +impl ChunkReader { + fn read(&mut self, guid: &str, rel_path: &str) -> Result<&[u8], String> { + if self.last.as_ref().map(|(g, _)| g.as_str()) != Some(guid) { + let path = self.cache_dir.join(guid); + if !path.exists() { + return Err(format!("Missing chunk {guid} for {rel_path}")); + } + let data = fs::read(&path).map_err(|e| format!("read chunk {guid}: {e}"))?; + self.last = Some((guid.to_string(), data)); + } + Ok(self.last.as_ref().map(|(_, d)| d.as_slice()).unwrap_or(&[])) + } + + /// Drop the kept copy of a chunk that is about to be deleted. + fn forget(&mut self, guid: &str) { + if self.last.as_ref().map(|(g, _)| g.as_str()) == Some(guid) { + self.last = None; + } + } +} + +/// Write one file from the cache. Returns the bytes written. The output is removed on any error, +/// so a file only ever exists complete (and, when the manifest hashes it, verified) or not at all. +fn write_file(reader: &mut ChunkReader, f: &FileInfo, out_path: &Path) -> Result { + let rel_path = relative_path(f); + if let Some(parent) = out_path.parent() { + fs::create_dir_all(parent).map_err(|e| format!("mkdirs {}: {e}", parent.display()))?; + } + let result = (|| { + let file = File::create(out_path).map_err(|e| format!("create {rel_path}: {e}"))?; + let mut out = BufWriter::with_capacity(1024 * 1024, file); + let mut sha = expected_sha1(f).map(|_| Sha1::new()); + let mut written: u64 = 0; + for part in &f.parts { + let guid = part.guid_str(); + let data = reader.read(&guid, &rel_path)?; + let start = usize::try_from(part.offset).map_err(|_| { + format!("Chunk {guid} part offset {} invalid for {rel_path}", part.offset) + })?; + let len = part.size as u32 as usize; + let end = start + .checked_add(len) + .filter(|&e| e <= data.len()) + .ok_or_else(|| { + format!( + "Chunk {guid} too short for {rel_path}: need {start}+{len}, have {}", + data.len() + ) + })?; + let slice = &data[start..end]; + out.write_all(slice).map_err(|e| format!("write {rel_path}: {e}"))?; + if let Some(sha) = sha.as_mut() { + sha.update(slice); + } + written += len as u64; + } + out.flush().map_err(|e| format!("flush {rel_path}: {e}"))?; + drop(out); + if let (Some(expected), Some(sha)) = (expected_sha1(f), sha) { + if sha.finalize().as_slice() != &expected[..] { + return Err(format!("SHA-1 mismatch for {rel_path}")); + } + } + Ok(written) + })(); + if result.is_err() { + let _ = fs::remove_file(out_path); + } + result +} + +/// Run the plan. `progress(bytes_done, bytes_total, files_done, files_total)` fires after every +/// file; `log` receives the start line, failures and the terminal summary. +pub fn run_assemble( + plan: &AssemblePlan, + cancel: &AtomicBool, + progress: &(dyn Fn(u64, u64, u64, u64) + Sync), + log: &(dyn Fn(&str) + Sync), +) -> AssembleOutcome { + let files_total = plan.files.len() as u64; + let mut outcome = AssembleOutcome { + files_total, + bytes_total: plan.bytes_total, + ..AssembleOutcome::default() + }; + log(&format!( + "assemble cache_dir={} scratch={} files={files_total} bytes={} chunks_referenced={}", + plan.cache_dir.display(), + plan.scratch_cache, + plan.bytes_total, + plan.refs.len() + )); + + let mut refs = plan.refs.clone(); + let mut reader = ChunkReader { + cache_dir: plan.cache_dir.clone(), + last: None, + }; + for &fi in &plan.files { + if cancel.load(Ordering::Relaxed) { + outcome.cancelled = true; + outcome.error = "cancelled".to_string(); + log(&format!( + "cancelled during assembly ({}/{files_total} files)", + outcome.files_done + )); + return outcome; + } + let f = &plan.manifest.files[fi]; + let out_path = plan.install_dir.join(relative_path(f)); + match write_file(&mut reader, f, &out_path) { + Ok(written) => outcome.bytes_written += written, + Err(err) => { + outcome.error = err; + log(&format!( + "FAIL {} ({}/{files_total} files ok)", + outcome.error, outcome.files_done + )); + return outcome; + } + } + outcome.files_done += 1; + progress( + outcome.bytes_written, + plan.bytes_total, + outcome.files_done, + files_total, + ); + // Scratch cache: this file was the last user of a chunk → the chunk goes now, not at the + // end, so the cache holds only what is still owed to files not yet written. + if plan.scratch_cache { + for guid in distinct_guids(f) { + let Some(count) = refs.get_mut(&guid) else { + continue; + }; + *count = count.saturating_sub(1); + if *count == 0 { + reader.forget(&guid); + if fs::remove_file(plan.cache_dir.join(&guid)).is_ok() { + outcome.chunks_removed += 1; + } + } + } + } + } + + outcome.success = true; + // Done with the cache: remove it whole (a scratch cache is already down to the chunks no + // pending file referenced; the default one is what the Kotlin loop deleted at this point). + match fs::remove_dir_all(&plan.cache_dir) { + Ok(()) => log(&format!("cache removed {}", plan.cache_dir.display())), + Err(e) => log(&format!( + "cache not removed {}: {e}", + plan.cache_dir.display() + )), + } + log(&format!( + "assembled files={} bytes={} chunks_removed_early={}", + outcome.files_done, outcome.bytes_written, outcome.chunks_removed + )); + outcome +} + +#[cfg(test)] +mod tests { + use super::super::chunk::test_support::temp_dir; + use super::super::manifest::test_support::*; + use super::*; + use std::sync::Mutex; + + const A: [u32; 4] = [1, 2, 3, 4]; + const B: [u32; 4] = [5, 6, 7, 8]; + + fn chunk_a() -> Vec { + (0..300u32).map(|i| (i % 251) as u8).collect() + } + + fn chunk_b() -> Vec { + (0..100u32).map(|i| (200 - i) as u8).collect() + } + + fn sha(bytes: &[u8]) -> [u8; 20] { + let mut out = [0u8; 20]; + out.copy_from_slice(&Sha1::digest(bytes)); + out + } + + /// file 0 = A[0..100] ++ B[10..60]; file 1 = A[100..300]. A is shared, B is file 0's alone. + fn expected_files() -> (Vec, Vec) { + let (a, b) = (chunk_a(), chunk_b()); + let mut f0 = a[0..100].to_vec(); + f0.extend_from_slice(&b[10..60]); + (f0, a[100..300].to_vec()) + } + + fn manifest_bytes(file0_sha: [u8; 20]) -> Vec { + let (_, f1) = expected_files(); + let chunks = vec![ + TestChunk { guid: A, hash: 1, sha1: [0x11; 20], group: 1, window: 300, file_size: 300 }, + TestChunk { guid: B, hash: 2, sha1: [0x22; 20], group: 2, window: 100, file_size: 100 }, + ]; + let files = vec![ + TestFile { + name: "Game\\Binaries\\Game.exe".to_string(), + sha1: file0_sha, + tags: vec![], + parts: vec![(A, 0, 100), (B, 10, 50)], + }, + TestFile { + name: "Game/Content/data.pak".to_string(), + sha1: sha(&f1), + tags: vec![], + parts: vec![(A, 100, 200)], + }, + ]; + build_manifest(&chunks, &files, 21, false) + } + + fn guid(g: [u32; 4]) -> String { + super::super::manifest::guid_to_string(&g) + } + + fn fill_cache(cache: &Path) { + fs::create_dir_all(cache).unwrap(); + fs::write(cache.join(guid(A)), chunk_a()).unwrap(); + fs::write(cache.join(guid(B)), chunk_b()).unwrap(); + } + + fn request(install: &Path, cache: &str) -> AssembleRequest { + let (f0, _) = expected_files(); + AssembleRequest { + manifest_bytes: manifest_bytes(sha(&f0)), + install_dir: install.to_str().unwrap().to_string(), + chunk_cache_dir: cache.to_string(), + file_indices: vec![0, 1], + } + } + + fn run(plan: &AssemblePlan, cancel: bool) -> (AssembleOutcome, Vec<(u64, u64, u64, u64)>) { + let calls = Mutex::new(Vec::new()); + let progress = |b: u64, bt: u64, f: u64, ft: u64| calls.lock().unwrap().push((b, bt, f, ft)); + let log = |_: &str| {}; + let out = run_assemble(plan, &AtomicBool::new(cancel), &progress, &log); + (out, calls.into_inner().unwrap()) + } + + #[test] + fn default_cache_assembles_like_the_kotlin_loop_and_removes_the_cache_at_the_end() { + let dir = temp_dir("asm-default"); + let install = dir.join("install"); + let cache = install.join(".chunks"); + fill_cache(&cache); + let plan = build_assemble_plan(&request(&install, "")).unwrap(); + assert!(!plan.scratch_cache); + assert_eq!(plan.refs[&guid(A)], 2); + assert_eq!(plan.refs[&guid(B)], 1); + let (out, calls) = run(&plan, false); + assert!(out.success, "{}", out.error); + let (f0, f1) = expected_files(); + assert_eq!(fs::read(install.join("Game/Binaries/Game.exe")).unwrap(), f0); + assert_eq!(fs::read(install.join("Game/Content/data.pak")).unwrap(), f1); + assert_eq!(out.bytes_written, 350); + assert_eq!(calls, vec![(150, 350, 1, 2), (350, 350, 2, 2)]); + assert_eq!(out.chunks_removed, 0, "no early deletion without a scratch cache"); + assert!(!cache.exists(), "the cache goes at the end, as the Kotlin loop's deleteDir"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn scratch_cache_frees_each_chunk_when_its_last_file_is_done() { + let dir = temp_dir("asm-scratch"); + let install = dir.join("install"); + let cache = dir.join("cache"); + fill_cache(&cache); + let plan = build_assemble_plan(&request(&install, cache.to_str().unwrap())).unwrap(); + assert!(plan.scratch_cache); + // After file 0: B (only file 0 used it) must be gone, A (file 1 still needs it) must stay. + let seen = Mutex::new(Vec::new()); + let progress = |_: u64, _: u64, files_done: u64, _: u64| { + if files_done == 1 { + seen.lock().unwrap().push((cache.join(guid(A)).exists(), cache.join(guid(B)).exists())); + } + }; + let log = |_: &str| {}; + let out = run_assemble(&plan, &AtomicBool::new(false), &progress, &log); + assert!(out.success, "{}", out.error); + assert_eq!(*seen.lock().unwrap(), vec![(true, false)]); + assert_eq!(out.chunks_removed, 2); + assert!(!cache.exists()); + let (f0, f1) = expected_files(); + assert_eq!(fs::read(install.join("Game/Binaries/Game.exe")).unwrap(), f0); + assert_eq!(fs::read(install.join("Game/Content/data.pak")).unwrap(), f1); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_missing_chunk_fails_with_the_kotlin_wording_and_leaves_the_cache() { + let dir = temp_dir("asm-missing"); + let install = dir.join("install"); + let cache = dir.join("cache"); + fill_cache(&cache); + fs::remove_file(cache.join(guid(B))).unwrap(); + let plan = build_assemble_plan(&request(&install, cache.to_str().unwrap())).unwrap(); + let (out, calls) = run(&plan, false); + assert!(!out.success && !out.cancelled); + assert_eq!(out.error, format!("Missing chunk {} for Game/Binaries/Game.exe", guid(B))); + assert!(calls.is_empty()); + assert!(!install.join("Game/Binaries/Game.exe").exists(), "no partial file survives"); + assert!(cache.join(guid(A)).exists(), "failure leaves the cache for the next run"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_sha1_mismatch_deletes_the_file_and_fails() { + let dir = temp_dir("asm-sha"); + let install = dir.join("install"); + let cache = dir.join("cache"); + fill_cache(&cache); + let mut req = request(&install, cache.to_str().unwrap()); + req.manifest_bytes = manifest_bytes([0x99; 20]); + let plan = build_assemble_plan(&req).unwrap(); + let (out, _) = run(&plan, false); + assert!(!out.success); + assert_eq!(out.error, "SHA-1 mismatch for Game/Binaries/Game.exe"); + assert!(!install.join("Game/Binaries/Game.exe").exists()); + assert!(cache.join(guid(B)).exists(), "nothing was freed for a file that failed"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_all_zero_manifest_hash_means_no_check() { + let dir = temp_dir("asm-nohash"); + let install = dir.join("install"); + let cache = install.join(".chunks"); + fill_cache(&cache); + let mut req = request(&install, ""); + req.manifest_bytes = manifest_bytes([0u8; 20]); + let plan = build_assemble_plan(&req).unwrap(); + let (out, _) = run(&plan, false); + assert!(out.success, "{}", out.error); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn cancel_before_the_first_file_writes_nothing_and_keeps_the_cache() { + let dir = temp_dir("asm-cancel"); + let install = dir.join("install"); + let cache = dir.join("cache"); + fill_cache(&cache); + let plan = build_assemble_plan(&request(&install, cache.to_str().unwrap())).unwrap(); + let (out, calls) = run(&plan, true); + assert!(out.cancelled && !out.success); + assert!(calls.is_empty()); + assert!(cache.join(guid(A)).exists() && cache.join(guid(B)).exists()); + assert!(!install.join("Game").exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn bad_inputs_fail_before_anything_is_written() { + let dir = temp_dir("asm-inputs"); + let mut req = request(&dir, ""); + req.file_indices = vec![0, 2]; + assert!(build_assemble_plan(&req).unwrap_err().contains("out of range")); + req.file_indices = vec![0]; + req.install_dir.clear(); + assert!(build_assemble_plan(&req).unwrap_err().contains("empty install dir")); + req.install_dir = dir.to_str().unwrap().to_string(); + req.manifest_bytes = vec![1, 2, 3]; + assert!(build_assemble_plan(&req).is_err()); + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/app/src/main/rust/stores/src/epic/driver.rs b/app/src/main/rust/stores/src/epic/driver.rs index 6740185fc..35e1f6a08 100644 --- a/app/src/main/rust/stores/src/epic/driver.rs +++ b/app/src/main/rust/stores/src/epic/driver.rs @@ -4,8 +4,9 @@ //! ("Download unique chunks — 8 parallel threads"). Inputs are exactly what that block sees: //! the parsed manifest (re-parsed here from the same bytes), the pending file set (indices Java //! computed after its delta/verify pass), the CDN prefixes (`baseUrl + cloudDir`, cloudflare -//! already skipped) and the chunk cache dir. Output = `/.chunks/` for every -//! needed chunk; Java assembles the files afterwards exactly as before. +//! already skipped) and the chunk cache dir. Output = `/` for every needed chunk, +//! where `` is `/.chunks` unless the caller named another directory; the +//! files are assembled from it afterwards (by the Kotlin manager, or by [`super::assemble`]). use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -16,7 +17,7 @@ use crate::fetch_core::{run_fetch, FetchItem, FetchOptions, FetchSink, SinkError use super::manifest::{parse_manifest, Manifest}; use super::plan::{ - cached_chunk_path, chunk_cache_dir, chunk_url, distinct_prefixes, per_host_cap, + cached_chunk_path, chunk_url, distinct_prefixes, per_host_cap, resolve_cache_dir, total_credit_bytes, unique_chunks_for_files, }; @@ -27,6 +28,8 @@ pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(60); pub struct EpicRequest { pub manifest_bytes: Vec, pub install_dir: String, + /// Chunk cache directory; `""` = `/.chunks`. See [`resolve_cache_dir`]. + pub chunk_cache_dir: String, /// `cdn.baseUrl + cdn.cloudDir` per manifest-API CDN entry, in Java's order. pub cdn_prefixes: Vec, /// Indices into `manifest.files` of Java's `pendingFiles` (post delta/verify), in order. @@ -47,6 +50,9 @@ pub struct EpicRequest { pub struct EpicPlan { pub manifest: Manifest, pub cache_dir: PathBuf, + /// The cache is a directory the caller named, apart from the install: scratch space that + /// the assembler empties as it goes and removes when it is done. + pub scratch_cache: bool, /// Chunk indices (into `manifest.unique_chunks`) in Java's submission order. pub needed: Vec, /// `Σ max(fileSize, 1)` over `needed`. @@ -105,12 +111,13 @@ pub fn build_plan(req: &EpicRequest) -> Result { if hosts.is_empty() { return Err("plan: no CDN prefixes".to_string()); } - let cache_dir = chunk_cache_dir(&req.install_dir); + let cache_dir = resolve_cache_dir(&req.install_dir, &req.chunk_cache_dir); std::fs::create_dir_all(&cache_dir) .map_err(|e| format!("plan: mkdirs {}: {e}", cache_dir.display()))?; Ok(EpicPlan { manifest, cache_dir, + scratch_cache: !req.chunk_cache_dir.is_empty(), needed, total_bytes, hosts, @@ -208,8 +215,10 @@ pub fn run_plan( }; let host_cap = per_host_cap(req.max_workers, plan.hosts.len()); log(&format!( - "plan chunk_dir={} files_pending={} chunks={} bytes={} hosts={} workers={} per_host_cap={host_cap} process_workers={}", + "plan chunk_dir={} cache_dir={} scratch={} files_pending={} chunks={} bytes={} hosts={} workers={} per_host_cap={host_cap} process_workers={}", plan.manifest.chunk_dir, + plan.cache_dir.display(), + plan.scratch_cache, req.pending_file_indices.len(), chunks_total, plan.total_bytes, @@ -368,6 +377,7 @@ mod tests { EpicRequest { manifest_bytes: build_manifest(&sample_chunks(), &sample_files(), 21, true), install_dir: dir.to_string(), + chunk_cache_dir: String::new(), cdn_prefixes: vec![ "https://fastly-download.epicgames.com/Builds/o/x/default".to_string(), "https://download.epicgames.com/Builds/o/x/default".to_string(), @@ -393,6 +403,20 @@ mod tests { assert_eq!(plan.hosts.len(), 2, "duplicate CDN prefix collapsed"); assert!(plan.cache_dir.ends_with(".chunks")); assert!(plan.cache_dir.is_dir()); + assert!(!plan.scratch_cache); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_named_cache_dir_is_created_and_marked_scratch() { + let dir = super::super::chunk::test_support::temp_dir("scratch"); + let cache = dir.join("cache").join("Game"); + let mut req = request(dir.join("install").to_str().unwrap(), vec![0, 1]); + req.chunk_cache_dir = cache.to_str().unwrap().to_string(); + let plan = build_plan(&req).unwrap(); + assert_eq!(plan.cache_dir, cache); + assert!(plan.cache_dir.is_dir()); + assert!(plan.scratch_cache); let _ = std::fs::remove_dir_all(&dir); } diff --git a/app/src/main/rust/stores/src/epic/jni.rs b/app/src/main/rust/stores/src/epic/jni.rs index 9f7cf2f52..903a17a97 100644 --- a/app/src/main/rust/stores/src/epic/jni.rs +++ b/app/src/main/rust/stores/src/epic/jni.rs @@ -1,16 +1,21 @@ //! JNI exports for `com.droiddeck.launcher.stores.epic.EpicNative`. //! //! ```text -//! nativeStart(manifest: byte[], installDir: String, cdnPrefixes: String[], pendingFileIdx: int[], -//! expectedChunks: int, expectedBytes: long, caBundlePath: String, maxWorkers: int, -//! processWorkers: int, listener: EpicNative.Listener) -> long handle (0 = not started) -//! nativeCancel(handle) — flips the run's AtomicBool; the fetch core stops promptly +//! nativeStart(manifest: byte[], installDir: String, chunkCacheDir: String, cdnPrefixes: String[], +//! pendingFileIdx: int[], expectedChunks: int, expectedBytes: long, +//! caBundlePath: String, maxWorkers: int, processWorkers: int, +//! listener: EpicNative.Listener) -> long handle (0 = not started) +//! nativeAssemble(manifest: byte[], installDir: String, chunkCacheDir: String, fileIdx: int[], +//! listener: EpicNative.Listener) -> long handle (0 = not started) +//! nativeCancel(handle) — flips the run's AtomicBool; fetch or assembly stops promptly //! nativeRelease(handle) — frees the handle (after onComplete) //! ``` -//! Listener (all methods run on native threads): +//! `chunkCacheDir` = "" keeps the cache at `/.chunks`; any other directory is a +//! scratch cache (see `assemble.rs`). Listener (all methods run on native threads): //! `onPlan(int chunksTotal, long bytesTotal, String chunkDir)` once before any fetch, -//! `onProgress(long bytesDone, long bytesTotal, int chunksDone, int chunksTotal)` per chunk, -//! `onLog(String line)`, `onComplete(boolean success, String error, long bytesCredited)`. +//! `onProgress(long bytesDone, long bytesTotal, int done, int total)` per chunk fetched (or, in +//! an assembly run, per file written), `onLog(String line)`, +//! `onComplete(boolean success, String error, long bytes)`. //! //! Planning (manifest parse + cross-check) runs synchronously on the calling thread so a plan //! failure returns 0 BEFORE any fetch and Java can fall back to its own pool; the fetch runs on @@ -24,6 +29,7 @@ use jni::objects::{GlobalRef, JByteArray, JClass, JIntArray, JObject, JObjectArr use jni::sys::{jint, jlong, JNI_FALSE, JNI_TRUE}; use jni::{JNIEnv, JavaVM}; +use super::assemble::{build_assemble_plan, run_assemble, AssembleRequest}; use super::driver::{build_plan, run_plan, EpicRequest}; #[cfg(target_os = "android")] @@ -53,7 +59,8 @@ fn android_log(message: &str) { } } -/// Per-run native state behind the `jlong` handle. +/// Per-run native state behind the `jlong` handle — the same type for a fetch run and an +/// assembly run, so one `nativeCancel` / `nativeRelease` pair serves both. pub struct EpicDownloadHandle { cancel: Arc, } @@ -205,6 +212,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native _class: JClass, manifest: JByteArray, install_dir: JString, + chunk_cache_dir: JString, cdn_prefixes: JObjectArray, pending_file_idx: JIntArray, expected_chunks: jint, @@ -224,6 +232,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native return 0; }; let install_dir = jstring_to_string(&mut env, &install_dir).unwrap_or_default(); + let chunk_cache_dir = jstring_to_string(&mut env, &chunk_cache_dir).unwrap_or_default(); let cdn_prefixes = string_array_to_vec(&mut env, &cdn_prefixes); let pending_file_indices: Vec = int_array_to_vec(&env, &pending_file_idx) .into_iter() @@ -246,7 +255,8 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native &mut env, &listener, &format!( - "engine=rust label=\"{label}\" install_dir={install_dir} cdns={} hosts={host_count} pending_files={} workers={max_workers} per_host_cap={host_cap} process_workers={process_workers} manifest_bytes={}", + "engine=rust label=\"{label}\" install_dir={install_dir} cache_dir={} cdns={} hosts={host_count} pending_files={} workers={max_workers} per_host_cap={host_cap} process_workers={process_workers} manifest_bytes={}", + if chunk_cache_dir.is_empty() { "/.chunks" } else { chunk_cache_dir.as_str() }, cdn_prefixes.len(), pending_file_indices.len(), manifest_bytes.len() @@ -256,6 +266,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native let req = EpicRequest { manifest_bytes, install_dir, + chunk_cache_dir, cdn_prefixes, pending_file_indices, expected_chunks: if expected_chunks >= 0 { @@ -359,6 +370,92 @@ fn run_on_thread( ); } +/// `EpicNative.nativeAssemble(manifest, installDir, chunkCacheDir, fileIdx, listener)`: write +/// the files `fileIdx` names from the chunk cache (see `assemble.rs`). Parse + plan run on the +/// calling thread, so bad inputs return 0 (after `onComplete(false, reason, 0)`) before anything +/// is written; the assembly runs on a new thread and reports per file through `onProgress(bytes, +/// bytesTotal, filesDone, filesTotal)`, then `onComplete(success, error, bytesWritten)`. +#[no_mangle] +pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeAssemble( + mut env: JNIEnv, + _class: JClass, + manifest: JByteArray, + install_dir: JString, + chunk_cache_dir: JString, + file_idx: JIntArray, + listener: JObject, +) -> jlong { + if listener.is_null() { + android_log("nativeAssemble: null listener"); + return 0; + } + let Ok(manifest_bytes) = env.convert_byte_array(manifest) else { + clear_pending_exception(&mut env); + call_on_complete(&mut env, &listener, false, "manifest bytes unreadable", 0); + return 0; + }; + let req = AssembleRequest { + manifest_bytes, + install_dir: jstring_to_string(&mut env, &install_dir).unwrap_or_default(), + chunk_cache_dir: jstring_to_string(&mut env, &chunk_cache_dir).unwrap_or_default(), + file_indices: int_array_to_vec(&env, &file_idx) + .into_iter() + .map(|i| i.max(0) as usize) + .collect(), + }; + let plan = match build_assemble_plan(&req) { + Ok(plan) => plan, + Err(err) => { + log_both(&mut env, &listener, &format!("not started: {err}")); + call_on_complete(&mut env, &listener, false, &err, 0); + return 0; + } + }; + let Ok(vm) = env.get_java_vm() else { + clear_pending_exception(&mut env); + call_on_complete(&mut env, &listener, false, "JavaVM unavailable", 0); + return 0; + }; + let Ok(listener) = env.new_global_ref(&listener) else { + clear_pending_exception(&mut env); + call_on_complete(&mut env, &listener, false, "listener ref failed", 0); + return 0; + }; + + let cancel = Arc::new(AtomicBool::new(false)); + let thread_cancel = Arc::clone(&cancel); + let handle = Box::new(EpicDownloadHandle { cancel }); + + thread::spawn(move || { + let progress = |bytes_done: u64, bytes_total: u64, files_done: u64, files_total: u64| { + let Ok(mut env) = vm.attach_current_thread_as_daemon() else { + return; + }; + call_on_progress(&mut env, listener.as_obj(), bytes_done, bytes_total, files_done, files_total); + }; + let log = |line: &str| { + android_log(line); + let Ok(mut env) = vm.attach_current_thread_as_daemon() else { + return; + }; + call_on_log(&mut env, listener.as_obj(), line); + }; + let outcome = run_assemble(&plan, thread_cancel.as_ref(), &progress, &log); + let Ok(mut env) = vm.attach_current_thread_as_daemon() else { + return; + }; + call_on_complete( + &mut env, + listener.as_obj(), + outcome.success, + &outcome.error, + outcome.bytes_written, + ); + }); + + Box::into_raw(handle) as jlong +} + #[no_mangle] pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeCancel( _env: JNIEnv, diff --git a/app/src/main/rust/stores/src/epic/plan.rs b/app/src/main/rust/stores/src/epic/plan.rs index 49b70d80f..0c93358de 100644 --- a/app/src/main/rust/stores/src/epic/plan.rs +++ b/app/src/main/rust/stores/src/epic/plan.rs @@ -95,6 +95,18 @@ pub fn chunk_cache_dir(install_dir: &str) -> PathBuf { Path::new(install_dir).join(super::CHUNK_CACHE_DIR) } +/// Where this run's chunks go: `chunk_cache_dir` when the caller named one, else the default +/// `/.chunks`. A separate directory exists so the cache can sit on internal storage +/// while the game installs to an SD card: a chunk is written once into the cache and once into +/// the assembled file, and with both on a 26 MB/s card the second write starved the fetchers. +pub fn resolve_cache_dir(install_dir: &str, chunk_cache_dir: &str) -> PathBuf { + if chunk_cache_dir.is_empty() { + chunk_cache_dir(install_dir) + } else { + PathBuf::from(chunk_cache_dir) + } +} + /// Final cache file for a chunk: `new File(chunkCacheDir, chunk.guidStr())`. pub fn cached_chunk_path(cache_dir: &Path, chunk: &ChunkInfo) -> PathBuf { cache_dir.join(chunk.guid_str()) @@ -229,6 +241,11 @@ mod tests { ); let cache = chunk_cache_dir("/data/x/imagefs/epic_games/Game"); assert_eq!(cache, PathBuf::from("/data/x/imagefs/epic_games/Game/.chunks")); + assert_eq!(resolve_cache_dir("/data/x/imagefs/epic_games/Game", ""), cache); + assert_eq!( + resolve_cache_dir("/sdcard/Games/Game", "/data/x/cache/epic/Game"), + PathBuf::from("/data/x/cache/epic/Game") + ); assert_eq!( cached_chunk_path(&cache, c), PathBuf::from("/data/x/imagefs/epic_games/Game/.chunks/00000001000000020000000300000004")