mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 13:05:47 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
338ef5b29a | ||
|
|
26dec85c1d | ||
|
|
f2ecda239a | ||
|
|
93beda11d2 | ||
|
|
cb7f745fcb |
No files matched your search
@@ -87,6 +87,15 @@ object SessionPrefs {
|
||||
prefs(context).edit().putString("gameStoresSpeedTier", tier).apply()
|
||||
}
|
||||
|
||||
/**
|
||||
* Hidden A/B switch for the Epic installer: "adaptive" (default: native parallel fetch written
|
||||
* straight into staged files), "lookahead" (the native ordered-lookahead engine that caches each
|
||||
* chunk and copies it into staged files), "batch" (the older whole-cache native fetch, then
|
||||
* native assembly; needs about twice the game's size free) or "java" (the bounded Java writer).
|
||||
* No UI; set it in the `session` preferences for benchmarks.
|
||||
*/
|
||||
fun storesEpicMode(context: Context): String = prefs(context).getString("storesEpicMode", "adaptive") ?: "adaptive"
|
||||
|
||||
/** Which tab a signed-in store opens on when its chip is picked: [STORES_OPEN_LIBRARY] or [STORES_OPEN_STORE]. */
|
||||
fun storesOpenTab(context: Context): String =
|
||||
prefs(context).getString("storesOpenTab", STORES_OPEN_LIBRARY)?.takeIf { it == STORES_OPEN_STORE } ?: STORES_OPEN_LIBRARY
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,18 +9,23 @@ import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
/**
|
||||
* The native batch APIs for Epic in `libdroiddeckstores.so`: [run] fills the chunk cache with
|
||||
* verified, decompressed chunks for the files the manager says are pending, [assemble] writes those
|
||||
* files from the cache. The production installer intentionally uses one serial Java
|
||||
* chunk-to-file path instead, so cache bounds and resume behavior do not depend on native
|
||||
* availability. These APIs remain for callers that explicitly need batch fetch/assembly.
|
||||
* The native Epic engines in `libdroiddeckstores.so`:
|
||||
*
|
||||
* - [stream] (mode `adaptive`, the default): chunks fetched in parallel by the adaptive fetch core
|
||||
* and written straight into each file's staging file as they arrive, shared chunks kept in a
|
||||
* cache of at most the given budget, every file verified and swapped in (`stream.rs`).
|
||||
* - [installAdaptive] (mode `lookahead`): a JSON snapshot of the pending files; Rust chooses a
|
||||
* storage-safe ordered lookahead, reserves and caches each chunk, then copies it into staged
|
||||
* files (`adaptive.rs`). The manager also uses it when the stream engine's space plan does not
|
||||
* fit, since it narrows its window to the free space.
|
||||
* - [run] + [assemble] (mode `batch`): every chunk into the cache, then the files from it.
|
||||
*
|
||||
* The cache is `<installDir>/.chunks` when `chunkCacheDir` is `""`, else the scratch folder given -
|
||||
* the app's own cache when the game installs to a card, where the assembler drops each chunk right
|
||||
* after its last use and the folder at the end. Both calls take the same value for one install.
|
||||
* the app's own cache when the game installs to a card.
|
||||
*
|
||||
* Both block while polling [AtomicBoolean] `cancel` every 250 ms: on cancel they flip the native
|
||||
* flag, wait up to 5 s for the run to wind down, then return.
|
||||
* All block while polling [AtomicBoolean] `cancel` every 250 ms. [stream] and [installAdaptive]
|
||||
* wait for the native run to finish after a cancel (their staging cleanup must be done before the
|
||||
* manager returns); [run] and [assemble] wait up to 5 s.
|
||||
*/
|
||||
object EpicNative {
|
||||
private const val TAG = "EpicNative"
|
||||
@@ -37,6 +42,30 @@ object EpicNative {
|
||||
fun onComplete(success: Boolean, error: String, bytes: Long)
|
||||
}
|
||||
|
||||
interface InstallListener : Listener {
|
||||
/** Synchronous approval before the first verified atomic replacement. False aborts. */
|
||||
fun beforeSwap(): Boolean
|
||||
}
|
||||
|
||||
/** One native budgeted fetch/assembly run. A loaded-engine failure is never a Java retry. */
|
||||
@JvmStatic
|
||||
fun installAdaptive(request: String, cancel: AtomicBoolean, listener: InstallListener): Result =
|
||||
drive("nativeInstallAdaptive", cancel, listener, strict = true) { inner ->
|
||||
nativeInstallAdaptive(request, inner)
|
||||
}
|
||||
|
||||
/** Callbacks from a [stream] run; every method is called on a native thread. */
|
||||
interface StreamListener {
|
||||
/** File bytes written so far (staging included), and the files verified and swapped in so far. */
|
||||
fun onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long)
|
||||
/** Engine log line (already in logcat under `EpicNative`). */
|
||||
fun onLog(line: String)
|
||||
/** Once, before the first file replaces its destination; false (or a throw) fails the run with nothing replaced. */
|
||||
fun onBeforeReplace(): Boolean
|
||||
/** Terminal; `bytes` = file bytes written. */
|
||||
fun onComplete(success: Boolean, error: String, bytes: Long)
|
||||
}
|
||||
|
||||
/** Outcome of a run. `started == false`: nothing happened on disk, the caller runs its own loop. */
|
||||
class Result(
|
||||
@JvmField val started: Boolean, @JvmField val success: Boolean, @JvmField val cancelled: Boolean,
|
||||
@@ -59,13 +88,69 @@ object EpicNative {
|
||||
fun assemble(manifest: ByteArray, installDir: String, chunkCacheDir: String, fileIdx: IntArray, cancel: AtomicBoolean?, listener: Listener): Result =
|
||||
drive("nativeAssemble", cancel, listener) { inner -> nativeAssemble(manifest, installDir, chunkCacheDir, fileIdx, inner) }
|
||||
|
||||
private fun drive(what: String, cancel: AtomicBoolean?, listener: Listener, start: (Listener) -> Long): Result {
|
||||
/**
|
||||
* The adaptive install of the files [pendingFileIdx] (indices into the manifest's file list),
|
||||
* with at most [cacheBudget] bytes of shared chunks cached and at most [overlapBudget] planned
|
||||
* bytes of replaced files staged at once (`-1` = no limit), staged in [stagingDir] (the
|
||||
* manager's owned staging directory). `started == false` means nothing was fetched or written.
|
||||
*/
|
||||
@JvmStatic
|
||||
fun stream(
|
||||
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, cancel: AtomicBoolean?, listener: StreamListener,
|
||||
): Result {
|
||||
if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0)
|
||||
val latch = CountDownLatch(1)
|
||||
val completion = AtomicReference<Completion?>(null)
|
||||
val doneRef = AtomicReference(0)
|
||||
val totalRef = AtomicReference(pendingFileIdx.size)
|
||||
val inner = object : StreamListener {
|
||||
override fun onStreamProgress(bytesWritten: Long, bytesTotal: Long, filesDone: Int, filesTotal: Int, filesBytes: Long) {
|
||||
doneRef.set(filesDone); totalRef.set(filesTotal)
|
||||
listener.onStreamProgress(bytesWritten, bytesTotal, filesDone, filesTotal, filesBytes)
|
||||
}
|
||||
override fun onLog(line: String) = listener.onLog(line)
|
||||
override fun onBeforeReplace(): Boolean = runCatching { listener.onBeforeReplace() }.getOrDefault(false)
|
||||
override fun onComplete(success: Boolean, error: String, bytes: Long) {
|
||||
completion.set(Completion(success, error, bytes))
|
||||
latch.countDown()
|
||||
runCatching { listener.onComplete(success, error, bytes) }
|
||||
}
|
||||
}
|
||||
val handle: Long = try {
|
||||
nativeStream(manifest, installDir, chunkCacheDir, stagingDir, cdnPrefixes, pendingFileIdx, expectedBytes, cacheBudget, overlapBudget, caBundlePath, maxWorkers, processWorkers, inner)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "engine unavailable: ${t.javaClass.simpleName}: ${t.message}")
|
||||
return Result(false, false, false, "nativeStream: ${t.javaClass.simpleName}: ${t.message}", 0L, 0, 0)
|
||||
}
|
||||
if (handle == 0L) return Result(false, false, false, completion.get()?.error ?: "not started", 0L, 0, totalRef.get())
|
||||
var cancelSent = false
|
||||
try {
|
||||
while (!latch.await(250, TimeUnit.MILLISECONDS)) {
|
||||
if (!cancelSent && cancel != null && cancel.get()) {
|
||||
nativeCancel(handle)
|
||||
cancelSent = true
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (completion.get() == null) nativeCancel(handle)
|
||||
nativeRelease(handle)
|
||||
}
|
||||
val c = completion.get()
|
||||
val cancelled = cancelSent || (c != null && !c.success && c.error == "cancelled")
|
||||
val success = !cancelled && c != null && c.success
|
||||
val error = when { cancelled -> "cancelled"; c == null -> "no completion"; else -> c.error }
|
||||
return Result(true, success, cancelled, error, c?.bytes ?: 0L, doneRef.get(), totalRef.get())
|
||||
}
|
||||
|
||||
private fun drive(what: String, cancel: AtomicBoolean?, listener: Listener, strict: Boolean = false, start: (Listener) -> Long): Result {
|
||||
if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0)
|
||||
val latch = CountDownLatch(1)
|
||||
val completion = AtomicReference<Completion?>(null)
|
||||
val doneRef = AtomicReference(0)
|
||||
val totalRef = AtomicReference(0)
|
||||
val inner = object : Listener {
|
||||
val inner = object : InstallListener {
|
||||
override fun beforeSwap(): Boolean = (listener as? InstallListener)?.beforeSwap() ?: false
|
||||
override fun onPlan(chunksTotal: Int, bytesTotal: Long, chunkDir: String) { totalRef.set(chunksTotal); listener.onPlan(chunksTotal, bytesTotal, chunkDir) }
|
||||
override fun onProgress(bytesDone: Long, bytesTotal: Long, done: Int, total: Int) { doneRef.set(done); totalRef.set(total); listener.onProgress(bytesDone, bytesTotal, done, total) }
|
||||
override fun onLog(line: String) = listener.onLog(line)
|
||||
@@ -78,21 +163,26 @@ object EpicNative {
|
||||
val handle: Long = try {
|
||||
start(inner)
|
||||
} catch (t: Throwable) {
|
||||
Log.w(TAG, "engine unavailable: ${t.javaClass.simpleName}: ${t.message}")
|
||||
return Result(false, false, false, "$what: ${t.javaClass.simpleName}", 0L, 0, 0)
|
||||
Log.w(TAG, "${if (strict) "engine start failed (no fallback)" else "engine unavailable"}: ${t.javaClass.simpleName}: ${t.message}")
|
||||
return Result(strict, false, false, "$what: ${t.javaClass.simpleName}: ${t.message}", 0L, 0, 0)
|
||||
}
|
||||
if (handle == 0L) return Result(false, false, false, completion.get()?.error ?: "not started", 0L, 0, totalRef.get())
|
||||
if (handle == 0L) return Result(strict, false, false, completion.get()?.error ?: "not started", 0L, 0, totalRef.get())
|
||||
var cancelSent = false
|
||||
try {
|
||||
while (!latch.await(250, TimeUnit.MILLISECONDS)) {
|
||||
if (cancel != null && cancel.get()) {
|
||||
nativeCancel(handle)
|
||||
cancelSent = true
|
||||
latch.await(5, TimeUnit.SECONDS)
|
||||
if (strict) {
|
||||
while (!latch.await(250, TimeUnit.MILLISECONDS)) { }
|
||||
} else {
|
||||
latch.await(5, TimeUnit.SECONDS)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (completion.get() == null) nativeCancel(handle)
|
||||
nativeRelease(handle)
|
||||
}
|
||||
val c = completion.get()
|
||||
@@ -101,6 +191,9 @@ object EpicNative {
|
||||
return Result(true, success, cancelSent, error, c?.bytes ?: 0L, doneRef.get(), totalRef.get())
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeInstallAdaptive(request: String, listener: Listener): Long
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeStart(
|
||||
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedChunks: Int, expectedBytes: Long,
|
||||
@@ -110,6 +203,12 @@ object EpicNative {
|
||||
@JvmStatic
|
||||
private external fun nativeAssemble(manifest: ByteArray, installDir: String, chunkCacheDir: String, fileIdx: IntArray, listener: Listener): Long
|
||||
|
||||
@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
|
||||
|
||||
@JvmStatic
|
||||
private external fun nativeCancel(handle: Long)
|
||||
|
||||
|
||||
@@ -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,15 +1,18 @@
|
||||
//! Epic Games Store download adapter for the shared fetch core (`crate::fetch_core`).
|
||||
//!
|
||||
//! Scope = the chunk-fetch inner loop of `EpicDownloadManager.java` (the fixed 8-thread pool that
|
||||
//! fills `<installDir>/.chunks/<GUID>`), nothing more. The Java manager still 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 adapter re-parses
|
||||
//! the same manifest bytes, rebuilds the same chunk plan for the pending files Java hands it,
|
||||
//! skips chunks already in the cache and writes verified chunks with the same `.part` + rename
|
||||
//! protocol, so the on-disk state is identical whichever engine ran (see
|
||||
//! Bannerlator's `docs/RUST_EPIC_PARITY.md` for the rule-by-rule table).
|
||||
//! Production installs use [`stream`] (mode `adaptive`): the manager hands over the manifest
|
||||
//! bytes and the pending files, fetch_core downloads the chunks in first-use order, and each chunk
|
||||
//! is written straight into the staged files that use it (shared ones kept in a budgeted cache).
|
||||
//! [`adaptive`] (mode `lookahead`) is the fallback when the stream engine's space plan does not
|
||||
//! fit: the Java manifest/delta pass supplies a versioned snapshot, the shared pure storage
|
||||
//! schedule selects an ordered lookahead, and fetch_core runs concurrently with verified staged
|
||||
//! assembly. Both keep old outputs until their atomic swap; a synchronous JNI callback marks the
|
||||
//! sidecar updating before the first replacement. Legacy batch APIs remain available. A missing
|
||||
//! library uses the bounded Java installer; native plan/runtime failures never silently switch
|
||||
//! engines.
|
||||
//!
|
||||
//! Submodules:
|
||||
//! - [`adaptive`] — budget planner and bounded overlapping fetch/assembly coordinator.
|
||||
//! - [`manifest`] — ChunksV4 binary manifest + legacy JSON manifest parsers (1:1 with the Java
|
||||
//! `parseManifest` / `parseJsonManifest`).
|
||||
//! - [`plan`] — install-tag selection, unique-chunk plan, chunk paths / CDN URLs.
|
||||
@@ -18,6 +21,9 @@
|
||||
//! - [`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.
|
||||
//! - [`stream`] — the adaptive install the manager uses by default: the chunks fetched in
|
||||
//! parallel through the fetch core and written straight into staging files as they arrive,
|
||||
//! shared chunks kept in a budgeted cache, each file verified and swapped in safely.
|
||||
//! - [`jni`] — `Java_com_droiddeck_launcher_stores_epic_EpicNative_native*` exports.
|
||||
//!
|
||||
//! The selective-install-tag, delta/resume and chunk verification rules mirrored here were ported
|
||||
@@ -26,11 +32,13 @@
|
||||
//! 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;
|
||||
|
||||
/// User-Agent the Java manager sends on every chunk request (`EpicDownloadManager.UA`).
|
||||
pub const USER_AGENT: &str =
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -24,7 +24,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};
|
||||
|
||||
@@ -33,6 +33,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)
|
||||
}
|
||||
|
||||
/// Everything the JNI layer hands over for one assembly run.
|
||||
pub struct AssembleRequest {
|
||||
pub manifest_bytes: Vec<u8>,
|
||||
|
||||
@@ -93,10 +93,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]);
|
||||
@@ -129,10 +133,21 @@ pub fn write_verified_chunk(
|
||||
// `tmp.delete()` — clear any stale partial from a prior interrupted attempt.
|
||||
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
|
||||
}
|
||||
|
||||
@@ -141,23 +156,46 @@ 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() {
|
||||
// Java: inflate until the stream finishes or the input runs out; a corrupt stream throws
|
||||
// (DataFormatException) → this CDN attempt fails. flate2 behaves the same way: EOF on a
|
||||
// truncated stream is a clean end (partial output), corruption is an error.
|
||||
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}"))?;
|
||||
}
|
||||
@@ -165,6 +203,9 @@ fn write_part(
|
||||
let written = out.written;
|
||||
let digest = out.sha.take().map(|s| s.finalize());
|
||||
drop(out); // close the file before the rename
|
||||
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[..] {
|
||||
@@ -177,6 +218,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::*;
|
||||
@@ -361,6 +476,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");
|
||||
|
||||
@@ -7,7 +7,13 @@
|
||||
//! 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
|
||||
//! nativeStream(manifest: byte[], installDir: String, chunkCacheDir: String, stagingDir: String,
|
||||
//! cdnPrefixes: String[],
|
||||
//! pendingFileIdx: int[], expectedBytes: long, cacheBudget: long, overlapBudget: long,
|
||||
//! caBundlePath: String,
|
||||
//! maxWorkers: int, processWorkers: int, listener: EpicNative.StreamListener)
|
||||
//! -> long handle (0 = not started)
|
||||
//! nativeCancel(handle) — flips the run's AtomicBool; fetch, assembly or stream stops promptly
|
||||
//! nativeRelease(handle) — frees the handle (after onComplete)
|
||||
//! ```
|
||||
//! `chunkCacheDir` = "" keeps the cache at `<installDir>/.chunks`; any other directory is a
|
||||
@@ -17,6 +23,11 @@
|
||||
//! an assembly run, per file written), `onLog(String line)`,
|
||||
//! `onComplete(boolean success, String error, long bytes)`.
|
||||
//!
|
||||
//! The stream run (`stream.rs`) writes the files as the chunks arrive; its listener has
|
||||
//! `onStreamProgress(long bytesWritten, long bytesTotal, int filesDone, int filesTotal,
|
||||
//! long filesBytes)`, `onLog(String)`, `boolean onBeforeReplace()` (called once, before the first
|
||||
//! file replaces its destination; `false` fails the run) and the same `onComplete`.
|
||||
//!
|
||||
//! 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
|
||||
//! a new thread. JavaVM attach / GlobalRef handling is the same shape as the GOG facade.
|
||||
@@ -31,6 +42,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")]
|
||||
@@ -63,6 +75,7 @@ fn android_log(message: &str) {
|
||||
/// assembly run, so one `nativeCancel` / `nativeRelease` pair serves both.
|
||||
pub struct EpicDownloadHandle {
|
||||
cancel: Arc<AtomicBool>,
|
||||
worker: Option<thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
fn clear_pending_exception(env: &mut JNIEnv) {
|
||||
@@ -314,12 +327,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
|
||||
}
|
||||
@@ -425,9 +437,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 {
|
||||
@@ -454,6 +464,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
|
||||
}
|
||||
@@ -483,5 +681,73 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native
|
||||
}
|
||||
// The worker thread owns its own Arc clone of the cancel flag and its own GlobalRef, so
|
||||
// freeing the handle is safe even if a (cancelled) run is still winding down.
|
||||
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
@@ -221,6 +221,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();
|
||||
@@ -484,6 +503,7 @@ mode={}",
|
||||
Ok(rt) => {
|
||||
rt.block_on(run_driver(DriverCtx {
|
||||
items: items.as_slice(),
|
||||
gate,
|
||||
hosts: hosts.as_slice(),
|
||||
opts,
|
||||
label,
|
||||
@@ -1006,6 +1026,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,
|
||||
@@ -1027,6 +1048,7 @@ struct DriverCtx<'a> {
|
||||
async fn run_driver(ctx: DriverCtx<'_>) {
|
||||
let DriverCtx {
|
||||
items,
|
||||
gate,
|
||||
hosts,
|
||||
opts,
|
||||
label,
|
||||
@@ -1182,10 +1204,10 @@ 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; // nothing dispatchable now (retry not due, or all dispatched)
|
||||
break; // nothing dispatchable now (retry not due, gate closed, or all dispatched)
|
||||
};
|
||||
let item = &items[idx];
|
||||
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.droiddeck.launcher.stores.epic
|
||||
|
||||
import java.io.File
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Rule
|
||||
import org.junit.Test
|
||||
import org.junit.rules.TemporaryFolder
|
||||
import org.junit.runner.RunWith
|
||||
import org.robolectric.RobolectricTestRunner
|
||||
import org.robolectric.annotation.Config
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class EpicAdaptivePlanTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
private val mib = 1024L * 1024
|
||||
private val gib = 1024 * mib
|
||||
|
||||
private fun file(name: String, size: Long) = EpicDownloadManager.FileInfo().apply {
|
||||
filename = name
|
||||
var left = size
|
||||
while (left > 0) {
|
||||
val part = minOf(left, Int.MAX_VALUE.toLong())
|
||||
parts.add(EpicDownloadManager.ChunkPart().apply { this.size = part.toInt() })
|
||||
left -= part
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun netPeakCreditsEachOldCopyAtItsSwapAndLargestReplacedIgnoresFreshFiles() {
|
||||
val files = listOf(file("a", 10 * gib), file("b", 2 * gib), file("c", 4 * gib))
|
||||
val old = mapOf("a" to 9 * gib, "c" to 5 * gib)
|
||||
// Running Σ(new − old): +1, +3, +2 GiB.
|
||||
assertEquals(3 * gib, EpicDownloadManager.settledNetPeak(files, old))
|
||||
assertEquals(10 * gib, EpicDownloadManager.largestReplacedFile(files, old))
|
||||
assertEquals(16 * gib, EpicDownloadManager.settledNetPeak(files, emptyMap()))
|
||||
assertEquals(0L, EpicDownloadManager.largestReplacedFile(files, emptyMap()))
|
||||
assertEquals(0L, EpicDownloadManager.largestReplacedFile(files, mapOf("b" to 0L)))
|
||||
}
|
||||
|
||||
@Test fun cacheBudgetIsHalfTheHeadroomCappedAndDefaultsWhenSpaceIsUnknown() {
|
||||
assertEquals(EpicDownloadManager.ADAPTIVE_CACHE_DEFAULT_BYTES, EpicDownloadManager.adaptiveCacheBudget(-1, 0))
|
||||
assertEquals(EpicDownloadManager.ADAPTIVE_CACHE_MAX_BYTES, EpicDownloadManager.adaptiveCacheBudget(100 * gib, 10 * gib))
|
||||
assertEquals(0L, EpicDownloadManager.adaptiveCacheBudget(gib, gib))
|
||||
val free = 1000 * mib
|
||||
assertEquals((free - 400 * mib - EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES) / 2, EpicDownloadManager.adaptiveCacheBudget(free, 400 * mib))
|
||||
}
|
||||
|
||||
@Test fun freshInstallsHaveNoOverlapLimit() {
|
||||
val plan = EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, 30 * gib, true, 10 * gib)
|
||||
assertNull(plan.error)
|
||||
assertEquals(-1L, plan.overlapBudget)
|
||||
assertEquals(20 * gib, plan.gameNeed)
|
||||
}
|
||||
|
||||
@Test fun updateOverlapBudgetIsTheLeftoverAfterNetGrowthAndCache() {
|
||||
// Card install, cache on internal: the card's leftover after the net growth is the budget.
|
||||
val roomy = EpicDownloadManager.planAdaptiveSpace(gib, 4 * gib, 20 * gib, true, 10 * gib)
|
||||
assertNull(roomy.error)
|
||||
assertFalse(roomy.cacheBesideGame)
|
||||
assertEquals(19 * gib, roomy.overlapBudget)
|
||||
assertEquals(20 * gib, roomy.gameNeed)
|
||||
// Tight: floored at the largest replaced file, one at a time.
|
||||
val tight = EpicDownloadManager.planAdaptiveSpace(gib, 4 * gib, 5 * gib, true, 10 * gib)
|
||||
assertNull(tight.error)
|
||||
assertEquals(4 * gib, tight.overlapBudget)
|
||||
// Not even one replaced file fits: the shortfall is named.
|
||||
val short = EpicDownloadManager.planAdaptiveSpace(gib, 4 * gib, 4 * gib, true, 10 * gib)
|
||||
assertTrue(short.error!!.contains("game's storage"))
|
||||
assertTrue(short.error!!.contains("short by 1.0 GB"))
|
||||
// Unknown free space: one replaced file at a time.
|
||||
assertEquals(4 * gib, EpicDownloadManager.planAdaptiveSpace(gib, 4 * gib, -1, true, -1).overlapBudget)
|
||||
}
|
||||
|
||||
@Test fun cacheBesideTheGameComesOutOfTheOverlapBudget() {
|
||||
val plan = EpicDownloadManager.planAdaptiveSpace(gib, 2 * gib, 10 * gib, false, -1)
|
||||
assertNull(plan.error)
|
||||
assertTrue(plan.cacheBesideGame)
|
||||
assertTrue(plan.cacheBudget > 0)
|
||||
assertEquals(10 * gib - gib - plan.cacheBudget - EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES, plan.overlapBudget)
|
||||
assertEquals(10 * gib, plan.gameNeed)
|
||||
}
|
||||
|
||||
@Test fun fullInternalStorageMovesTheCacheBesideTheGameInsteadOfFailing() {
|
||||
val plan = EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, 30 * gib, true, 100 * mib)
|
||||
assertNull(plan.error)
|
||||
assertTrue(plan.cacheBesideGame)
|
||||
assertEquals(0L, plan.scratchNeed)
|
||||
assertTrue(plan.cacheBudget > 0)
|
||||
assertEquals(20 * gib + plan.cacheBudget + EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES, plan.gameNeed)
|
||||
}
|
||||
|
||||
@Test fun ownedStagingIsRemovedOnlyWhenItHoldsJustItsMarker() {
|
||||
val root = temp.newFolder("game")
|
||||
val staging = EpicDownloadManager.recoverOwnedStaging(root, emptyList())
|
||||
File(staging, "keep.stage").writeText("x")
|
||||
EpicDownloadManager.releaseOwnedStaging(root)
|
||||
assertTrue(File(staging, "owner").exists())
|
||||
File(staging, "keep.stage").delete()
|
||||
EpicDownloadManager.releaseOwnedStaging(root)
|
||||
assertFalse(staging.exists())
|
||||
// A directory without the marker is not ours.
|
||||
staging.mkdir()
|
||||
File(staging, "owner").writeText("someone else")
|
||||
EpicDownloadManager.releaseOwnedStaging(root)
|
||||
assertTrue(staging.exists())
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,11 @@ import java.nio.ByteOrder
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.net.Socket
|
||||
import org.junit.After
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Before
|
||||
@@ -33,6 +38,11 @@ class EpicBoundedInstallTest {
|
||||
private lateinit var root: File
|
||||
private val requests = AtomicInteger()
|
||||
private val reject = AtomicBoolean()
|
||||
private val rejectGuid = AtomicInteger()
|
||||
private val handlers = Executors.newCachedThreadPool()
|
||||
private val sockets = ConcurrentHashMap.newKeySet<Socket>()
|
||||
private var requestBarrier: CountDownLatch? = null
|
||||
private var deliveryGate: CountDownLatch? = null
|
||||
private var bytes = ByteArray(256 * 1024) { (it % 251).toByte() }
|
||||
|
||||
@Before fun setUp() {
|
||||
@@ -44,23 +54,38 @@ class EpicBoundedInstallTest {
|
||||
val socket = try { server.accept() } catch (e: SocketException) {
|
||||
if (server.isClosed) break else throw e
|
||||
}
|
||||
socket.use {
|
||||
it.soTimeout = 5000
|
||||
val reader = it.getInputStream().bufferedReader()
|
||||
while (!reader.readLine().isNullOrEmpty()) { }
|
||||
requests.incrementAndGet()
|
||||
val out = it.getOutputStream()
|
||||
if (reject.get()) {
|
||||
out.write("HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
} else {
|
||||
val header = ByteBuffer.allocate(41).order(ByteOrder.LITTLE_ENDIAN)
|
||||
.putInt(0xB1FE3AA2.toInt()).putInt(1).putInt(41).putInt(bytes.size)
|
||||
.put(ByteArray(24)).put(0).array()
|
||||
out.write("HTTP/1.1 200 OK\r\nContent-Length: ${header.size + bytes.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
out.write(header)
|
||||
out.write(bytes)
|
||||
}
|
||||
out.flush()
|
||||
sockets.add(socket)
|
||||
handlers.submit {
|
||||
try {
|
||||
socket.use {
|
||||
it.soTimeout = 5000
|
||||
val reader = it.getInputStream().bufferedReader()
|
||||
val request = reader.readLine()
|
||||
while (!reader.readLine().isNullOrEmpty()) { }
|
||||
requests.incrementAndGet()
|
||||
requestBarrier?.let { barrier ->
|
||||
barrier.countDown()
|
||||
check(barrier.await(5, TimeUnit.SECONDS)) { "Requests did not overlap" }
|
||||
}
|
||||
val out = it.getOutputStream()
|
||||
val rejectedGuid = rejectGuid.get()
|
||||
if (reject.get() || (rejectedGuid != 0 && request.contains("_%08X".format(rejectedGuid)))) {
|
||||
out.write("HTTP/1.1 503 Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
} else {
|
||||
val header = ByteBuffer.allocate(41).order(ByteOrder.LITTLE_ENDIAN)
|
||||
.putInt(0xB1FE3AA2.toInt()).putInt(1).putInt(41).putInt(bytes.size)
|
||||
.put(ByteArray(24)).put(0).array()
|
||||
out.write("HTTP/1.1 200 OK\r\nContent-Length: ${header.size + bytes.size}\r\nConnection: close\r\n\r\n".toByteArray())
|
||||
out.write(header)
|
||||
out.flush()
|
||||
deliveryGate?.await(5, TimeUnit.SECONDS)
|
||||
out.write(bytes)
|
||||
}
|
||||
out.flush()
|
||||
}
|
||||
} catch (_: java.io.IOException) {
|
||||
// Cancellation disconnects an owned request while this fixture serves it.
|
||||
} finally { sockets.remove(socket) }
|
||||
}
|
||||
}
|
||||
}.apply { start() }
|
||||
@@ -78,7 +103,15 @@ class EpicBoundedInstallTest {
|
||||
}
|
||||
}
|
||||
|
||||
@After fun tearDown() { server.close(); worker.join(6000); assertFalse(worker.isAlive) }
|
||||
@After fun tearDown() {
|
||||
deliveryGate?.countDown()
|
||||
server.close()
|
||||
worker.join(6000)
|
||||
sockets.forEach { it.close() }
|
||||
handlers.shutdownNow()
|
||||
assertTrue(handlers.awaitTermination(6, TimeUnit.SECONDS))
|
||||
assertFalse(worker.isAlive)
|
||||
}
|
||||
|
||||
private fun sha(data: ByteArray) = MessageDigest.getInstance("SHA-1").digest(data)
|
||||
|
||||
@@ -159,13 +192,9 @@ class EpicBoundedInstallTest {
|
||||
}
|
||||
manifest.uniqueChunks.add(secondChunk)
|
||||
manifest.files.last().parts.single().guid = secondChunk.guid
|
||||
val callback = object : EpicDownloadManager.Callback {
|
||||
override fun onProgress(message: String, pct: Int) {}
|
||||
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
|
||||
if (stage == "stream" && items == 1) reject.set(true)
|
||||
}
|
||||
}
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install(callback = callback) }
|
||||
// Prefetch may fail early, but replacement is still ordered by the writer.
|
||||
rejectGuid.set(2)
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
|
||||
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
|
||||
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
|
||||
@@ -376,7 +405,7 @@ class EpicBoundedInstallTest {
|
||||
assertTrue(samples.all { it.second == bytes.size.toLong() })
|
||||
}
|
||||
|
||||
@Test fun evictedSharedChunksAdvanceWriteProgressOnEveryRefetchWithoutChangingStages() {
|
||||
@Test fun oversizedSharedChunkStaysPinnedAcrossPrefetchedFilesWithoutChangingStages() {
|
||||
bytes = ByteArray((EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 1024).toInt()) { (it % 251).toByte() }
|
||||
manifest.uniqueChunks.single().apply {
|
||||
windowSize = bytes.size
|
||||
@@ -407,7 +436,7 @@ class EpicBoundedInstallTest {
|
||||
}
|
||||
}
|
||||
assertNotNull(install(callback = callback))
|
||||
assertEquals(3, requests.get())
|
||||
assertEquals(1, requests.get())
|
||||
assertEquals(listOf(0L, 1024L, 2048L, 3072L), samples)
|
||||
assertEquals("install", stages.last())
|
||||
repeat(3) { assertArrayEquals(bytes.copyOfRange(it * 1024, (it + 1) * 1024), File(root, "part-$it.bin").readBytes()) }
|
||||
@@ -442,4 +471,176 @@ class EpicBoundedInstallTest {
|
||||
assertEquals(2 * half, EpicDownloadManager.estimateStagedFilePeak(manifest.files, emptyMap()))
|
||||
assertEquals(bytes.size.toLong(), EpicDownloadManager.estimatePeakAdditionalBytes(manifest.files, chunks, emptyMap(), false, old))
|
||||
}
|
||||
|
||||
private fun distinctFiles(count: Int) {
|
||||
val template = manifest.uniqueChunks.single()
|
||||
manifest.uniqueChunks = (1..count).map { id ->
|
||||
EpicDownloadManager.ChunkInfo().apply {
|
||||
guid = intArrayOf(id, 0, 0, 0)
|
||||
windowSize = template.windowSize
|
||||
fileSize = template.fileSize
|
||||
sha1 = template.sha1
|
||||
}
|
||||
}
|
||||
manifest.files = manifest.uniqueChunks.mapIndexed { index, chunk ->
|
||||
gameFile("file-$index.bin", 0, bytes.size).apply { parts.single().guid = chunk.guid }
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun prefetchOverlapsEightSinglePartFilesButNeverFetchesTheWholeManifest() {
|
||||
distinctFiles(20)
|
||||
requestBarrier = CountDownLatch(8)
|
||||
val cancel = AtomicBoolean()
|
||||
var sawWindow = false
|
||||
assertNull(install(cancel, EpicDownloadManager.Callback { message, _ ->
|
||||
if (message.startsWith("Downloading chunks (")) {
|
||||
assertEquals(8, requests.get())
|
||||
val cacheBytes = File(root, ".chunks").listFiles()!!.sumOf { it.length() }
|
||||
assertTrue(cacheBytes <= 8L * bytes.size)
|
||||
sawWindow = true
|
||||
cancel.set(true)
|
||||
}
|
||||
}))
|
||||
assertTrue("An eight-request barrier cannot pass with a sequential downloader", sawWindow)
|
||||
assertEquals(8, requests.get())
|
||||
assertTrue(root.walk().none { it.name.endsWith(".stage") || it.name.endsWith(".part") })
|
||||
}
|
||||
|
||||
@Test fun parallelWindowSpaceThresholdIsCheckedBeforeStartingAnyRequest() {
|
||||
distinctFiles(20)
|
||||
val cache = temp.newFolder("parallel-scratch")
|
||||
val peak = EpicDownloadManager.estimatePeakAdditionalBytes(
|
||||
manifest.files, manifest.uniqueChunks.associateBy { it.guidStr() }, emptyMap(), false,
|
||||
)
|
||||
assertEquals(8L * bytes.size, peak)
|
||||
ShadowStatFs.registerStats(cache.path, 1024, peak.toInt() / 4096 - 1, peak.toInt() / 4096 - 1)
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install(cache = cache.path) }
|
||||
assertEquals(0, requests.get())
|
||||
ShadowStatFs.registerStats(cache.path, 1024, peak.toInt() / 4096, peak.toInt() / 4096)
|
||||
requestBarrier = CountDownLatch(8)
|
||||
assertNotNull(install(cache = cache.path))
|
||||
assertEquals(20, requests.get())
|
||||
manifest.files.forEach { assertArrayEquals(bytes, File(root, it.filename).readBytes()) }
|
||||
}
|
||||
|
||||
@Test fun cancellationDuringParallelNetworkReadsJoinsWorkersBeforeReturning() {
|
||||
distinctFiles(20)
|
||||
requestBarrier = CountDownLatch(8)
|
||||
deliveryGate = CountDownLatch(1)
|
||||
val cancel = AtomicBoolean()
|
||||
val outcome = java.util.concurrent.atomic.AtomicReference<Any?>()
|
||||
val installer = Thread {
|
||||
try { outcome.set(install(cancel)) } catch (e: Throwable) { outcome.set(e) }
|
||||
}.apply { start() }
|
||||
try {
|
||||
assertTrue(requestBarrier!!.await(5, TimeUnit.SECONDS))
|
||||
cancel.set(true)
|
||||
installer.join(10_000)
|
||||
assertFalse("Installer must disconnect and join all download workers", installer.isAlive)
|
||||
assertNull(outcome.get())
|
||||
val cache = File(root, ".chunks")
|
||||
val snapshot = cache.listFiles()?.associate { it.name to it.length() }.orEmpty()
|
||||
deliveryGate!!.countDown()
|
||||
Thread.sleep(150)
|
||||
assertEquals(snapshot, cache.listFiles()?.associate { it.name to it.length() }.orEmpty())
|
||||
assertTrue(snapshot.keys.none { it.endsWith(".part") })
|
||||
assertTrue(root.walk().none { it.name.endsWith(".stage") })
|
||||
assertEquals(8, requests.get())
|
||||
} finally {
|
||||
cancel.set(true)
|
||||
deliveryGate!!.countDown()
|
||||
installer.join(10_000)
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun failedParallelFetchJoinsOtherNetworkReadersBeforeReturning() {
|
||||
distinctFiles(20)
|
||||
requestBarrier = CountDownLatch(8)
|
||||
deliveryGate = CountDownLatch(1)
|
||||
rejectGuid.set(1)
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertEquals(8, requests.get())
|
||||
val cache = File(root, ".chunks")
|
||||
val snapshot = cache.listFiles()?.associate { it.name to it.length() }.orEmpty()
|
||||
deliveryGate!!.countDown()
|
||||
Thread.sleep(150)
|
||||
assertEquals(snapshot, cache.listFiles()?.associate { it.name to it.length() }.orEmpty())
|
||||
assertTrue(snapshot.keys.none { it.endsWith(".part") })
|
||||
assertTrue(root.walk().none { it.name.endsWith(".stage") })
|
||||
}
|
||||
|
||||
@Test fun ownedOrphanStagingIsRecoveredBeforeTheSpaceProbeWithoutTouchingManifestFiles() {
|
||||
val staging = EpicDownloadManager.recoverOwnedStaging(root, manifest.files)
|
||||
File(staging, "native-123-0.stage").writeBytes(ByteArray(bytes.size))
|
||||
val legitimate = File(root, ".droiddeck-epic-old.stage").apply { writeText("keep") }
|
||||
oldInstall()
|
||||
val peak = 2 * bytes.size
|
||||
ShadowStatFs.registerStats(root.path, 1024, peak / 4096, peak / 4096)
|
||||
assertNotNull(install())
|
||||
assertEquals("keep", legitimate.readText())
|
||||
// The orphan was recovered, and a finished install removes the then-empty owned namespace.
|
||||
assertFalse(staging.exists())
|
||||
}
|
||||
|
||||
@Test fun stagingRecoveryRefusesUnownedAndManifestOwnedNamespaces() {
|
||||
val staging = File(root, EpicDownloadManager.STAGING_DIRECTORY).apply { mkdir() }
|
||||
val untouched = File(staging, "legitimate.stage").apply { writeText("keep") }
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertEquals("keep", untouched.readText())
|
||||
File(staging, "owner").writeText("DroidDeck Epic staging v1\n")
|
||||
manifest.files.first().filename = "${EpicDownloadManager.STAGING_DIRECTORY}/legitimate.stage"
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertEquals("keep", untouched.readText())
|
||||
assertEquals(0, requests.get())
|
||||
}
|
||||
|
||||
@Test fun loadedNativeAbiFailureIsExplicitAndNeverFallsBackToJavaDownloads() {
|
||||
val field = com.droiddeck.launcher.stores.StoresNative::class.java.getDeclaredField("loaded")
|
||||
field.isAccessible = true
|
||||
field.set(null, true)
|
||||
try {
|
||||
oldInstall()
|
||||
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertTrue(error.message.orEmpty().contains("Native Epic install failed"))
|
||||
assertEquals(0, requests.get())
|
||||
assertOldInstallIntact()
|
||||
} finally {
|
||||
com.droiddeck.launcher.stores.StoresNative.forget()
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun stagingRecoveryRejectsSymlinkNamespaceOwnerAndEntriesWithoutDeletingOutsideData() {
|
||||
val outside = temp.newFolder("outside-staging")
|
||||
val externalStage = File(outside, "keep.stage").apply { writeText("keep") }
|
||||
val externalOwner = File(outside, "owner").apply { writeText("DroidDeck Epic staging v1\n") }
|
||||
val staging = File(root, EpicDownloadManager.STAGING_DIRECTORY)
|
||||
try {
|
||||
java.nio.file.Files.createSymbolicLink(staging.toPath(), outside.toPath())
|
||||
} catch (e: java.nio.file.FileSystemException) {
|
||||
org.junit.Assume.assumeNoException("Host does not permit symbolic links", e)
|
||||
}
|
||||
try {
|
||||
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertTrue(error.message.orEmpty().contains("Unsafe Epic staging"))
|
||||
assertEquals("keep", externalStage.readText())
|
||||
java.nio.file.Files.delete(staging.toPath())
|
||||
staging.mkdir()
|
||||
java.nio.file.Files.createSymbolicLink(File(staging, "owner").toPath(), externalOwner.toPath())
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
java.nio.file.Files.delete(File(staging, "owner").toPath())
|
||||
File(staging, "owner").writeText("DroidDeck Epic staging v1\n")
|
||||
val localStage = File(staging, "local.stage").apply { writeText("local") }
|
||||
java.nio.file.Files.createSymbolicLink(File(staging, "linked.stage").toPath(), externalStage.toPath())
|
||||
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
|
||||
assertEquals("local", localStage.readText())
|
||||
assertEquals("keep", externalStage.readText())
|
||||
assertEquals(0, requests.get())
|
||||
} finally {
|
||||
if (java.nio.file.Files.isSymbolicLink(staging.toPath())) java.nio.file.Files.delete(staging.toPath())
|
||||
for (name in listOf("owner", "linked.stage")) {
|
||||
val entry = File(staging, name).toPath()
|
||||
if (java.nio.file.Files.isSymbolicLink(entry)) java.nio.file.Files.delete(entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,14 +15,14 @@ import org.robolectric.annotation.Config
|
||||
@Config(sdk = [33])
|
||||
class EpicJsonManifestTest {
|
||||
@Test
|
||||
fun boundedInstallPeakCountsOnlyOneLiveChunkForSequentialChunks() {
|
||||
fun boundedInstallPeakReservesParallelIncomingChunksBeforeWriting() {
|
||||
val first = chunk(1)
|
||||
val second = chunk(2)
|
||||
val file = file(part(1, 0, 100), part(2, 0, 100))
|
||||
val chunks = mapOf(first.guidStr() to first, second.guidStr() to second)
|
||||
|
||||
assertEquals(300L, EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), true))
|
||||
assertEquals(100L, EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), false))
|
||||
assertEquals(200L, EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), false))
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -45,7 +45,7 @@ class EpicJsonManifestTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun distantSharedChunksAreEvictedAndRefetchedWithinTheCacheCeiling() {
|
||||
fun sharedChunksWithinTheWindowStayPinnedWithinTheCacheCeiling() {
|
||||
val first = chunk(1).apply { windowSize = 40 * 1024 * 1024 }
|
||||
val second = chunk(2).apply { windowSize = 40 * 1024 * 1024 }
|
||||
val files = listOf(
|
||||
@@ -63,6 +63,43 @@ class EpicJsonManifestTest {
|
||||
assertTrue(cachePeak <= EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 40L * 1024 * 1024)
|
||||
}
|
||||
|
||||
@Test fun scheduleDeduplicatesWindowAndEvictsOnlyUnpinnedReusableChunks() {
|
||||
val size = 40L * 1024 * 1024
|
||||
val chunks = (1..12).map { chunk(it).apply { windowSize = size.toInt() } }
|
||||
.associateBy { it.guidStr() }
|
||||
val files = (1..12).map { file(part(it, 0, 1)) } + (1..12).map { file(part(it, 0, 1)) }
|
||||
val schedule = EpicDownloadManager.PrefetchSchedule(files, chunks, emptyMap())
|
||||
assertEquals(chunks.keys.take(8), schedule.fill())
|
||||
assertEquals(emptyList<String>(), schedule.fill())
|
||||
assertEquals(8 * size, schedule.bytes())
|
||||
assertEquals(emptyList<String>(), schedule.consume())
|
||||
assertEquals(listOf(chunks.keys.elementAt(8)), schedule.fill())
|
||||
assertEquals(9 * size, schedule.bytes())
|
||||
assertEquals(listOf(chunks.keys.first()), schedule.consume())
|
||||
var refetchedFirst = false
|
||||
repeat(22) {
|
||||
val fetched = schedule.fill()
|
||||
if (chunks.keys.first() in fetched) refetchedFirst = true
|
||||
assertTrue(schedule.bytes() <= EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 8 * size)
|
||||
val released = schedule.consume()
|
||||
assertTrue(released.none { it in schedule.window() })
|
||||
}
|
||||
assertTrue(refetchedFirst)
|
||||
assertEquals(0L, schedule.bytes())
|
||||
assertEquals(9 * size, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), false))
|
||||
}
|
||||
|
||||
@Test fun cachedAndOldOutputBytesAreCreditedOnlyWhenTheScheduleReleasesThem() {
|
||||
val chunks = (1..8).map { chunk(it) }.associateBy { it.guidStr() }
|
||||
val files = (1..8).map { id -> file(part(id, 0, 100)).apply { filename = "file-$id" } }
|
||||
val existing = chunks.keys.associateWith { 100L }
|
||||
val old = files.associate { it.filename to 100L }
|
||||
assertEquals(800L, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), false))
|
||||
assertEquals(0L, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, existing, false))
|
||||
assertEquals(900L, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), true, old))
|
||||
assertEquals(100L, EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, existing, true, old))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun resumeCacheDropsCorruptAndUnneededEntriesButKeepsVerifiedChunks() {
|
||||
val dir = java.io.File(System.getProperty("user.dir"), "build/epic-cache-test-${System.nanoTime()}")
|
||||
|
||||
+120
-24
@@ -45,35 +45,121 @@ with a placeholder job. Failures are kept in the Downloads UI, notification and
|
||||
duplicated as transient failure toasts. Active queue persistence and ordinary backend pause/retry
|
||||
are unchanged.
|
||||
|
||||
Epic installs use the same bounded Java writer whether the native engine is available or not.
|
||||
It fetches one chunk at a time, verifies it, and writes the required parts into the current
|
||||
game file. Chunks are deleted after their last use; reusable chunks are retained up to 64 MiB,
|
||||
with at most one additional incoming chunk before eviction. Evicted shared chunks may be
|
||||
downloaded again. This trades parallel-download throughput and potentially extra network
|
||||
traffic for bounded temporary disk usage. The native batch APIs remain available but are not
|
||||
used by this install path.
|
||||
Epic installs have four writers, all with the same per-file safety rules (below). The hidden
|
||||
`storesEpicMode` string in the `session` preferences picks one: `adaptive` (default), `lookahead`,
|
||||
`batch` or `java`. There is no UI for it; set it on a test device to compare the modes on the same
|
||||
game. Every mode logs an `epic: summary mode=<mode>` line (files, bytes written, elapsed, average
|
||||
MB/s). When `libdroiddeckstores.so` does not load, every mode runs the Java writer. Once it is
|
||||
loaded, an engine failure (refused plan, ABI mismatch, network, hash or I/O failure, unsupported
|
||||
atomic swap) fails the install; it never silently reruns as Java downloads.
|
||||
|
||||
The earlier batch design intentionally prioritizes parallel-download throughput. Native
|
||||
`epic/assemble.rs::build_assemble_plan` enables `scratch_cache` only for a nonempty cache path.
|
||||
`run_assemble` decrements per-file chunk references and removes chunks at their last use **only
|
||||
when that flag is set**; the default beside-game cache is removed at the end. The native tests
|
||||
`default_cache_assembles_like_the_kotlin_loop_and_removes_the_cache_at_the_end` and
|
||||
the scratch-cache assembly tests cover that distinction. Extending last-use reclamation to
|
||||
internal native assembly could keep parallel batch throughput and reduce the overlapping
|
||||
cache/output peak, but batch fetching still fills
|
||||
the cache before assembly. That is not equivalent to the bounded sequential writer's fixed
|
||||
retained-cache ceiling. This change keeps the bounded path and its explicit throughput/refetch
|
||||
tradeoff; it does not redesign or benchmark native download throughput.
|
||||
**Adaptive (default)** - `EpicNative.stream`, `epic/stream.rs`. Measured on device: about
|
||||
83 MB/s on a 71 GB install. The chunks go through the shared fetch core in the order their files
|
||||
need them, with its full adaptivity (window ramp, per-host caps, in-flight byte budget, retries,
|
||||
host rotation, stall handoff). A chunk only one file part uses is verified and written straight
|
||||
into that file's staging file at the part's offset, in whatever order it arrives; it is never
|
||||
cached, so each byte is written once. A chunk several parts use is written into every part whose
|
||||
file the download has reached and kept, decompressed, in the cache until its last part is written.
|
||||
The cache has a byte budget; the plan simulates the install in file order and, when the budget
|
||||
would be exceeded, drops the cached chunk needed furthest ahead and downloads it again later.
|
||||
Files are opened only once the download reaches them, so the set of half-written files stays
|
||||
within the fetch window. All writes happen in the fetch core's process pool, whose completion
|
||||
frees the in-flight byte budget: a slow card throttles the download instead of growing memory.
|
||||
Each file's SHA-1 is computed as its parts are written (parts that arrived out of order are read
|
||||
back once the bytes before them are in). Stage files go into the owned staging namespace below.
|
||||
The run logs `stream-plan` (direct vs shared chunks, planned refetches, budget) and
|
||||
`stream-summary mode=adaptive` (peak cache, peak staging, refetches, bytes written from the
|
||||
download vs from the cache).
|
||||
|
||||
The bounded Epic download bar, measured rate and ETA count pending file bytes written, not unique
|
||||
On an update, a staged file that replaces an existing one sits beside its old copy until its swap,
|
||||
so the engine paces replacements with an overlap budget: files are admitted in order, a replaced
|
||||
file only while the planned sizes of admitted, not-yet-swapped replaced files fit the budget (one
|
||||
is always admitted, so the run progresses), and a chunk is fetched only once its file is admitted.
|
||||
Fresh files are never held back, and admission only delays files, never reorders them, so the
|
||||
cache plan stays exact. The run logs `overlap_budget=` in `stream-plan` and
|
||||
`peak_replace_overlap_bytes=` in `stream-summary`. With room to spare the budget is large and
|
||||
updates run as wide as fresh installs; on a nearly full volume, replaced files are staged one
|
||||
after another and the fetch pauses at each replaced-file boundary until the previous one is
|
||||
swapped in.
|
||||
|
||||
Its space plan (`EpicDownloadManager.planAdaptiveSpace`, unit-tested in `EpicAdaptivePlanTest`)
|
||||
checks each volume for what lands on it, with the lookahead planner's rule (the need must not
|
||||
exceed the free reading). The game volume: the net growth at its worst point (`settledNetPeak`,
|
||||
the running Σ(new − old) with each old copy released at its swap), plus the overlap budget, plus
|
||||
the cache when it is beside the game. The overlap budget is whatever the game volume has left
|
||||
after the net growth and the cache, never less than the largest replaced file; when even that
|
||||
does not fit, the plan hands over to the lookahead engine. The cache volume: the budget plus 64 MiB of
|
||||
chunks in transit. The cache budget is half the cache volume's free space after those needs, at most
|
||||
1 GiB (256 MiB when free space is unknown; 0 is allowed and means every reuse is a refetch). On a
|
||||
card install the cache stays on internal scratch unless internal storage cannot hold at least
|
||||
64 MiB of it; then the cache goes beside the game (still released chunk by chunk) instead of
|
||||
failing. A plan that does not fit logs the short storage and the shortfall and hands over to the
|
||||
lookahead engine, which narrows its window to the space there is (or fails its own preflight with
|
||||
an explicit error). Running out of space in the middle of an adaptive run is not destructive: a
|
||||
failed write fails the run, unfinished staging files are removed, the old files stay.
|
||||
|
||||
**Lookahead** - `EpicNative.installAdaptive`, `epic/adaptive.rs`; also the adaptive engine's
|
||||
fallback when its space plan does not fit. The Java delta pass sends a versioned snapshot of
|
||||
pending files, chunk metadata, verified cache lengths, old output lengths and both measured
|
||||
free-space probes to Rust. The native planner and execution share one ordered moving-window
|
||||
policy. Before any chunk request, Rust chooses the largest safe lookahead (128, 64, 32, 16, 8, 4,
|
||||
2 or 1 part references) and reusable-cache budget (64 MiB, 16 MiB or zero) whose simulated
|
||||
staged-file and cache peaks fit. Native device IDs also detect an explicitly named cache on the
|
||||
game volume, so two separate paths cannot incorrectly turn one filesystem's requirement into two
|
||||
independent checks.
|
||||
|
||||
| Storage situation | Lookahead policy |
|
||||
| --- | --- |
|
||||
| Plenty of room | Up to 128 references ahead, up to 32 network requests, 64 MiB reusable data |
|
||||
| Tight | Smaller lookahead and/or reusable budget; parallel fetching remains where space permits |
|
||||
| Barely fits | One-reference lookahead, one request, no reusable retention if needed |
|
||||
| Does not fit even the minimal schedule | Explicit preflight error before requests or replacement |
|
||||
| Free space unknown | Conservative bounded lookahead (at most eight), not an invented zero |
|
||||
|
||||
The lookahead fetch coordinator reuses `fetch_core`'s host scheduling, retries, adaptive network
|
||||
window and decode pool. Each chunk is cached, then its parts are copied into staged files by a
|
||||
writer that runs concurrently, waiting only for its next required chunk, through the native
|
||||
assembler's streaming copy primitive. GUIDs in the lookahead are reserved once before submission,
|
||||
at their full decoded size. Chunks are released at last use on **both** cache layouts; distant
|
||||
reusable data is oldest-first bounded and may be refetched. At most the selected reusable budget
|
||||
plus distinct lookahead decoded sizes is resident/reserved. New request admission re-probes both
|
||||
volumes and can shrink unsent lookahead or retention if headroom disappears; already in-flight
|
||||
reservations remain protected. If even existing reservations cannot fit, the run fails and joins
|
||||
its workers rather than waiting indefinitely or deleting old game files. An install to SD retains
|
||||
its internal scratch cache, so assembled output is the only game data written to the card.
|
||||
|
||||
**Java** - without the native library, or with `storesEpicMode=java`. Eight Java workers prefetch
|
||||
the next eight chunk-part references, across file boundaries, while one writer assembles and
|
||||
verifies files in manifest order. Shared GUIDs within that window are fetched only once. Chunks
|
||||
are deleted after their last use; other reusable chunks are retained up to 64 MiB. At most eight
|
||||
additional decoded chunks (complete or in flight) coexist with that retained cache. The size
|
||||
bound is 64 MiB plus the decoded sizes of the window's distinct GUIDs, not a fixed eight-MiB
|
||||
allowance: manifests can supply larger chunk windows. Evicted distant shared chunks may be
|
||||
downloaded again. No worker downloads outside the moving window; cancellation and failure
|
||||
disconnect and join all workers before returning or removing the cache. Its summary line is
|
||||
`mode=java-bounded`.
|
||||
|
||||
**Batch** - the earlier native design, kept for A/B benchmarks: every chunk fetched into the
|
||||
cache in parallel, then the files assembled from it (`EpicNative.run` + `EpicNative.assemble`).
|
||||
It needs the cache and the files at once (about twice the game) and checks exactly that before
|
||||
starting; it writes files in place, so an existing install is marked `updating` before assembly.
|
||||
`epic/assemble.rs::build_assemble_plan` enables `scratch_cache` only for a nonempty cache path:
|
||||
`run_assemble` then removes chunks at their last use; the default beside-game cache is removed at
|
||||
the end (`default_cache_assembles_like_the_kotlin_loop_and_removes_the_cache_at_the_end` and the
|
||||
scratch-cache assembly tests cover that distinction).
|
||||
|
||||
The Epic download bar, measured rate and ETA (adaptive, lookahead and Java) count pending file bytes written, not unique
|
||||
compressed chunks fetched. Shared chunks therefore cannot complete the bar before later files
|
||||
are written, and an evicted chunk's refetch is reflected in the time spent doing that work.
|
||||
Streaming stays in the Download stage until all files are written and verified, then enters
|
||||
Install for registration; it does not bounce between stages for each file.
|
||||
|
||||
The space check follows the manifest delta pass and simulates file writes, chunk fetches,
|
||||
and evictions, rather than adding the entire cache to the entire game. Each file is written to a
|
||||
unique sibling staging file on its output volume (never the literal `<filename>.part`, which can
|
||||
For the lookahead and Java writers, the space check follows the manifest delta pass and uses the
|
||||
same pure moving-window policy as execution, reserving all incoming decoded chunk sizes before writing parts and simulating
|
||||
last-use releases and unpinned oldest-first evictions. Existing verified cache bytes count against
|
||||
current free space and are credited only at their scheduled release. This avoids adding the entire
|
||||
cache to the entire game without undercounting concurrent downloads. Each file is written to a
|
||||
unique file in an owned staging namespace on its output volume (never the literal `<filename>.part`, which can
|
||||
be a legitimate manifest file), size/hash verified, synced and atomically renamed over its output.
|
||||
The old file remains until that swap succeeds. The planner credits its bytes only after that
|
||||
file's complete staging write, not by subtracting all old outputs up front. Both volume checks
|
||||
@@ -84,8 +170,18 @@ verified cached chunks are accounted for on resume. On a card, game and cache re
|
||||
are checked separately. File SHA-1 hashes are checked where supplied by the manifest; failed
|
||||
or cancelled staging files are removed without deleting old outputs. A successful run removes the
|
||||
cache. A resume within a large incomplete file restarts that file, not its individual parts.
|
||||
Abrupt process termination can leave a unique staging file; unlike normal failure/cancellation,
|
||||
its cleanup is not guaranteed, and the next space probe includes its occupied bytes.
|
||||
All three staged writers (adaptive, lookahead, Java) use `<installDir>/.droiddeck-epic-staging/`, whose `owner` marker identifies this
|
||||
namespace. A successful install removes it when it holds nothing but the marker (same no-follow
|
||||
and canonical-path checks); the next run recreates it. Before the delta pass and free-space probes, the manager removes orphan `.stage`
|
||||
entries only from this owned namespace. A manifest naming that directory or any descendant
|
||||
fails without deletion; an unowned directory or unexpected entry also fails conservatively.
|
||||
The namespace must be a real directory at the expected canonical child of the install root.
|
||||
Ownership markers and staging entries must be no-follow regular files; symlink directories,
|
||||
markers and entries are rejected before recovery deletes anything.
|
||||
Ordinary game files with `.stage` or `.part` suffixes elsewhere are never recovery targets.
|
||||
Abrupt process termination is therefore recoverable on the next run without inferring ownership
|
||||
from a loose filename prefix. Cancellation/failure waits for all native/Java fetch writers before
|
||||
returning; completed verified cache chunks remain usable on resume.
|
||||
|
||||
## The sidecar
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ EXPORTS = ['Java_com_droiddeck_launcher_stores_StoresNative_nativeVersion',
|
||||
'Java_com_droiddeck_launcher_stores_gog_GogNative_nativeStart',
|
||||
'Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStart',
|
||||
'Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeAssemble',
|
||||
'Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStream',
|
||||
'Java_com_droiddeck_launcher_stores_amazon_AmazonNative_nativeStart']
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user