mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-23 06:46:02 +00:00
Improve store install storage checks and recovery; adaptive parallel Epic installs (#710)
Space checks before Epic, GOG and Amazon installs (measured zero vs unknown), clear failure reasons with retry/clear, resume-aware checks, and safe per-file replacement so a failed or cancelled update never breaks an installed game. Epic installs stream chunks straight into staged files in parallel (most bytes written once, a small budgeted cache for shared chunks, about 1x game size instead of 2x), pace updates by free space, and keep the lookahead, batch and bounded Java writers as hidden alternatives. Co-authored-by: Juan Marti Mercado <juanma@microsoft.com> Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
This commit is contained in:
1 parent
d310e59fce
commit
a074ba994b
34 files changed
+6777
-233
No files matched your search
@@ -112,7 +112,45 @@ On-disk protocol (what a resumed run, by either engine, relies on): a file is as
|
||||
|
||||
## `com.droiddeck.launcher.stores.epic.EpicNative`
|
||||
|
||||
Two runs make up the native half of an Epic install:
|
||||
The manager's default Epic install is the **stream** run (`nativeStream`, mode `adaptive`,
|
||||
below): the chunks are fetched in parallel and written straight into staged files as they arrive;
|
||||
on device it measured about 83 MB/s on a 71 GB install. The **lookahead** install
|
||||
(`nativeInstallAdaptive`, mode `lookahead`) is its fallback when the stream engine's space plan
|
||||
does not fit, and is selectable directly, as is the legacy batch pair (`nativeStart` +
|
||||
`nativeAssemble`, mode `batch`), through the hidden `storesEpicMode` preference.
|
||||
|
||||
### Lookahead install (snapshot schema v1)
|
||||
|
||||
`nativeInstallAdaptive(request: String, listener: EpicNative.Listener): Long`
|
||||
exports `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeInstallAdaptive`.
|
||||
Its exact Kotlin descriptor is
|
||||
`(Ljava/lang/String;Lcom/droiddeck/launcher/stores/epic/EpicNative$Listener;)J`.
|
||||
The listener must also implement `EpicNative.InstallListener.beforeSwap(): Boolean` (`()Z`).
|
||||
Rust invokes it synchronously after staging/hash/sync and before the first atomic replacement;
|
||||
false or a Java exception aborts without replacing that output. Java marks the sidecar updating
|
||||
there. Later verified swaps preserve mixed-update/resume semantics.
|
||||
|
||||
The UTF-8 JSON request contains:
|
||||
|
||||
- `schema_version: 1`, absolute `install_dir`, `cache_dir`, owned `staging_dir`,
|
||||
`same_volume`, signed `free_game`/`free_cache` (`-1` unknown), `max_workers`, CDN `hosts`.
|
||||
- `chunks`: distinct `guid`, relative CDN `path`, decoded `size`, `exact_size`, `wire_size`,
|
||||
SHA-1 hex `sha1` (empty/all-zero means absent), `cached` verified length (`-1` absent).
|
||||
- `files`: pending manifest-order relative `path`, `sha1`, current `old_size`, ordered `parts`
|
||||
containing `guid`, unsigned `offset` and `size`.
|
||||
|
||||
Parse, owned-namespace validation and adaptive storage planning happen synchronously. Errors
|
||||
return zero after `onComplete(false, error, 0)` and are **terminal**, not fallback signals.
|
||||
`onPlan` reports the selected lookahead/retention/peaks; `onProgress` counts staged file bytes
|
||||
and verified swapped file counts, not fetched wire bytes. Fetch and staged assembly overlap
|
||||
in one native run, using the same pure reservation/release policy as the peak planner.
|
||||
Cancellation/release joins native workers; no worker survives the terminal callback/handle
|
||||
release. Only `StoresNative.ensureLoaded() == false` selects bounded parallel Java; the same rule
|
||||
holds for `nativeStream`.
|
||||
|
||||
### Legacy batch APIs (mode `batch`, for A/B runs)
|
||||
|
||||
Two explicit calls provide the legacy batch interface:
|
||||
|
||||
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
|
||||
@@ -224,6 +262,57 @@ Bannerlator's `BlEpicDownload.run(...)` wraps `nativeStart` in a blocking call t
|
||||
`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).
|
||||
|
||||
### `nativeStream` — the adaptive install
|
||||
|
||||
| Method | JNI signature | Symbol |
|
||||
|---|---|---|
|
||||
| `nativeStream(...)`: Long | `([BLjava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;[IJJJLjava/lang/String;IILcom/droiddeck/launcher/stores/epic/EpicNative$StreamListener;)J` | `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStream` |
|
||||
|
||||
```kotlin
|
||||
@JvmStatic private external fun nativeStream(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, stagingDir: String,
|
||||
cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedBytes: Long, cacheBudget: Long,
|
||||
overlapBudget: Long, caBundlePath: String,
|
||||
maxWorkers: Int, processWorkers: Int, listener: StreamListener,
|
||||
): Long
|
||||
```
|
||||
|
||||
Parameters as `nativeStart`, plus `stagingDir` (the manager's owned
|
||||
`<installDir>/.droiddeck-epic-staging`, which must exist; `""` = stage beside each file), and
|
||||
except `expectedBytes` (the manager's `Σ fileSize` of the pending
|
||||
files, `-1` = no cross-check; no chunk count) and `cacheBudget` (the most bytes of shared chunks
|
||||
the cache may hold; the manager sizes it from free space, `0` = never cache, refetch instead) and
|
||||
`overlapBudget` (the most planned bytes of *replaced* files - destination already holds data -
|
||||
staged at once, since each sits beside its old copy until its swap; one is always allowed so the
|
||||
run progresses; `-1` = no limit). Files are admitted in order and a chunk is dispatched only once
|
||||
the file of its first use is admitted; fresh files are never held back.
|
||||
`chunkCacheDir` is `""` (`<installDir>/.chunks`) or a scratch directory; the manager falls back to
|
||||
`""` for a card install when internal storage cannot hold the budget.
|
||||
|
||||
What the run does (`epic/stream.rs`): a chunk one file part uses is decompressed, verified and
|
||||
written at the part's offset into a unique `stream-*.stage` file in `stagingDir`; a
|
||||
chunk several parts use is also kept in the cache, decompressed, as `<GUID>` (a later copy after
|
||||
an eviction as `<GUID>.<n>`) and deleted after its last covered part. The plan evicts by furthest
|
||||
next use when the budget would be exceeded and fetches the evicted chunk again later. Each file,
|
||||
once complete: synced, size and SHA-1 checked, `onBeforeReplace()` once for the whole run, then
|
||||
renamed over its destination. Cancel or failure removes every unfinished stage file before
|
||||
`onComplete`, leaves the destinations and the cache; success removes the cache directory.
|
||||
|
||||
Planning runs on the calling thread and also prepares the cache (keeps verified chunks this
|
||||
install needs, deletes everything else, as the Java writer does). A refusal returns `0` after a
|
||||
synchronous `onComplete(false, reason, 0)`; nothing was fetched or written, and the manager fails
|
||||
the install with that reason (it does not switch engines once the library is loaded).
|
||||
|
||||
| `StreamListener` method | JNI signature | When |
|
||||
|---|---|---|
|
||||
| `onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long)` | `(JJIIJ)V` | after written parts (at most every 50 ms) and after every finished file; `filesBytes` = sizes of the files swapped in |
|
||||
| `onLog(line: String)` | `(Ljava/lang/String;)V` | engine lines: `stream-plan …`, the fetch core's lines, `stream-summary mode=adaptive …` (peak cache, peak staging, refetches, direct vs cached bytes) |
|
||||
| `onBeforeReplace(): Boolean` | `()Z` | once, before the first file replaces its destination; `false` or a throw fails the run with nothing replaced |
|
||||
| `onComplete(success: Boolean, error: String, bytes: Long)` | `(ZLjava/lang/String;J)V` | terminal, exactly once; `bytes` = file bytes written; `error` = `"cancelled"` on cancel |
|
||||
|
||||
Unlike the batch runs, the Kotlin wrapper (`EpicNative.stream`) waits for `onComplete` after a
|
||||
cancel without a time limit: the stage-file cleanup must be finished before the manager returns.
|
||||
|
||||
## `com.droiddeck.launcher.stores.amazon.AmazonNative`
|
||||
|
||||
The file-fetch pool of an Amazon Games install: one streamed HTTP GET per manifest file, SHA-256
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
//! Derived from GameNative's Epic manager (itself derived from Legendary); both are GPL-3.0 and this crate carries the same licence (see Cargo.toml).
|
||||
|
||||
pub mod assemble;
|
||||
pub mod adaptive;
|
||||
pub mod chunk;
|
||||
pub mod driver;
|
||||
pub mod jni;
|
||||
pub mod manifest;
|
||||
pub mod plan;
|
||||
pub mod stream;
|
||||
|
||||
pub const USER_AGENT: &str =
|
||||
"UELauncher/11.0.1-14907503+++Portal+Release-Live Windows/10.0.19041.1.256.64bit";
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
@@ -10,6 +10,33 @@ use sha1::{Digest, Sha1};
|
||||
use super::manifest::{parse_manifest, FileInfo, Manifest};
|
||||
use super::plan::resolve_cache_dir;
|
||||
|
||||
/// Streaming assembly primitive used by the budgeted installer; never holds a decoded chunk
|
||||
/// in memory and closes the reader before the caller releases the cache reservation.
|
||||
pub fn copy_chunk_part(
|
||||
cache_path: &Path, offset: u64, size: u64, output: &mut impl Write,
|
||||
sha: &mut Sha1, cancel: &AtomicBool,
|
||||
) -> Result<u64, String> {
|
||||
let mut input = File::open(cache_path).map_err(|e| format!("read chunk: {e}"))?;
|
||||
let length = input.metadata().map_err(|e| e.to_string())?.len();
|
||||
if offset.checked_add(size).filter(|end| *end <= length).is_none() {
|
||||
return Err("chunk part exceeds cached data".into());
|
||||
}
|
||||
input.seek(SeekFrom::Start(offset)).map_err(|e| e.to_string())?;
|
||||
let mut left = size;
|
||||
let mut buffer = [0u8; 64 * 1024];
|
||||
while left > 0 {
|
||||
if cancel.load(Ordering::Acquire) { return Err("cancelled".into()); }
|
||||
let take = left.min(buffer.len() as u64) as usize;
|
||||
let count = input.read(&mut buffer[..take])
|
||||
.map_err(|e| e.to_string())?;
|
||||
if count == 0 { return Err("short cached chunk".into()); }
|
||||
output.write_all(&buffer[..count]).map_err(|e| e.to_string())?;
|
||||
sha.update(&buffer[..count]);
|
||||
left -= count as u64;
|
||||
}
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
pub struct AssembleRequest {
|
||||
pub manifest_bytes: Vec<u8>,
|
||||
pub install_dir: String,
|
||||
|
||||
@@ -71,10 +71,14 @@ struct HashingWriter<W: Write> {
|
||||
inner: W,
|
||||
sha: Option<Sha1>,
|
||||
written: u64,
|
||||
limit: u64,
|
||||
}
|
||||
|
||||
impl<W: Write> Write for HashingWriter<W> {
|
||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||
if self.written.saturating_add(buf.len() as u64) > self.limit {
|
||||
return Err(io::Error::other("chunk exceeds reserved decoded window"));
|
||||
}
|
||||
let n = self.inner.write(buf)?;
|
||||
if let Some(sha) = self.sha.as_mut() {
|
||||
sha.update(&buf[..n]);
|
||||
@@ -102,10 +106,21 @@ pub fn write_verified_chunk(
|
||||
let tmp = part_path(final_path);
|
||||
let _ = fs::remove_file(&tmp);
|
||||
|
||||
let result = write_part(body, expected_sha1, &tmp, final_path);
|
||||
let result = write_part(body, expected_sha1, &tmp, final_path, u64::MAX, false);
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
pub fn write_verified_chunk_bounded(
|
||||
body: &[u8], expected_sha1: Option<&[u8; 20]>, final_path: &Path,
|
||||
decoded_limit: u64, exact_size: bool,
|
||||
) -> Result<u64, String> {
|
||||
let tmp = part_path(final_path);
|
||||
let result = write_part(body, expected_sha1, &tmp, final_path, decoded_limit, exact_size);
|
||||
if result.is_err() { let _ = fs::remove_file(tmp); }
|
||||
result
|
||||
}
|
||||
|
||||
@@ -114,20 +129,43 @@ fn write_part(
|
||||
expected_sha1: Option<&[u8; 20]>,
|
||||
tmp: &Path,
|
||||
final_path: &Path,
|
||||
limit: u64,
|
||||
exact_size: bool,
|
||||
) -> Result<u64, String> {
|
||||
let hdr = parse_chunk_header(body)?;
|
||||
let payload = chunk_payload(body, &hdr)?;
|
||||
if limit != u64::MAX && (hdr.compressed_size < 0 || payload.len() != hdr.compressed_size as usize) {
|
||||
return Err("truncated chunk body".into());
|
||||
}
|
||||
|
||||
let file = File::create(tmp).map_err(|e| format!("open {}: {e}", tmp.display()))?;
|
||||
let mut out = HashingWriter {
|
||||
inner: BufWriter::with_capacity(128 * 1024, file),
|
||||
sha: expected_sha1.map(|_| Sha1::new()),
|
||||
written: 0,
|
||||
limit,
|
||||
};
|
||||
|
||||
if hdr.is_compressed() {
|
||||
let mut dec = flate2::read::ZlibDecoder::new(payload);
|
||||
io::copy(&mut dec, &mut out).map_err(|e| format!("inflate: {e}"))?;
|
||||
if limit == u64::MAX {
|
||||
let mut dec = flate2::read::ZlibDecoder::new(payload);
|
||||
io::copy(&mut dec, &mut out).map_err(|e| format!("inflate: {e}"))?;
|
||||
} else {
|
||||
let mut dec = flate2::Decompress::new(true);
|
||||
let mut buffer = [0u8; 128 * 1024];
|
||||
loop {
|
||||
let input = dec.total_in() as usize;
|
||||
let before = dec.total_out();
|
||||
let status = dec.decompress(&payload[input..], &mut buffer, flate2::FlushDecompress::None)
|
||||
.map_err(|e| format!("inflate: {e}"))?;
|
||||
let count = (dec.total_out() - before) as usize;
|
||||
out.write_all(&buffer[..count]).map_err(|e| format!("inflate write: {e}"))?;
|
||||
if status == flate2::Status::StreamEnd { break; }
|
||||
if count == 0 && dec.total_in() as usize == input {
|
||||
return Err("truncated compressed Epic chunk".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
out.write_all(payload).map_err(|e| format!("write: {e}"))?;
|
||||
}
|
||||
@@ -135,6 +173,9 @@ fn write_part(
|
||||
let written = out.written;
|
||||
let digest = out.sha.take().map(|s| s.finalize());
|
||||
drop(out);
|
||||
if exact_size && written != limit {
|
||||
return Err("chunk decoded size mismatch".into());
|
||||
}
|
||||
|
||||
if let (Some(expected), Some(actual)) = (expected_sha1, digest) {
|
||||
if actual.as_slice() != &expected[..] {
|
||||
@@ -146,6 +187,80 @@ fn write_part(
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// The window a chunk decompresses to: the manifest's, or 1 MiB for a legacy JSON manifest that
|
||||
/// names none (`EpicDownloadManager.chunkWindowSize`). The streaming installer also plans its
|
||||
/// shared-chunk cache with this size.
|
||||
pub fn chunk_window_bytes(window_size: i32) -> u64 {
|
||||
if window_size > 0 {
|
||||
window_size as u64
|
||||
} else {
|
||||
1024 * 1024
|
||||
}
|
||||
}
|
||||
|
||||
/// One downloaded body → the verified, decompressed chunk in memory, for the streaming installer
|
||||
/// (`stream.rs`), which writes most chunks straight into the files that use them and never puts
|
||||
/// them in a cache. The checks are the bounded Java writer's (`downloadChunkStreaming`), which is
|
||||
/// stricter than [`write_verified_chunk`]: a stored payload shorter than `compressedSize` is
|
||||
/// truncated, a zlib stream must reach its end, the output may not grow past the chunk's window
|
||||
/// and must fill it exactly when the manifest names one, and the SHA-1 must match when the
|
||||
/// manifest has one. `Err` = "try another CDN", exactly like a cache write that failed.
|
||||
pub fn decode_verified_chunk(
|
||||
body: &[u8],
|
||||
window_size: i32,
|
||||
expected_sha1: Option<&[u8; 20]>,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
let hdr = parse_chunk_header(body)?;
|
||||
let start = hdr.payload_start();
|
||||
if start > body.len() {
|
||||
return Err("Stream ended during skip".to_string());
|
||||
}
|
||||
let want = if hdr.compressed_size <= 0 {
|
||||
0
|
||||
} else {
|
||||
hdr.compressed_size as usize
|
||||
};
|
||||
let avail = body.len() - start;
|
||||
let cap = chunk_window_bytes(window_size) as usize;
|
||||
let out = if hdr.is_compressed() {
|
||||
// Java stops reading once the inflater finishes, so a body may carry less than
|
||||
// `compressedSize` as long as the stream itself is complete.
|
||||
let payload = &body[start..start + want.min(avail)];
|
||||
let mut out: Vec<u8> = Vec::with_capacity(cap + 1);
|
||||
let mut inflater = flate2::Decompress::new(true);
|
||||
let status = inflater
|
||||
.decompress_vec(payload, &mut out, flate2::FlushDecompress::Finish)
|
||||
.map_err(|e| format!("inflate: {e}"))?;
|
||||
if out.len() > cap {
|
||||
return Err("chunk exceeds expected window size".to_string());
|
||||
}
|
||||
if status != flate2::Status::StreamEnd {
|
||||
return Err("truncated compressed Epic chunk".to_string());
|
||||
}
|
||||
out
|
||||
} else {
|
||||
if avail < want {
|
||||
return Err("truncated Epic chunk".to_string());
|
||||
}
|
||||
if want > cap {
|
||||
return Err("chunk exceeds expected window size".to_string());
|
||||
}
|
||||
body[start..start + want].to_vec()
|
||||
};
|
||||
if window_size > 0 && out.len() != window_size as usize {
|
||||
return Err(format!(
|
||||
"chunk is {} bytes, window is {window_size}",
|
||||
out.len()
|
||||
));
|
||||
}
|
||||
if let Some(expected) = expected_sha1 {
|
||||
if Sha1::digest(&out).as_slice() != &expected[..] {
|
||||
return Err("Chunk SHA-1 mismatch (streaming)".to_string());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod test_support {
|
||||
use super::*;
|
||||
@@ -326,6 +441,29 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decode_in_memory_applies_the_bounded_writer_checks() {
|
||||
let data = sample_data();
|
||||
let window = data.len() as i32;
|
||||
let sha = sha1_of(&data);
|
||||
let zipped = build_chunk_body(&data, true, 2, None);
|
||||
assert_eq!(decode_verified_chunk(&zipped, window, Some(&sha)).unwrap(), data);
|
||||
let stored = build_chunk_body(&data, false, 0, None);
|
||||
assert_eq!(decode_verified_chunk(&stored, window, Some(&sha)).unwrap(), data);
|
||||
// No window and no hash (legacy JSON manifest): accepted up to 1 MiB.
|
||||
assert_eq!(decode_verified_chunk(&zipped, 0, None).unwrap(), data);
|
||||
// Window mismatch, SHA-1 mismatch, truncation, oversize.
|
||||
assert!(decode_verified_chunk(&zipped, window + 1, None).is_err());
|
||||
let err = decode_verified_chunk(&zipped, window, Some(&[7; 20])).unwrap_err();
|
||||
assert!(err.contains("SHA-1 mismatch"), "{err}");
|
||||
let cut = zipped.len() - 500;
|
||||
assert!(decode_verified_chunk(&zipped[..cut], window, None).is_err());
|
||||
assert!(decode_verified_chunk(&stored[..stored.len() - 1], 0, None)
|
||||
.unwrap_err()
|
||||
.contains("truncated"));
|
||||
assert!(decode_verified_chunk(&zipped, window - 1, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_part_file_is_cleared_before_the_attempt() {
|
||||
let dir = temp_dir("stale");
|
||||
|
||||
@@ -9,6 +9,7 @@ use jni::{JNIEnv, JavaVM};
|
||||
|
||||
use super::assemble::{build_assemble_plan, run_assemble, AssembleRequest};
|
||||
use super::driver::{build_plan, run_plan, EpicRequest};
|
||||
use super::stream::{build_stream_plan, run_stream, Hooks, StreamProgress, StreamRequest};
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
#[link(name = "log")]
|
||||
@@ -39,6 +40,7 @@ fn android_log(message: &str) {
|
||||
|
||||
pub struct EpicDownloadHandle {
|
||||
cancel: Arc<AtomicBool>,
|
||||
worker: Option<thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
fn clear_pending_exception(env: &mut JNIEnv) {
|
||||
@@ -289,12 +291,11 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native
|
||||
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let thread_cancel = Arc::clone(&cancel);
|
||||
let handle = Box::new(EpicDownloadHandle { cancel });
|
||||
|
||||
thread::spawn(move || {
|
||||
let worker = thread::spawn(move || {
|
||||
crate::priority::background();
|
||||
run_on_thread(vm, listener, plan, req, thread_cancel);
|
||||
});
|
||||
let handle = Box::new(EpicDownloadHandle { cancel, worker: Some(worker) });
|
||||
|
||||
Box::into_raw(handle) as jlong
|
||||
}
|
||||
@@ -393,9 +394,7 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native
|
||||
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let thread_cancel = Arc::clone(&cancel);
|
||||
let handle = Box::new(EpicDownloadHandle { cancel });
|
||||
|
||||
thread::spawn(move || {
|
||||
let worker = thread::spawn(move || {
|
||||
crate::priority::background();
|
||||
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 {
|
||||
@@ -422,6 +421,194 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native
|
||||
outcome.bytes_written,
|
||||
);
|
||||
});
|
||||
let handle = Box::new(EpicDownloadHandle { cancel, worker: Some(worker) });
|
||||
|
||||
Box::into_raw(handle) as jlong
|
||||
}
|
||||
|
||||
fn call_on_stream_progress(env: &mut JNIEnv, listener: &JObject, p: &StreamProgress) {
|
||||
if listener.is_null() {
|
||||
return;
|
||||
}
|
||||
let _ = env.call_method(
|
||||
listener,
|
||||
"onStreamProgress",
|
||||
"(JJIIJ)V",
|
||||
&[
|
||||
JValue::Long(p.bytes_written as jlong),
|
||||
JValue::Long(p.bytes_total as jlong),
|
||||
JValue::Int(p.files_done.min(i32::MAX as u64) as jint),
|
||||
JValue::Int(p.files_total.min(i32::MAX as u64) as jint),
|
||||
JValue::Long(p.files_bytes as jlong),
|
||||
],
|
||||
);
|
||||
clear_pending_exception(env);
|
||||
}
|
||||
|
||||
/// `boolean onBeforeReplace()`: the Java side marks an existing install `updating`. A thrown
|
||||
/// exception or `false` is a refusal.
|
||||
fn call_on_before_replace(env: &mut JNIEnv, listener: &JObject) -> Result<(), String> {
|
||||
if listener.is_null() {
|
||||
return Ok(());
|
||||
}
|
||||
let result = env
|
||||
.call_method(listener, "onBeforeReplace", "()Z", &[])
|
||||
.and_then(|v| v.z());
|
||||
let threw = env.exception_check().unwrap_or(false);
|
||||
clear_pending_exception(env);
|
||||
match result {
|
||||
Ok(true) if !threw => Ok(()),
|
||||
_ => Err("could not mark the install as updating".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `EpicNative.nativeStream(...)`: the adaptive install (see `stream.rs`). Parse, plan and cache
|
||||
/// preparation run on the calling thread, so a refusal returns 0 (after a synchronous
|
||||
/// `onComplete(false, reason, 0)`) before anything is fetched or written, and the manager runs
|
||||
/// the bounded Java writer instead. The run itself is on a new thread; `onComplete` fires after
|
||||
/// every unfinished staging file of a cancelled or failed run is gone.
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStream(
|
||||
mut env: JNIEnv,
|
||||
_class: JClass,
|
||||
manifest: JByteArray,
|
||||
install_dir: JString,
|
||||
chunk_cache_dir: JString,
|
||||
staging_dir: JString,
|
||||
cdn_prefixes: JObjectArray,
|
||||
pending_file_idx: JIntArray,
|
||||
expected_bytes: jlong,
|
||||
cache_budget: jlong,
|
||||
overlap_budget: jlong,
|
||||
ca_bundle_path: JString,
|
||||
max_workers: jint,
|
||||
process_workers: jint,
|
||||
listener: JObject,
|
||||
) -> jlong {
|
||||
if listener.is_null() {
|
||||
android_log("nativeStream: 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 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 staging_dir = jstring_to_string(&mut env, &staging_dir).unwrap_or_default();
|
||||
let cdn_prefixes = string_array_to_vec(&mut env, &cdn_prefixes);
|
||||
let pending_file_indices: Vec<usize> = int_array_to_vec(&env, &pending_file_idx)
|
||||
.into_iter()
|
||||
.map(|i| i.max(0) as usize)
|
||||
.collect();
|
||||
let ca_bundle_path = jstring_to_string(&mut env, &ca_bundle_path).unwrap_or_default();
|
||||
let max_workers = max_workers.max(1) as usize;
|
||||
let process_workers = process_workers.max(1) as usize;
|
||||
let label = {
|
||||
let base = std::path::Path::new(&install_dir)
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
format!("epic app={base}")
|
||||
};
|
||||
log_both(
|
||||
&mut env,
|
||||
&listener,
|
||||
&format!(
|
||||
"engine=rust-stream label=\"{label}\" install_dir={install_dir} cache_dir={} cdns={} pending_files={} cache_budget={} workers={max_workers} process_workers={process_workers} manifest_bytes={}",
|
||||
if chunk_cache_dir.is_empty() { "<installDir>/.chunks" } else { chunk_cache_dir.as_str() },
|
||||
cdn_prefixes.len(),
|
||||
pending_file_indices.len(),
|
||||
cache_budget.max(0),
|
||||
manifest_bytes.len()
|
||||
),
|
||||
);
|
||||
|
||||
let req = StreamRequest {
|
||||
manifest_bytes,
|
||||
install_dir,
|
||||
chunk_cache_dir,
|
||||
staging_dir,
|
||||
cdn_prefixes,
|
||||
pending_file_indices,
|
||||
expected_bytes: if expected_bytes >= 0 {
|
||||
Some(expected_bytes as u64)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
cache_budget: cache_budget.max(0) as u64,
|
||||
// Negative = no limit (nothing the manager knows of is being replaced).
|
||||
replace_overlap_budget: if overlap_budget < 0 {
|
||||
u64::MAX
|
||||
} else {
|
||||
overlap_budget as u64
|
||||
},
|
||||
ca_bundle_path,
|
||||
max_workers,
|
||||
process_workers,
|
||||
label,
|
||||
};
|
||||
let plan = match build_stream_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 worker = thread::spawn(move || {
|
||||
crate::priority::background();
|
||||
let progress = |p: &StreamProgress| {
|
||||
let Ok(mut env) = vm.attach_current_thread_as_daemon() else {
|
||||
return;
|
||||
};
|
||||
call_on_stream_progress(&mut env, listener.as_obj(), p);
|
||||
};
|
||||
let before_replace = || {
|
||||
let Ok(mut env) = vm.attach_current_thread_as_daemon() else {
|
||||
return Err("JavaVM attach failed".to_string());
|
||||
};
|
||||
call_on_before_replace(&mut env, listener.as_obj())
|
||||
};
|
||||
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 hooks = Hooks {
|
||||
progress: &progress,
|
||||
before_replace: &before_replace,
|
||||
log: &log,
|
||||
};
|
||||
let outcome = run_stream(&plan, &req, thread_cancel.as_ref(), &hooks);
|
||||
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,
|
||||
);
|
||||
});
|
||||
let handle = Box::new(EpicDownloadHandle { cancel, worker: Some(worker) });
|
||||
|
||||
Box::into_raw(handle) as jlong
|
||||
}
|
||||
@@ -449,5 +636,73 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native
|
||||
if handle == 0 {
|
||||
return;
|
||||
}
|
||||
drop(unsafe { Box::from_raw(handle as *mut EpicDownloadHandle) });
|
||||
let mut handle = unsafe { Box::from_raw(handle as *mut EpicDownloadHandle) };
|
||||
if let Some(worker) = handle.worker.take() { let _ = worker.join(); }
|
||||
}
|
||||
|
||||
/// ABI v1 snapshot: selected chunks/files, verified cache lengths, old output lengths and both
|
||||
/// measured free-space probes. Parse/budget failures are terminal, never fallback requests.
|
||||
#[no_mangle]
|
||||
pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeInstallAdaptive(
|
||||
mut env: JNIEnv, _class: JClass, request: JString, listener: JObject,
|
||||
) -> jlong {
|
||||
if listener.is_null() { return 0; }
|
||||
let parsed = jstring_to_string(&mut env, &request).ok_or("unreadable adaptive request".to_string())
|
||||
.and_then(|s| super::adaptive::Request::parse(&s))
|
||||
.and_then(|req| super::adaptive::choose_budget(&req).map(|budget| (req, budget)));
|
||||
let (req, budget) = match parsed {
|
||||
Ok(plan) => plan,
|
||||
Err(error) => {
|
||||
call_on_complete(&mut env, &listener, false, &error, 0);
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
call_on_plan(&mut env, &listener, req.chunks.len() as u64, 0,
|
||||
&format!("lookahead={} retained={} game_peak={} cache_peak={}",
|
||||
budget.lookahead, budget.retained, budget.game_peak, budget.cache_peak));
|
||||
let Ok(vm) = env.get_java_vm() else {
|
||||
call_on_complete(&mut env, &listener, false, "JavaVM unavailable", 0);
|
||||
return 0;
|
||||
};
|
||||
let Ok(listener) = env.new_global_ref(&listener) else {
|
||||
call_on_complete(&mut env, &listener, false, "listener ref failed", 0);
|
||||
return 0;
|
||||
};
|
||||
let cancel = Arc::new(AtomicBool::new(false));
|
||||
let thread_cancel = cancel.clone();
|
||||
let worker = thread::spawn(move || {
|
||||
crate::priority::background();
|
||||
let progress = |done, total, files, files_total| {
|
||||
if let Ok(mut env) = vm.attach_current_thread_as_daemon() {
|
||||
call_on_progress(&mut env, listener.as_obj(), done, total, files, files_total);
|
||||
}
|
||||
};
|
||||
let before_swap = || -> Result<(), String> {
|
||||
let mut env = vm.attach_current_thread_as_daemon().map_err(|e| e.to_string())?;
|
||||
match env.call_method(listener.as_obj(), "beforeSwap", "()Z", &[]) {
|
||||
Ok(value) => if value.z().unwrap_or(false) { Ok(()) } else { Err("Could not mark installed record updating before replacement".into()) },
|
||||
_ => {
|
||||
clear_pending_exception(&mut env);
|
||||
Err("Could not mark installed record updating before replacement".into())
|
||||
}
|
||||
}
|
||||
};
|
||||
let log = |line: &str| {
|
||||
android_log(line);
|
||||
if let Ok(mut env) = vm.attach_current_thread_as_daemon() {
|
||||
call_on_log(&mut env, listener.as_obj(), line);
|
||||
}
|
||||
};
|
||||
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(||
|
||||
super::adaptive::run(&req, budget, &thread_cancel, &before_swap, &progress, &log)))
|
||||
.unwrap_or_else(|_| Err("Native Epic install panicked".into()));
|
||||
let (success, error, bytes) = match outcome {
|
||||
Ok(bytes) => (true, String::new(), bytes),
|
||||
Err(error) => (false, error, 0),
|
||||
};
|
||||
if let Ok(mut env) = vm.attach_current_thread_as_daemon() {
|
||||
call_on_complete(&mut env, listener.as_obj(), success, &error, bytes);
|
||||
}
|
||||
});
|
||||
Box::into_raw(Box::new(EpicDownloadHandle { cancel, worker: Some(worker) })) as jlong
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -117,6 +117,25 @@ pub fn run_fetch(
|
||||
cancel: &AtomicBool,
|
||||
progress: &(dyn Fn(u64, u64) + Sync),
|
||||
log: &(dyn Fn(&str) + Sync),
|
||||
) -> FetchOutcome {
|
||||
run_fetch_gated(items, hosts, opts, sink, cancel, progress, log, &|_: usize| true)
|
||||
}
|
||||
|
||||
/// [`run_fetch`] with an admission gate: the next fresh item (by index) is only dispatched once
|
||||
/// `gate(index)` says so. Items are still taken strictly in order, and retries are never held
|
||||
/// back. While the gate is closed the driver idles as it does on a full window, so a gate that
|
||||
/// opens as the sink makes progress (e.g. as files finish) paces the run without stalling the
|
||||
/// requests already in flight. The adaptivity is unchanged.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run_fetch_gated(
|
||||
items: Vec<FetchItem>,
|
||||
hosts: &[String],
|
||||
opts: &FetchOptions,
|
||||
sink: &dyn FetchSink,
|
||||
cancel: &AtomicBool,
|
||||
progress: &(dyn Fn(u64, u64) + Sync),
|
||||
log: &(dyn Fn(&str) + Sync),
|
||||
gate: &(dyn Fn(usize) -> bool + Sync),
|
||||
) -> FetchOutcome {
|
||||
let started = Instant::now();
|
||||
let label = opts.label.as_str();
|
||||
@@ -359,6 +378,7 @@ mode={}",
|
||||
Ok(rt) => {
|
||||
rt.block_on(run_driver(DriverCtx {
|
||||
items: items.as_slice(),
|
||||
gate,
|
||||
hosts: hosts.as_slice(),
|
||||
opts,
|
||||
label,
|
||||
@@ -832,6 +852,7 @@ struct FetchDone {
|
||||
|
||||
struct DriverCtx<'a> {
|
||||
items: &'a [FetchItem],
|
||||
gate: &'a (dyn Fn(usize) -> bool + Sync),
|
||||
hosts: &'a [String],
|
||||
opts: &'a FetchOptions,
|
||||
label: &'a str,
|
||||
@@ -853,6 +874,7 @@ struct DriverCtx<'a> {
|
||||
async fn run_driver(ctx: DriverCtx<'_>) {
|
||||
let DriverCtx {
|
||||
items,
|
||||
gate,
|
||||
hosts,
|
||||
opts,
|
||||
label,
|
||||
@@ -997,7 +1019,7 @@ async fn run_driver(ctx: DriverCtx<'_>) {
|
||||
let (idx, attempts) = if use_retry {
|
||||
let p = *retry.front().expect("retry nonempty");
|
||||
(p.idx, p.attempts)
|
||||
} else if next_item < items.len() {
|
||||
} else if next_item < items.len() && gate(next_item) {
|
||||
(next_item, 0u32)
|
||||
} else {
|
||||
break;
|
||||
|
||||
Reference in new issue
Block a user