Compare commits

...
Author SHA1 Message Date
The412Banner 10a66b2298 Use the adaptive Epic engine by default, keep bounded and batch modes
EpicDownloadManager runs EpicNative.stream when the library loads and its
per-volume space plan fits (cache on internal scratch for card installs,
beside the game when internal storage is full), and falls back to the
bounded Java writer otherwise. A hidden storesEpicMode preference selects
adaptive, batch (whole-cache fetch then native assembly, with its 2x
space check) or java for A/B runs; each mode logs a summary line.
2026-10-13 20:31:22 -04:00
The412Banner 509c0482bf Stream Epic chunks straight into staged files with a budgeted shared cache
The native adaptive install: chunks fetched in parallel through the fetch
core in first-use order; single-use chunks are written at their part's
offset into the file's staging file, shared chunks are kept in a budgeted
cache (furthest-next-use eviction, refetch later), and every file is
SHA-1 checked, synced and atomically renamed with the bounded writer's
rules. New JNI export nativeStream.
2026-10-13 20:31:21 -04:00
Juan Marti Mercado 05d1795a51 Preserve Epic files during replacement and distinguish full storage 2026-10-13 19:15:36 -04:00
Juan Marti Mercado 87e6556993 Simplify storage probes, cache policy, and failure feedback 2026-10-13 19:15:36 -04:00
Juan Marti Mercado 8ff1f5dd20 Preserve Epic game files when storage checks reject updates 2026-10-13 19:15:35 -04:00
Juan Marti Mercado 93cd54c93b Fix store retry lifecycle, resume checks, and Epic progress 2026-10-13 19:15:34 -04:00
Juan Marti Mercado c8a49e853a Keep bounded Epic downloads in a stable UI stage 2026-10-13 19:15:34 -04:00
Juan Marti Mercado 78b3f27816 Bound Epic chunk cache during installation 2026-10-13 19:15:33 -04:00
Juan Marti Mercado eaa095925c Use known game size for preflight checks 2026-10-13 19:15:32 -04:00
Juan Marti Mercado 82b8cf1230 Show storage warning and error message on insufficient download space 2026-10-13 19:15:31 -04:00
31 changed files with 3974 additions and 238 deletions

No files matched your search

@@ -87,6 +87,14 @@ 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), "batch" (the older whole-cache native fetch, then native
* assembly; needs about twice the game's size free) or "java" (the bounded one-chunk-at-a-time
* 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
@@ -90,6 +90,7 @@ class StoreGameSidecar(
const val VERSION = 1
const val STATE_INSTALLED = "installed"
const val STATE_INSTALLING = "installing"
const val STATE_UPDATING = "updating"
fun file(folder: File): File = File(folder, FILE_NAME)
@@ -20,13 +20,68 @@ import java.util.zip.CRC32
* shortcut's path - and with it its appid - stays the same from one session to the next.
*/
object StoreInstallRoot {
const val SPACE_UNKNOWN = -1L
private const val INTERNAL = "root/Games/Stores"
private const val ON_VOLUME = "Games"
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
/** One place a game can be installed: the folder, its name for the dialog, and whether it is a card. */
class Target(val root: File, val label: String, val removable: Boolean) {
val freeBytes: Long get() = try { StatFs((if (root.isDirectory) root else root.parentFile ?: root).path).availableBytes } catch (e: Exception) { 0L }
val freeBytes: Long get() = availableBytes(root)
}
data class StorageCheck(
val enough: Boolean,
val requiredBytes: Long,
val availableBytes: Long,
val errorMessage: String? = null
)
@JvmStatic
fun availableBytes(file: File): Long = probeAvailableBytes(file, { StatFs(it.path).availableBytes }, { it.usableSpace })
internal fun probeAvailableBytes(file: File, statBytes: (File) -> Long, usableBytes: (File) -> Long): Long {
var dir: File? = if (file.isDirectory) file else file.parentFile
if (dir == null) dir = file
while (dir != null && !dir.exists()) dir = dir.parentFile
val existing = dir ?: return SPACE_UNKNOWN
return try {
statBytes(existing).coerceAtLeast(SPACE_UNKNOWN)
} catch (e: Exception) {
StoresState.logLine("storage: StatFs failed for store install target (${e.javaClass.simpleName})")
try {
// File's zero also means an unavailable measurement; only StatFs establishes zero.
usableBytes(existing).takeIf { it > 0L } ?: SPACE_UNKNOWN
} catch (fallback: Exception) {
StoresState.logLine("storage: usable-space fallback failed for store install target (${fallback.javaClass.simpleName})")
SPACE_UNKNOWN
}
}
}
@JvmStatic
fun insufficientSpace(required: Long, available: Long): Boolean = required > 0L && available >= 0L && available < required
/**
* The catalog size is the known minimum for an install. Epic's actual chunk-cache requirement
* is determined from its manifest before chunk downloads begin.
*/
fun estimatedBytesNeeded(item: CatalogItem): Long = StoreSizes.size(item).coerceAtLeast(0L)
/** Pre-install storage check to detect insufficient space before starting. */
fun checkStorage(context: Context, item: CatalogItem, targetRoot: File): StorageCheck {
val size = estimatedBytesNeeded(item)
val existing = existingFolder(context, item.store, item.id, item.title)
val freeTarget = availableBytes(existing ?: targetRoot)
// Backends account for completed files on resume; the catalog cannot describe remaining work.
// Comparing the full catalog size to remaining free space would reject valid resumes.
if (item.store == Store.EPIC || existing != null) return StorageCheck(enough = true, requiredBytes = size, availableBytes = freeTarget)
if (size <= 0L) return StorageCheck(enough = true, requiredBytes = 0L, availableBytes = freeTarget)
if (insufficientSpace(size, freeTarget)) {
val msg = context.getString(com.droiddeck.launcher.R.string.stores_storage_insufficient, formatBytes(size), formatBytes(freeTarget))
return StorageCheck(enough = false, requiredBytes = size, availableBytes = freeTarget, errorMessage = msg)
}
return StorageCheck(enough = true, requiredBytes = size, availableBytes = freeTarget)
}
/** The internal root: always there, always the default. */
@@ -7,6 +7,8 @@ import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.LibraryCache
import com.droiddeck.launcher.frontend.Library
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
/**
* What happens around a store install so the rest of the app sees the game: the sidecar is
@@ -30,10 +32,28 @@ object StoreInstalls {
* updated keeps its finished sidecar, so the game stays in Steam meanwhile.
*/
fun begin(folder: File, store: Store, id: String, title: String, cover: String?, hero: String?) {
if (StoreGameSidecar.read(folder)?.isInstalled == true) return
val before = StoreGameSidecar.read(folder)
if (before?.isInstalled == true || before?.state == StoreGameSidecar.STATE_UPDATING) return
StoreGameSidecar(store, id, title, exe = "", cover = cover, hero = hero, state = StoreGameSidecar.STATE_INSTALLING).write(folder)
}
/** Epic commits verified files individually, not a whole-game transaction. Keep updates resumable. */
@JvmStatic
fun markUpdating(folder: File) {
val before = StoreGameSidecar.read(folder) ?: return
if (!before.isInstalled) return
val stage = File.createTempFile(".droiddeck-update-", ".stage", folder)
try {
java.io.FileOutputStream(stage).use {
it.write(before.copy(state = StoreGameSidecar.STATE_UPDATING, installVersion = "").toJson().toString(2).toByteArray(Charsets.UTF_8))
it.fd.sync()
}
Files.move(stage.toPath(), StoreGameSidecar.file(folder).toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} finally {
stage.delete()
}
}
/**
* Finishes an install: writes the launcher and the finished sidecar, then the art, then
* registers the game. Runs on the caller's worker thread. The launcher and sidecar writes
@@ -105,16 +125,18 @@ object StoreInstalls {
/**
* What Cancel does: everything the install wrote goes - the game folder with its sidecar and
* the caches in [caches] - unless the folder holds a finished install being repaired or updated;
* then only the caches go and the working game stays. Off the caller's thread; the library
* follows when it is done, so the game reads Install again.
* then only the caches go. An Epic `updating` folder is retained too: its verified swaps are
* not rolled back, and it must be resumed before being advertised as installed again.
* Off the caller's thread; the library follows when it is done.
*/
fun discard(context: Context, folder: File, caches: List<File>) {
val app = context.applicationContext
Thread({
val keep = StoreGameSidecar.read(folder)?.isInstalled == true
val sidecar = StoreGameSidecar.read(folder)
val keep = sidecar?.isInstalled == true || sidecar?.state == StoreGameSidecar.STATE_UPDATING
caches.forEach { deleteTree(it) }
if (!keep) deleteTree(folder)
StoresState.logLine(if (keep) "removed the partial update of ${folder.name}" else "removed ${folder.name}")
StoresState.logLine(if (keep) "removed update caches for ${folder.name}; verified file swaps are retained" else "removed ${folder.name}")
StoresState.notifyLibraryChanged(app)
}, "store-cancel-clean").start()
}
@@ -219,7 +219,25 @@ object StoresState {
/** Starts an install into [root] (the internal root when null). */
fun install(context: Context, item: CatalogItem, root: java.io.File? = null) {
val app = context.applicationContext
val target = root ?: StoreInstallRoot.installRoot(app)
val folder = StoreInstallRoot.folderFor(app, item.store, item.id, item.title, root ?: StoreInstallRoot.installRoot(app))
val target = folder.parentFile!!.parentFile!!
val check = StoreInstallRoot.checkStorage(app, item, target)
if (!check.enough) {
val errorMsg = check.errorMessage ?: app.getString(com.droiddeck.launcher.R.string.stores_storage_insufficient, formatBytes(check.requiredBytes), formatBytes(check.availableBytes))
val entry = com.droiddeck.launcher.stores.download.DownloadEntry(
item.store,
item.id,
item.title,
cover = item.imageUrl,
bytesTotal = item.sizeBytes,
location = StoreInstallRoot.labelFor(app, folder)
)
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, target)
com.droiddeck.launcher.stores.download.DownloadQueue.recordFailed(app, entry, errorMsg) {
install(app, item, target)
}
return
}
com.droiddeck.launcher.stores.download.SavedQueue.remember(app, item, target)
backends[item.store]?.install(app, item, target) ?: logLine("${item.store.label}: this build cannot install yet")
}
@@ -77,9 +77,10 @@ public final class AmazonDownloadManager {
if (manifestBytes == null) throw new InstallException("The manifest could not be downloaded");
AmazonManifest.ParsedManifest manifest = AmazonManifest.parse(manifestBytes);
cb.onLog("amazon: " + manifest.allFiles.size() + " files, " + fmt(manifest.totalInstallSize));
long usable = installDir.getUsableSpace();
if (manifest.totalInstallSize > 0 && usable > 0 && manifest.totalInstallSize > usable)
throw new InstallException("Not enough free space: need " + fmt(manifest.totalInstallSize) + ", only " + fmt(usable) + " free");
long remainingBytes = remainingInstallBytes(manifest.allFiles, installDir);
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installDir);
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(remainingBytes, usable))
throw new InstallException("Not enough free space: need " + fmt(remainingBytes) + ", only " + fmt(usable) + " free");
cb.onSizes(manifest.totalInstallSize, manifest.totalInstallSize);
cb.onBytes(0, manifest.totalInstallSize, 0);
if (cancel.get()) return null;
@@ -184,7 +185,7 @@ public final class AmazonDownloadManager {
AtomicLong lastSpeedMs, AtomicLong lastSpeedBytes, AtomicLong speedBps, Callback cb, AtomicBoolean cancel) {
File destFile = new File(installDir, file.unixPath());
File tmpFile = new File(installDir, file.unixPath() + ".tmp");
if (destFile.exists() && destFile.length() == file.size) { totalDownloaded.addAndGet(file.size); return true; }
if (fileComplete(file, destFile)) { totalDownloaded.addAndGet(file.size); return true; }
String fileUrl = AmazonApiClient.appendPath(baseUrl, "files/" + file.hashHex());
for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
destFile.getParentFile().mkdirs();
@@ -256,6 +257,21 @@ public final class AmazonDownloadManager {
public static boolean isInstalled(File installDir) { return new File(installDir, COMPLETE_MARKER).exists(); }
static long remainingInstallBytes(List<AmazonManifest.ManifestFile> files, File installDir) {
long remaining = 0;
for (AmazonManifest.ManifestFile file : files) {
if (!fileComplete(file, new File(installDir, file.unixPath()))) remaining += file.size;
}
return remaining;
}
private static boolean fileComplete(AmazonManifest.ManifestFile file, File output) {
if (!output.isFile() || output.length() != file.size) return false;
if (file.hashAlgorithm != 0 || file.hashBytes.length == 0) return true;
try { return Arrays.equals(sha256(output), file.hashBytes); }
catch (Exception e) { return false; }
}
private static byte[] sha256(File file) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
try (FileInputStream fis = new FileInputStream(file)) {
@@ -128,7 +128,7 @@ object DownloadQueue {
}
}
private class Item(var entry: DownloadEntry, val factory: () -> DownloadJob, var job: DownloadJob? = null, val cancelled: AtomicBoolean = AtomicBoolean(false), var pauseRequested: Boolean = false) {
private class Item(var entry: DownloadEntry, val factory: (() -> DownloadJob)? = null, val retry: (() -> Unit)? = null, var job: DownloadJob? = null, val cancelled: AtomicBoolean = AtomicBoolean(false), var pauseRequested: Boolean = false) {
/** The shown speed's state: the last sample's clock and bytes, and the running average (bytes/s). */
var speedAt = 0L
var speedBytes = 0L
@@ -185,6 +185,32 @@ object DownloadQueue {
advance(app)
}
/** Immediately records a failed download (e.g. from pre-flight storage check). */
fun recordFailed(context: Context, entry: DownloadEntry, error: String, retry: (() -> Unit)? = null) {
val app = context.applicationContext
val now = System.currentTimeMillis()
synchronized(lock) {
if (items[entry.key]?.entry?.isActive == true) return
items.remove(entry.key)
heldPaused.remove(entry.key)
items[entry.key] = Item(
entry.copy(
state = DownloadState.FAILED,
error = error,
speedBps = 0,
etaSeconds = -1,
startedAt = now,
finishedAt = now
),
retry = retry
)
renumber()
publishLocked()
}
StoresState.logLine("${entry.store.label}: \"${entry.name}\" failed: $error")
StoreDownloadService.ended(app, entry.copy(state = DownloadState.FAILED, error = error), installed = false, gamesKey = null)
}
fun pause(key: String) {
val item = synchronized(lock) { items[key] } ?: return
synchronized(lock) {
@@ -199,14 +225,21 @@ object DownloadQueue {
fun resume(context: Context, key: String) {
val app = context.applicationContext
val retry: (() -> Unit)?
synchronized(lock) {
val item = items[key] ?: return
if (item.entry.state != DownloadState.PAUSED && item.entry.state != DownloadState.FAILED) return
retry = item.retry
if (retry == null && item.factory == null) return
items.remove(key)
items[key] = Item(item.entry.copy(state = DownloadState.QUEUED, speedBps = 0, etaSeconds = -1, error = null, startedAt = System.currentTimeMillis()), item.factory)
if (retry == null) {
items[key] = Item(item.entry.copy(state = DownloadState.QUEUED, speedBps = 0, etaSeconds = -1, error = null, startedAt = System.currentTimeMillis()), item.factory)
}
renumber()
publishLocked()
}
// A preflight retry rechecks storage and enqueues the real backend, never a running placeholder.
if (retry != null) { retry(); return }
StoresState.logLine("resumed \"${entry(key)?.name}\"")
advance(app)
}
@@ -231,7 +264,7 @@ object DownloadQueue {
item.job?.cancel(deleteFiles = true)
} else {
// Never started: nothing is on disk, but the job knows where it would have gone.
Thread({ runCatching { item.factory().cancel(deleteFiles = true) } }, "store-dl-cancel").start()
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-cancel").start()
}
StoresState.logLine("cancelled \"${item.entry.name}\"")
StoreDownloadService.finish(app, key)
@@ -248,7 +281,7 @@ object DownloadQueue {
val item = synchronized(lock) { items[key] } ?: return
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
if (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) {
Thread({ runCatching { item.factory().cancel(deleteFiles = true) } }, "store-dl-clear").start()
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-clear").start()
}
synchronized(lock) { items.remove(key); publishLocked() }
StoreDownloadService.finish(context.applicationContext, key)
@@ -343,7 +376,7 @@ object DownloadQueue {
var result: String? = null
var error: String? = null
try {
val job = item.factory()
val job = checkNotNull(item.factory).invoke()
synchronized(lock) { item.job = job }
StoresState.logLine("${item.entry.store.label}: fetching manifest for \"${item.entry.name}\"")
result = job.run(handle)
@@ -263,12 +263,16 @@ class StoreDownloadService : Service() {
val app = context.applicationContext
channels(app)
val code = entry.key.hashCode()
val n = Notification.Builder(app, DONE_CHANNEL)
val builder = Notification.Builder(app, DONE_CHANNEL)
.setSmallIcon(if (installed) android.R.drawable.stat_sys_download_done else android.R.drawable.stat_notify_error)
.setContentTitle(app.getString(if (installed) R.string.stores_notification_installed else R.string.stores_notification_failed, entry.name))
.setAutoCancel(true)
.setContentIntent(if (installed && gamesKey != null) openPage(app, gamesKey, code + 10) else openDownloads(app, code + 11))
.build()
if (!installed && !entry.error.isNullOrBlank()) {
builder.setContentText(entry.error)
builder.style = Notification.BigTextStyle().bigText(entry.error)
}
val n = builder.build()
runCatching { app.getSystemService(NotificationManager::class.java)?.notify(ID + 1 + (code and 0xFFFF), n) }
}
}
@@ -146,6 +146,8 @@ object EpicBackend : StoreBackend, EpicLaunchSupport {
EpicLibrary.rememberSize(app, item.id, diskBytes)
}
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
// Assembly overlaps chunk fetching; only the final install event advances the UI.
if (stage == "stream") return
handle.stage(when (stage) { "check" -> DownloadStage.MANIFEST; "verify" -> DownloadStage.VERIFY; else -> DownloadStage.INSTALL })
handle.stageProgress(done, total, items, itemsTotal, bytes = stage == "install")
}
File diff suppressed because it is too large. Load diff
@@ -9,17 +9,20 @@ import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
/**
* The native half of an Epic install 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. Everything around them (manifest, install tags, delta pass, post-install)
* stays in the manager.
* The native Epic engines in `libdroiddeckstores.so`. [stream] is the install the manager uses
* whenever the library loads: 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 with the same rules as the bounded Java
* writer (see `stream.rs`). [run] and [assemble] are the older batch pair: [run] fills the chunk
* cache with verified, decompressed chunks for the pending files, [assemble] writes the files from
* it. They stay for callers that explicitly want a whole-game cache.
*
* 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 like the Java loops they replace and poll [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. [run] and [assemble] flip the
* native flag on cancel and wait up to 5 s; [stream] waits for the run to finish, because its
* cleanup (removing unfinished staging files) must be done before the manager returns.
*/
object EpicNative {
private const val TAG = "EpicNative"
@@ -36,6 +39,18 @@ object EpicNative {
fun onComplete(success: Boolean, error: String, bytes: Long)
}
/** 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,
@@ -58,6 +73,59 @@ 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) }
/**
* The adaptive install of the files [pendingFileIdx] (indices into the manifest's file list),
* with at most [cacheBudget] bytes of shared chunks cached. `started == false` means nothing
* was fetched or written and the caller runs the bounded Java writer.
*/
@JvmStatic
fun stream(
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedBytes: Long,
cacheBudget: 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, cdnPrefixes, pendingFileIdx, expectedBytes, cacheBudget, 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}", 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 {
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, start: (Listener) -> Long): Result {
if (!StoresNative.ensureLoaded()) return Result(false, false, false, "engine not built", 0L, 0, 0)
val latch = CountDownLatch(1)
@@ -109,6 +177,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, cdnPrefixes: Array<String>, pendingFileIdx: IntArray, expectedBytes: Long,
cacheBudget: Long, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: StreamListener,
): Long
@JvmStatic
private external fun nativeCancel(handle: Long)
@@ -189,11 +189,12 @@ public final class GogDownloadManager {
installPath.mkdirs();
long plannedBytes = 0;
for (DepotFile df : files) plannedBytes += df.totalSize;
if (plannedBytes > 0) {
long usable = installPath.getUsableSpace();
if (usable > 0 && plannedBytes > usable) {
long remainingBytes = remainingInstallBytes(files, installPath);
if (remainingBytes > 0) {
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(remainingBytes, usable)) {
out.hardStop = true;
out.error = "Not enough free space: need " + formatBytes(plannedBytes) + ", only " + formatBytes(usable) + " free";
out.error = "Not enough free space: need " + formatBytes(remainingBytes) + ", only " + formatBytes(usable) + " free";
return out;
}
}
@@ -1018,7 +1019,16 @@ public final class GogDownloadManager {
for (File f : files) if (f.isDirectory()) collectExeRecursive(f, out);
}
private static final class DepotFile {
static long remainingInstallBytes(List<DepotFile> files, File installPath) {
long remaining = 0;
for (DepotFile file : files) {
File output = new File(installPath, file.relativePath);
if (!fileVerified(output, file.totalSize, file.md5)) remaining += file.totalSize;
}
return remaining;
}
static final class DepotFile {
final String relativePath;
final List<ChunkRef> chunks = new ArrayList<>();
String md5;
@@ -52,7 +52,9 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
val id = key.substringAfter(':')
val item = (StoresState.library[store].orEmpty() + StoresState.shelves[store]?.all.orEmpty()).firstOrNull { it.id == id }
val installed = StoresState.installedGame(store, id)
val download = StoresState.download("${store.id}:$id")?.takeIf { it.isActive }
val rawDownload = StoresState.download("${store.id}:$id")
val download = rawDownload?.takeIf { it.isActive }
val failedDownload = rawDownload?.takeIf { it.state == DownloadState.FAILED }
// Removal asks twice: one stray press of A should not cost a download.
val title = item?.title ?: installed?.sidecar?.title ?: id
Rise(0) {
@@ -79,12 +81,24 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
val state = when {
installed != null -> stringResource(R.string.stores_eyebrow_installed) + " · " + com.droiddeck.launcher.stores.StoreInstallRoot.labelFor(ctx, installed.folder)
download != null && download.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + download.location
failedDownload != null && failedDownload.location.isNotBlank() -> stringResource(R.string.stores_eyebrow_library) + " · " + failedDownload.location
item?.owned == true -> stringResource(R.string.stores_eyebrow_library)
else -> stringResource(R.string.stores_eyebrow_store)
}
val size = (item?.sizeBytes ?: 0L).takeIf { it > 0 }?.let { " · " + formatBytes(it) } ?: ""
Text((state + size).uppercase(), fontSize = 12.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 1.2.sp, color = pal.signal)
Text(title, fontSize = if (narrow) 24.sp else 30.sp, lineHeight = if (narrow) 27.sp else 33.sp, fontWeight = FontWeight.Black, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (!failedDownload?.error.isNullOrBlank()) {
Text(
failedDownload!!.error!!,
fontSize = 13.sp,
lineHeight = 17.sp,
fontWeight = FontWeight.Medium,
color = colors.error,
maxLines = 3,
overflow = TextOverflow.Ellipsis
)
}
Actions {
when {
installed != null -> {
@@ -106,6 +120,16 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro
else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) { com.droiddeck.launcher.stores.download.DownloadQueue.resume(ctx, download.key) }
ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { com.droiddeck.launcher.stores.download.DownloadQueue.cancel(ctx, download.key) }
}
failedDownload != null -> {
ActionChip(stringResource(R.string.stores_dl_failed), ok = false)
PrimaryButton(stringResource(R.string.stores_dl_resume), main = true) {
if (item != null) StoresState.requestInstall(ctx, item)
else com.droiddeck.launcher.stores.download.DownloadQueue.retry(ctx, failedDownload.key)
}
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) {
com.droiddeck.launcher.stores.download.DownloadQueue.clear(ctx, failedDownload.key)
}
}
item?.owned == true && StoresState.isUnfinished(item) -> {
InstallButton(stringResource(R.string.stores_resume_install)) { StoresState.requestInstall(ctx, item) }
ConfirmButton(stringResource(R.string.stores_dl_clear), stringResource(R.string.stores_dl_cancel_confirm), compact = true) { StoresState.clearUnfinished(ctx, item) }
@@ -339,6 +339,7 @@ private fun Modifier.timeRim(left: () -> Float, color: Color): Modifier = drawWi
@Composable
private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val narrow = LocalNarrowPane.current
val ink = Color.White
@@ -362,8 +363,11 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
val meta = when (d.state) {
DownloadState.INSTALLED -> stringResource(R.string.stores_installed_chip)
DownloadState.CANCELLED -> stringResource(R.string.stores_dl_cancelled)
// The reason is in the engine log; the row only says what is kept for Resume.
DownloadState.FAILED -> if (d.bytesDone > 0) stringResource(R.string.stores_dl_failed_kept, formatBytes(d.bytesDone)) else stringResource(R.string.stores_dl_failed)
DownloadState.FAILED -> {
if (!d.error.isNullOrBlank()) stringResource(R.string.stores_dl_failed_reason, d.error)
else if (d.bytesDone > 0) stringResource(R.string.stores_dl_failed_kept, formatBytes(d.bytesDone))
else stringResource(R.string.stores_dl_failed)
}
DownloadState.PAUSED -> stringResource(R.string.stores_dl_paused)
DownloadState.QUEUED -> if (d.queuePosition > 0) stringResource(R.string.stores_dl_queued_at, d.queuePosition) else stringResource(R.string.stores_dl_queued)
DownloadState.RUNNING -> {
@@ -375,7 +379,8 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
}
}
}
Text(meta, fontSize = 12.sp, color = dim, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
val metaColor = if (d.state == DownloadState.FAILED) colors.error else dim
Text(meta, fontSize = 12.sp, color = metaColor, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
if (d.state == DownloadState.RUNNING && (d.stage == DownloadStage.DOWNLOAD || d.stage == DownloadStage.INSTALL) && d.speedBps > 0) {
Text(formatSpeed(d.speedBps), fontSize = 12.sp, color = dim, maxLines = 1)
if (d.etaSeconds >= 0) Text(eta(d.etaSeconds), fontSize = 12.sp, color = dim, maxLines = 1)
@@ -393,7 +398,10 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions)
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.resume(ctx, d.key) }
CancelAction { DownloadQueue.cancel(ctx, d.key) }
}
DownloadState.FAILED -> RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
DownloadState.FAILED -> {
RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) }
CancelAction { DownloadQueue.clear(ctx, d.key) }
}
// Just installed (this row is on its way under the line): Play blooms where the bar gathered.
DownloadState.INSTALLED -> Box(Modifier.bloomIn(true, 420)) {
RoundAction(Icons.Filled.PlayArrow, stringResource(R.string.stores_play), primary = true) { launchStoreGame(ctx, d.store, d.id, s, a) }
@@ -460,6 +468,7 @@ private fun StageBar(d: DownloadEntry) {
val x = i * (segW + gap)
drawRoundRect(colors.surfaceVariant, Offset(x, cy - h / 2f), Size(segW, h), CornerRadius(h / 2f))
val base = when {
d.state == DownloadState.FAILED -> colors.error
done[i] -> pal.good
actives[i] && paused -> pausedColor.copy(alpha = breath)
actives[i] && stages[i] == DownloadStage.VERIFY -> verifyColor
@@ -72,10 +72,21 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
Rise(1) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
targets.forEachIndexed { i, t ->
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
val freeBytes = t.freeBytes
val isLow = com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, freeBytes)
val freeText = if (freeBytes < 0L) {
stringResource(R.string.stores_target_free_unknown)
} else if (isLow) {
stringResource(R.string.stores_storage_low, formatBytes(freeBytes), formatBytes(needed))
} else {
stringResource(R.string.stores_target_free, formatBytes(freeBytes))
}
TargetRow(
label = if (t.removable) t.label else stringResource(R.string.stores_target_internal),
free = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
free = freeText,
removable = t.removable, focus = focus[i],
warning = isLow,
) {
SessionPrefs.setStoresInstallTarget(ctx, t.root.absolutePath)
StoresState.install(ctx, item, t.root)
@@ -88,7 +99,7 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
}
@Composable
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, onPick: () -> Unit) {
private fun TargetRow(label: String, free: String, removable: Boolean, focus: FocusRequester, warning: Boolean = false, onPick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
@@ -104,6 +115,6 @@ private fun TargetRow(label: String, free: String, removable: Boolean, focus: Fo
) {
Icon(if (removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone, null, tint = if (hot) pal.signal else colors.onBackground, modifier = Modifier.size(22.dp))
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(free, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1)
Text(free, fontSize = 12.sp, color = if (warning) colors.error else colors.onSurfaceVariant, maxLines = 1)
}
}
@@ -511,10 +511,20 @@ private fun InstallWhere(item: CatalogItem) {
StepTitle(title)
StepList {
targets.forEachIndexed { i, t ->
val needed = com.droiddeck.launcher.stores.StoreInstallRoot.estimatedBytesNeeded(item)
val freeBytes = t.freeBytes
val isLow = com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, freeBytes)
val trailingText = if (freeBytes < 0L) {
stringResource(R.string.stores_target_free_unknown)
} else if (isLow) {
stringResource(R.string.stores_storage_low, formatBytes(freeBytes), formatBytes(needed))
} else {
stringResource(R.string.stores_target_free, formatBytes(freeBytes))
}
StepChoice(
label = if (t.removable) t.label else internalLabel,
icon = if (t.removable) androidx.compose.material.icons.Icons.Outlined.SdCard else androidx.compose.material.icons.Icons.Outlined.Smartphone,
trailing = stringResource(R.string.stores_target_free, formatBytes(t.freeBytes)),
trailing = trailingText,
enabled = open,
modifier = Modifier.fillMaxWidth().stepItem(1 + i).then(if (i == defaultIndex) Modifier.focusRequester(first) else Modifier),
) {
+3
View File
@@ -2257,6 +2257,9 @@
<string name="stores_install_title">Install %1$s:</string>
<string name="stores_target_internal">Internal</string>
<string name="stores_target_free">%1$s free</string>
<string name="stores_target_free_unknown">Free space unknown</string>
<string name="stores_storage_insufficient">Not enough free space: need %1$s, only %2$s free</string>
<string name="stores_storage_low">Insufficient space (%1$s free, need %2$s)</string>
<string name="stores_notification_channel">Store downloads</string>
<string name="stores_notification_channel_hint">Shows game download progress and keeps downloads running in the background</string>
<string name="stores_notification_one">Downloading</string>
+50 -1
View File
@@ -112,7 +112,12 @@ 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`, below): the chunks
are fetched in parallel and written straight into staged files as they arrive. The older batch
pair below (fetch everything into a cache, then assemble) stays for A/B benchmarks (the hidden
`storesEpicMode=batch` preference).
Two runs make up the native half of a batch Epic install:
1. **Fetch** (`nativeStart`): fills the chunk cache with verified, decompressed chunks for the
files the manager says are pending. The Kotlin manager still fetches and parses the manifest
@@ -224,6 +229,50 @@ 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;[IJJLjava/lang/String;IILjava/lang/Object;)J` (last parameter is the listener) | `Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeStream` |
```kotlin
@JvmStatic private external fun nativeStream(
manifest: ByteArray, installDir: String, chunkCacheDir: String, cdnPrefixes: Array<String>,
pendingFileIdx: IntArray, expectedBytes: Long, cacheBudget: Long, caBundlePath: String,
maxWorkers: Int, processWorkers: Int, listener: StreamListener,
): Long
```
Parameters as `nativeStart`, 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).
`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 that file's unique sibling `.droiddeck-epic-*.stage` file; 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 runs
its bounded Java writer.
| `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
+4
View File
@@ -18,6 +18,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
@@ -31,6 +34,7 @@ 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 =
@@ -177,6 +177,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 +435,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");
+189 -1
View File
@@ -7,7 +7,11 @@
//! 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, cdnPrefixes: String[],
//! pendingFileIdx: int[], expectedBytes: long, cacheBudget: 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 +21,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 +40,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")]
@@ -458,6 +468,184 @@ pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_native
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,
cdn_prefixes: JObjectArray,
pending_file_idx: JIntArray,
expected_bytes: jlong,
cache_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 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,
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,
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 handle = Box::new(EpicDownloadHandle { cancel });
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,
);
});
Box::into_raw(handle) as jlong
}
#[no_mangle]
pub extern "system" fn Java_com_droiddeck_launcher_stores_epic_EpicNative_nativeCancel(
_env: JNIEnv,
File diff suppressed because it is too large. Load diff
@@ -11,6 +11,7 @@ import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowStatFs
/** Where a store game goes: internal storage unless the user picks a card, and back to its own folder on a rerun. */
@RunWith(RobolectricTestRunner::class)
@@ -59,4 +60,87 @@ class StoreInstallRootTest {
assertTrue(dir.absolutePath.startsWith(app.cacheDir.absolutePath))
assertEquals("a_b_c", dir.name)
}
@Test fun estimatedBytesNeededUsesKnownInstallSizeForAllStores() {
val item = CatalogItem(Store.EPIC, "game1", "Game 1", imageUrl = null, owned = true, sizeBytes = 10_000_000L)
assertEquals(10_000_000L, StoreInstallRoot.estimatedBytesNeeded(item))
val gogItem = CatalogItem(Store.GOG, "game2", "Game 2", imageUrl = null, owned = true, sizeBytes = 10_000_000L)
assertEquals(10_000_000L, StoreInstallRoot.estimatedBytesNeeded(gogItem))
}
@Test fun checkStorageReportsEnoughWhenSpaceIsUnknownOrAvailable() {
val zeroItem = CatalogItem(Store.EPIC, "game1", "Game 1", imageUrl = null, owned = true, sizeBytes = 0L)
val check = StoreInstallRoot.checkStorage(app, zeroItem, StoreInstallRoot.internalRoot(app))
assertTrue(check.enough)
}
@Test fun availableBytesUsesNearestExistingAncestorWithoutCreatingDirectories() {
val existing = File(app.filesDir, "storage-probe").apply { mkdirs() }
val missing = File(existing, "not-created/another-level/game")
ShadowStatFs.registerStats(existing.path, 1024, 100, 100)
assertTrue(StoreInstallRoot.availableBytes(missing) > 0L)
assertFalse(File(existing, "not-created").exists())
}
@Test fun epicDefersFullSizeChecksToItsManifestDeltaForResume() {
val item = CatalogItem(Store.EPIC, "large", "Large", imageUrl = null, owned = true, sizeBytes = Long.MAX_VALUE)
val check = StoreInstallRoot.checkStorage(app, item, StoreInstallRoot.internalRoot(app))
assertTrue(check.enough)
assertEquals(Long.MAX_VALUE, check.requiredBytes)
}
@Test fun gogAndAmazonResumeChecksUseTheExistingVolumeAndDeferRemainingWork() {
val card = File(app.filesDir, "resume-card").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
for (store in listOf(Store.GOG, Store.AMAZON)) {
val item = CatalogItem(store, "resume-${store.id}", "Partial ${store.id}", imageUrl = null, sizeBytes = Long.MAX_VALUE)
val folder = File(StoreInstallRoot.storeDir(File(card, "Games"), store), StoreInstallRoot.folderName(item.title, item.id)).apply { mkdirs() }
StoreInstalls.begin(folder, store, item.id, item.title, null, null)
val check = StoreInstallRoot.checkStorage(app, item, StoreInstallRoot.internalRoot(app))
assertTrue(check.enough)
assertEquals(StoreInstallRoot.availableBytes(folder), check.availableBytes)
assertEquals(folder, StoreInstallRoot.folderFor(app, store, item.id, item.title))
}
}
@Test fun freshGogAndAmazonStillRejectInsufficientCatalogSpace() {
StoreInstallRoot.internalRoot(app).mkdirs()
ShadowStatFs.registerStats(StoreInstallRoot.internalRoot(app).path, 1024, 100, 100)
for (store in listOf(Store.GOG, Store.AMAZON)) {
val item = CatalogItem(store, "too-large-${store.id}", "Too large ${store.id}", imageUrl = null, sizeBytes = Long.MAX_VALUE)
assertFalse(StoreInstallRoot.checkStorage(app, item, StoreInstallRoot.internalRoot(app)).enough)
}
}
@Test fun measuredZeroRejectsFreshGogAndAmazonRatherThanBeingUnknown() {
val root = File(app.filesDir, "zero-space").apply { mkdirs() }
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
val missing = File(root, "not-created/game")
assertEquals(0L, StoreInstallRoot.availableBytes(missing))
assertFalse(File(root, "not-created").exists())
for (store in listOf(Store.GOG, Store.AMAZON)) {
val item = CatalogItem(store, "zero-${store.id}", "Zero ${store.id}", imageUrl = null, sizeBytes = 1L)
val check = StoreInstallRoot.checkStorage(app, item, missing)
assertFalse(check.enough)
assertEquals(0L, check.availableBytes)
}
}
@Test fun failedProbesAreUnknownAndDoNotCreateOrWriteToTargets() {
val root = File(app.filesDir, "read-only-probe").apply { mkdirs() }
val missing = File(root, "not-created/game")
val fail: (File) -> Long = { throw java.io.IOException("unavailable") }
assertEquals(-1L, StoreInstallRoot.probeAvailableBytes(missing, fail, fail))
assertEquals(-1L, StoreInstallRoot.probeAvailableBytes(missing, fail, { 0L }))
assertEquals(42L, StoreInstallRoot.probeAvailableBytes(missing, fail, { 42L }))
assertEquals(0L, StoreInstallRoot.probeAvailableBytes(missing, { 0L }, fail))
assertFalse(File(root, "not-created").exists())
assertTrue(root.listFiles().orEmpty().isEmpty())
assertFalse(StoreInstallRoot.insufficientSpace(1L, -1L))
assertTrue(StoreInstallRoot.insufficientSpace(1L, 0L))
assertFalse(StoreInstallRoot.insufficientSpace(1L, 1L))
assertFalse(StoreInstallRoot.insufficientSpace(0L, 0L))
}
}
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.stores.amazon
import java.io.File
import java.security.MessageDigest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowStatFs
import com.droiddeck.launcher.stores.StoreInstallRoot
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AmazonResumeSpaceTest {
@Test fun remainingWorkRejectsMeasuredZeroButNotUnknownSpace() {
val root = File(RuntimeEnvironment.getApplication().filesDir, "amazon-zero").apply { mkdirs() }
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
val files = listOf(AmazonManifest.ManifestFile("missing", 4, 0, null))
val needed = AmazonDownloadManager.remainingInstallBytes(files, root)
assertEquals(4L, needed)
assertTrue(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.availableBytes(root)))
assertFalse(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.SPACE_UNKNOWN))
}
@Test fun remainingSpaceExcludesVerifiedFilesButIncludesCorruptAndPartialFiles() {
val root = File(RuntimeEnvironment.getApplication().filesDir, "amazon-resume").apply { mkdirs() }
val data = byteArrayOf(1, 2, 3, 4)
val hash = MessageDigest.getInstance("SHA-256").digest(data)
val files = listOf("good", "corrupt", "partial", "missing").map {
AmazonManifest.ManifestFile(it, 4, 0, hash)
}
File(root, "good").writeBytes(data)
File(root, "corrupt").writeBytes(ByteArray(4))
File(root, "partial").writeBytes(byteArrayOf(1))
assertEquals(12L, AmazonDownloadManager.remainingInstallBytes(files, root))
for (file in files) File(root, file.unixPath()).writeBytes(data)
assertEquals(0L, AmazonDownloadManager.remainingInstallBytes(files, root))
}
}
@@ -0,0 +1,140 @@
package com.droiddeck.launcher.stores.download
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.*
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import org.junit.After
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.json.JSONArray
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowStatFs
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class DownloadQueueRetryTest {
private val app get() = RuntimeEnvironment.getApplication()
@After fun cleanRows() { DownloadQueue.dismissFinished(); StoreSizes.known.clear() }
private fun awaitFailure(key: String, error: String) {
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
while (System.nanoTime() < until) {
val entry = DownloadQueue.entry(key)
if (entry?.state == DownloadState.FAILED && entry.error == error) return
Thread.sleep(10)
}
fail("Expected failed real job: ${DownloadQueue.entry(key)}")
}
@Test fun storageRetryRechecksThenRunsTheRealBackendAndNormalRetryStillWorks() {
StoreInstallRoot.internalRoot(app).mkdirs()
ShadowStatFs.registerStats(StoreInstallRoot.internalRoot(app).path, 1024, 100, 100)
val item = CatalogItem(Store.GOG, "preflight-retry", "Preflight retry", imageUrl = null, sizeBytes = Long.MAX_VALUE)
val runs = AtomicInteger()
var lastTarget: File? = null
val previous = StoresState.backend(Store.GOG)
val backend = object : StoreBackend {
override val store = Store.GOG
override fun signIn(context: Context) {}
override fun signOut(context: Context) {}
override fun syncLibrary(context: Context, force: Boolean) {}
override fun loadShelves(context: Context, force: Boolean) {}
override fun uninstall(context: Context, game: InstalledStoreGame) {}
override fun install(context: Context, item: CatalogItem, root: File) {
lastTarget = root
DownloadQueue.enqueue(context, DownloadEntry(item.store, item.id, item.title)) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
throw IllegalStateException("backend-${runs.incrementAndGet()}")
}
override fun cancel(deleteFiles: Boolean) {}
}
}
}
}
StoresState.register(backend)
try {
StoresState.install(app, item)
assertEquals(DownloadState.FAILED, DownloadQueue.entry(item.key)?.state)
DownloadQueue.retry(app, item.key)
assertEquals(DownloadState.FAILED, DownloadQueue.entry(item.key)?.state)
assertEquals(0, runs.get())
StoreSizes.known[item.key] = 1
DownloadQueue.retry(app, item.key)
awaitFailure(item.key, "backend-1")
DownloadQueue.retry(app, item.key)
awaitFailure(item.key, "backend-2")
DownloadQueue.clear(app, item.key)
assertNull(DownloadQueue.entry(item.key))
// A card resume (including the restored paused path) must retain its real target.
val card = File(app.filesDir, "retry-card").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
val target = File(card, "Games")
val folder = File(StoreInstallRoot.storeDir(target, item.store), StoreInstallRoot.folderName(item.title, item.id)).apply { mkdirs() }
StoreInstalls.begin(folder, item.store, item.id, item.title, null, null)
StoreSizes.known[item.key] = Long.MAX_VALUE
StoresState.unfinished = StoreInstallRoot.unfinished(app)
DownloadQueue.holdPaused(item.key)
StoresState.requestInstall(app, item)
assertEquals(target, lastTarget)
assertEquals(DownloadState.PAUSED, DownloadQueue.entry(item.key)?.state)
assertEquals(2, runs.get())
val saved = File(app.filesDir, "store-queue.json")
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(5)
var correctSavedRoot = false
while (!correctSavedRoot && System.nanoTime() < until) {
correctSavedRoot = runCatching {
val rows = JSONArray(saved.readText())
(0 until rows.length()).any { i ->
val row = rows.getJSONObject(i)
row.getJSONObject("item").getString("id") == item.id &&
row.getString("root") == target.absolutePath && row.getBoolean("paused")
}
}.getOrDefault(false)
if (!correctSavedRoot) Thread.sleep(10)
}
assertTrue("Paused saved queue must remember the existing card root", correctSavedRoot)
DownloadQueue.clear(app, item.key)
} finally {
if (previous != null) StoresState.register(previous)
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
StoresState.unfinished = emptyList()
}
}
@Test fun preflightClearRemovesTheRowWithoutRunningItsRetry() {
val entry = DownloadEntry(Store.AMAZON, "clear-preflight", "Clear")
DownloadQueue.recordFailed(app, entry, "storage") { fail("Clear must not retry") }
DownloadQueue.clear(app, entry.key)
assertNull(DownloadQueue.entry(entry.key))
}
@Test fun heldPausedBackendRestoresAndResumesWithoutAPlaceholder() {
val entry = DownloadEntry(Store.GOG, "restored-paused", "Paused")
val ran = CountDownLatch(1)
DownloadQueue.holdPaused(entry.key)
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
ran.countDown()
throw IllegalStateException("restored")
}
override fun cancel(deleteFiles: Boolean) {}
}
}
assertEquals(DownloadState.PAUSED, DownloadQueue.entry(entry.key)?.state)
assertEquals(1L, ran.count)
DownloadQueue.resume(app, entry.key)
assertTrue(ran.await(5, TimeUnit.SECONDS))
awaitFailure(entry.key, "restored")
}
}
@@ -0,0 +1,57 @@
package com.droiddeck.launcher.stores.epic
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class EpicAdaptivePlanTest {
private val mib = 1024L * 1024
private val gib = 1024 * mib
@Test fun freshInstallsNeedNoOpenStagingAllowance() {
assertEquals(0L, EpicDownloadManager.adaptiveOpenStagingAllowance(emptyMap()))
val old = mapOf("big.pak" to 10 * gib, "small.pak" to gib)
assertEquals(10 * gib + EpicDownloadManager.ADAPTIVE_OPEN_WINDOW_BYTES, EpicDownloadManager.adaptiveOpenStagingAllowance(old))
assertEquals(100 * mib, EpicDownloadManager.adaptiveOpenStagingAllowance(mapOf("a" to 60 * mib, "b" to 40 * mib)))
}
@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 cardInstallKeepsTheCacheOnInternalScratchWhenItFits() {
val plan = EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, 30 * gib, true, 10 * gib)
assertNull(plan.error)
assertFalse(plan.cacheBesideGame)
assertEquals(EpicDownloadManager.ADAPTIVE_CACHE_MAX_BYTES, plan.cacheBudget)
assertEquals(20 * gib, plan.gameNeed)
assertEquals(plan.cacheBudget + EpicDownloadManager.ADAPTIVE_TRANSIENT_BYTES, plan.scratchNeed)
}
@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)
assertTrue(plan.gameNeed <= 30 * gib)
}
@Test fun shortStorageIsNamedWithTheShortfall() {
val card = EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, 10 * gib, true, 10 * gib)
assertTrue(card.error!!.contains("game's storage"))
assertTrue(card.error!!.contains("short by 10.0 GB"))
val internal = EpicDownloadManager.planAdaptiveSpace(20 * gib, gib, 20 * gib, false, -1)
assertTrue(internal.error!!.contains("game's storage"))
assertNull(EpicDownloadManager.planAdaptiveSpace(20 * gib, 0, -1, true, -1).error)
}
}
@@ -0,0 +1,445 @@
package com.droiddeck.launcher.stores.epic
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstalls
import java.io.File
import java.net.InetAddress
import java.net.ServerSocket
import java.net.SocketException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.security.MessageDigest
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import org.junit.After
import org.junit.Assert.*
import org.junit.Before
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
import org.robolectric.shadows.ShadowStatFs
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class EpicBoundedInstallTest {
@get:Rule val temp = TemporaryFolder()
private lateinit var server: ServerSocket
private lateinit var worker: Thread
private lateinit var manifest: EpicDownloadManager.Manifest
private lateinit var root: File
private val requests = AtomicInteger()
private val reject = AtomicBoolean()
private var bytes = ByteArray(256 * 1024) { (it % 251).toByte() }
@Before fun setUp() {
root = temp.newFolder("game")
ShadowStatFs.registerStats(root.path, 1_000_000_000, 1_000_000_000, 1_000_000_000)
server = ServerSocket(0, 8, InetAddress.getByName("127.0.0.1"))
worker = Thread {
while (!server.isClosed) {
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()
}
}
}.apply { start() }
val chunk = EpicDownloadManager.ChunkInfo().apply {
guid = intArrayOf(1, 0, 0, 0)
windowSize = bytes.size
fileSize = bytes.size.toLong()
sha1 = sha(bytes)
}
manifest = EpicDownloadManager.Manifest().apply {
chunkDir = "chunks"
uniqueChunks = arrayListOf(chunk)
cdnUrls = listOf(EpicDownloadManager.CdnUrl("http://127.0.0.1:${server.localPort}", "", ""))
files = arrayListOf(gameFile("game.bin", 0, bytes.size / 2), gameFile("game.bin.part", bytes.size / 2, bytes.size / 2))
}
}
@After fun tearDown() { server.close(); worker.join(6000); assertFalse(worker.isAlive) }
private fun sha(data: ByteArray) = MessageDigest.getInstance("SHA-1").digest(data)
private fun gameFile(name: String, offset: Int, size: Int) = EpicDownloadManager.FileInfo().apply {
filename = name
sha1 = sha(bytes.copyOfRange(offset, offset + size))
parts.add(EpicDownloadManager.ChunkPart().apply {
guid = intArrayOf(1, 0, 0, 0)
this.offset = offset
this.size = size
})
}
private fun install(cancel: AtomicBoolean = AtomicBoolean(), callback: EpicDownloadManager.Callback =
EpicDownloadManager.Callback { _, _ -> }, cache: String = "") =
EpicDownloadManager.installManifest(manifest, root.path, cache, null, cancel, callback)
private fun oldInstall() {
File(root, "game.bin").writeBytes(byteArrayOf(9, 8, 7))
File(root, "game.bin.part").writeBytes(byteArrayOf(6, 5, 4))
StoreGameSidecar(Store.EPIC, "game", "Game", "game.bin", installVersion = "old").write(root)
}
private fun assertOldInstallIntact() {
assertArrayEquals(byteArrayOf(9, 8, 7), File(root, "game.bin").readBytes())
assertArrayEquals(byteArrayOf(6, 5, 4), File(root, "game.bin.part").readBytes())
assertEquals("old", StoreGameSidecar.read(root)?.installVersion)
assertTrue(StoreGameSidecar.read(root)?.isInstalled == true)
assertTrue(root.walk().none { it.name.endsWith(".stage") })
}
@Test fun networkFailureAfterAcceptedPreflightPreservesInstalledFilesAndRecord() {
oldInstall()
reject.set(true)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertTrue(requests.get() > 0)
assertOldInstallIntact()
}
@Test fun hashFailureAfterAcceptedPreflightPreservesInstalledFilesAndRecord() {
oldInstall()
manifest.files.first().sha1 = ByteArray(20) { 1 }
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertOldInstallIntact()
}
@Test fun cancellationWhileStagingPreservesInstalledFilesAndRecord() {
oldInstall()
val cancel = AtomicBoolean()
assertNull(install(cancel, EpicDownloadManager.Callback { message, _ ->
if (message.startsWith("Downloading chunks (")) cancel.set(true)
}))
assertOldInstallIntact()
}
@Test fun laterFailureRetainsVerifiedSwapsAndMarksMixedUpdateResumable() {
oldInstall()
manifest.files.last().sha1 = ByteArray(20) { 1 }
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())
val record = StoreGameSidecar.read(root)!!
assertEquals(StoreGameSidecar.STATE_UPDATING, record.state)
assertFalse(record.isInstalled)
assertEquals("", record.installVersion)
StoreInstalls.begin(root, Store.EPIC, "game", "Game", null, null)
assertEquals("game.bin", StoreGameSidecar.read(root)?.exe)
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
}
@Test fun laterNetworkFailurePreservesTheUnreplacedOldFile() {
oldInstall()
val secondChunk = EpicDownloadManager.ChunkInfo().apply {
guid = intArrayOf(2, 0, 0, 0)
windowSize = bytes.size
fileSize = bytes.size.toLong()
sha1 = sha(bytes)
}
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) }
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)
assertTrue(root.walk().none { it.name.endsWith(".stage") })
}
@Test fun cancellationAfterFirstSwapLeavesAResumableMixedUpdate() {
oldInstall()
val cancel = AtomicBoolean()
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) cancel.set(true)
}
}
assertNull(install(cancel, callback))
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)
assertNotNull(install())
assertArrayEquals(bytes.copyOfRange(bytes.size / 2, bytes.size), File(root, "game.bin.part").readBytes())
// Registration, not an individual file swap, restores the installed state.
assertFalse(StoreGameSidecar.read(root)!!.isInstalled)
}
@Test fun atomicRenameFailurePreservesDestinationAndCleansStagingWithoutDeleteFallback() {
val destination = File(root, "game.bin").apply { mkdir() }
File(destination, "old-content").writeText("keep")
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertTrue(error.message.orEmpty().contains("atomically replace"))
assertEquals("keep", File(destination, "old-content").readText())
assertTrue(root.walk().none { it.name.endsWith(".stage") })
}
@Test fun safeStagingSpaceBoundaryRejectsWithoutReclaimingAllOldOutputs() {
// The first staged half-file must coexist with the shared chunk and BOTH old outputs.
val old = ByteArray(bytes.size / 2) { 9 }
File(root, "game.bin").writeBytes(old)
File(root, "game.bin.part").writeBytes(old)
val peak = bytes.size + old.size
ShadowStatFs.registerStats(root.path, 1024, peak / 4096 - 1, peak / 4096 - 1)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertEquals(0, requests.get())
assertArrayEquals(old, File(root, "game.bin").readBytes())
assertArrayEquals(old, File(root, "game.bin.part").readBytes())
ShadowStatFs.registerStats(root.path, 1024, peak / 4096, peak / 4096)
assertNotNull(install())
}
@Test fun zeroSpaceRejectsPendingFilesWhileUnknownSpaceIsNotTreatedAsZero() {
oldInstall()
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertOldInstallIntact()
assertEquals(0, requests.get())
assertTrue(com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(1, 0))
assertFalse(com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(1, -1))
}
@Test fun zeroScratchSpaceRejectsBeforeFetchWithoutTouchingInstalledOutputs() {
oldInstall()
val cache = temp.newFolder("full-scratch")
ShadowStatFs.registerStats(cache.path, 1024, 0, 0)
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install(cache = cache.path) }
assertTrue(error.message.orEmpty().contains("Not enough internal space"))
assertOldInstallIntact()
assertEquals(0, requests.get())
}
@Test fun installsSharedChunksAndPreservesLegitimatePartFilename() {
assertNotNull(install())
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
assertArrayEquals(bytes.copyOfRange(bytes.size / 2, bytes.size), File(root, "game.bin.part").readBytes())
assertEquals(1, requests.get())
assertFalse(File(root, ".chunks").exists())
assertNotNull(install())
assertEquals("Verified files must not be downloaded again", 1, requests.get())
}
private fun oversizedUpdate() {
val file = manifest.files[0]
val part = file.parts[0]
file.parts.clear()
repeat(100_000) {
file.parts.add(EpicDownloadManager.ChunkPart().apply {
guid = part.guid
size = Int.MAX_VALUE
})
}
}
@Test fun insufficientInstallSpacePreservesExistingFilesOnBothCacheLayouts() {
val oldGame = byteArrayOf(9, 8, 7)
val oldPart = byteArrayOf(6, 5, 4)
File(root, "game.bin").writeBytes(oldGame)
File(root, "game.bin.part").writeBytes(oldPart)
oversizedUpdate()
assertTrue(manifest.files[0].fileSize() > root.usableSpace)
for (cache in listOf("", temp.newFolder("scratch-rejected").path)) {
if (cache.isNotEmpty()) ShadowStatFs.registerStats(cache, 1_000_000_000, 1_000_000_000, 1_000_000_000)
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install(cache = cache) }
assertTrue(error.message.orEmpty().contains("Not enough free space"))
assertArrayEquals(oldGame, File(root, "game.bin").readBytes())
assertArrayEquals(oldPart, File(root, "game.bin.part").readBytes())
}
assertEquals(0, requests.get())
}
@Test fun acceptedUpdateReplacesOutdatedFilesWithVerifiedOutputs() {
oldInstall()
assertNotNull(install())
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
assertArrayEquals(bytes.copyOfRange(bytes.size / 2, bytes.size), File(root, "game.bin.part").readBytes())
assertEquals(StoreGameSidecar.STATE_UPDATING, StoreGameSidecar.read(root)?.state)
assertTrue(root.walk().none { it.name.endsWith(".stage") })
}
@Test fun pauseKeepsCompletedFilesAndResumeReusesSharedCache() {
val cancel = AtomicBoolean()
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) cancel.set(true)
}
}
assertNull(install(cancel, callback))
assertTrue(File(root, "game.bin").exists())
assertFalse(File(root, "game.bin.part").exists())
assertEquals(1, requests.get())
assertNotNull(install())
assertEquals(1, requests.get())
}
@Test fun cancellationDuringChunkDeliveryRemovesIncompleteOutput() {
val cancel = AtomicBoolean()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {
if (message.startsWith("Downloading chunks (")) cancel.set(true)
}
}
assertNull(install(cancel, callback))
assertFalse(File(root, "game.bin").exists())
assertNotNull(install())
assertArrayEquals(bytes.copyOfRange(0, bytes.size / 2), File(root, "game.bin").readBytes())
}
@Test fun fileHashFailureIsExplicitAndRetryRepairsIt() {
val expected = manifest.files[0].sha1
manifest.files[0].sha1 = ByteArray(20) { 1 }
val error = assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertTrue(error.message.orEmpty().contains("SHA-1 mismatch"))
assertFalse(File(root, "game.bin").exists())
manifest.files[0].sha1 = expected
assertNotNull(install())
}
@Test fun corruptCacheIsRefetchedAndScratchCacheIsRemovedOnSuccess() {
val cache = temp.newFolder("scratch")
ShadowStatFs.registerStats(cache.path, 1_000_000_000, 1_000_000_000, 1_000_000_000)
File(cache, manifest.uniqueChunks[0].guidStr()).writeBytes(ByteArray(bytes.size))
assertNotNull(install(cache = cache.path))
assertEquals(1, requests.get())
assertFalse(cache.exists())
}
@Test fun networkFailureLeavesNoCompletedFileAndCanBeRetried() {
reject.set(true)
assertThrows(EpicDownloadManager.InstallException::class.java) { install() }
assertFalse(File(root, "game.bin").exists())
reject.set(false)
assertNotNull(install())
}
@Test fun boundedProgressNeverReentersDownloadAfterEnteringInstall() {
val events = mutableListOf<String>()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {
if (message.startsWith("Downloading chunks")) events.add("download")
if (message.startsWith("Writing")) events.add("install")
}
override fun onBytes(done: Long, total: Long, speedBps: Long) { events.add("download") }
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
if (stage == "install") {
assertEquals(total, done)
assertEquals(itemsTotal, items)
events.add("install")
}
}
}
assertNotNull(install(callback = callback))
val firstInstall = events.indexOf("install")
assertTrue(firstInstall > 0)
assertFalse(events.drop(firstInstall).contains("download"))
}
@Test fun sharedChunksDoNotCompleteProgressBeforeTheRemainingFilesAreWritten() {
val samples = mutableListOf<Pair<Long, Long>>()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {}
override fun onBytes(done: Long, total: Long, speedBps: Long) { samples.add(done to total) }
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
if (stage == "stream" && items < itemsTotal) assertTrue(samples.last().first < samples.last().second)
}
}
assertNotNull(install(callback = callback))
assertEquals(listOf(0L, bytes.size / 2L, bytes.size.toLong()), samples.map { it.first })
assertTrue(samples.all { it.second == bytes.size.toLong() })
}
@Test fun evictedSharedChunksAdvanceWriteProgressOnEveryRefetchWithoutChangingStages() {
bytes = ByteArray((EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 1024).toInt()) { (it % 251).toByte() }
manifest.uniqueChunks.single().apply {
windowSize = bytes.size
fileSize = bytes.size.toLong()
sha1 = sha(bytes)
}
manifest.files = (0..2).map { gameFile("part-$it.bin", it * 1024, 1024) }
val chunk = manifest.uniqueChunks.single()
val estimatedPeak = EpicDownloadManager.estimatePeakAdditionalBytes(
manifest.files,
mapOf(chunk.guidStr() to chunk),
emptyMap(),
true,
)
assertEquals(EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 4 * 1024L, estimatedPeak)
val samples = mutableListOf<Long>()
val stages = mutableListOf<String>()
val callback = object : EpicDownloadManager.Callback {
override fun onProgress(message: String, pct: Int) {}
override fun onBytes(done: Long, total: Long, speedBps: Long) {
assertEquals(3072L, total)
assertFalse(stages.contains("install"))
samples.add(done)
}
override fun onStage(stage: String, done: Long, total: Long, items: Int, itemsTotal: Int) {
stages.add(stage)
if (stage == "stream" && items < itemsTotal) assertTrue(samples.last() < total)
}
}
assertNotNull(install(callback = callback))
assertEquals(3, 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()) }
}
@Test fun hogwartsSizedSequentialPlanFitsAvailableSpaceWithoutFullChunkCache() {
val gib = 1024L * 1024 * 1024
val file = EpicDownloadManager.FileInfo()
val chunks = LinkedHashMap<String, EpicDownloadManager.ChunkInfo>()
repeat(72) { index ->
val chunk = EpicDownloadManager.ChunkInfo().apply {
guid = intArrayOf(index + 1, 0, 0, 0)
windowSize = gib.toInt()
}
chunks[chunk.guidStr()] = chunk
file.parts.add(EpicDownloadManager.ChunkPart().apply {
guid = chunk.guid
size = chunk.windowSize
})
}
val peak = EpicDownloadManager.estimatePeakAdditionalBytes(listOf(file), chunks, emptyMap(), true)
assertEquals(73 * gib, peak)
assertTrue(peak < 96 * gib)
}
@Test fun plannersReclaimEachOldFileOnlyAfterItsOwnVerifiedSwap() {
val chunks = manifest.uniqueChunks.associateBy { it.guidStr() }
val half = bytes.size / 2L
val old = mapOf("game.bin" to half, "game.bin.part" to 100 * half)
assertEquals(bytes.size + half, EpicDownloadManager.estimatePeakAdditionalBytes(manifest.files, chunks, emptyMap(), true, old))
assertEquals(half, EpicDownloadManager.estimateStagedFilePeak(manifest.files, old))
assertEquals(2 * half, EpicDownloadManager.estimateStagedFilePeak(manifest.files, emptyMap()))
assertEquals(bytes.size.toLong(), EpicDownloadManager.estimatePeakAdditionalBytes(manifest.files, chunks, emptyMap(), false, old))
}
}
@@ -1,8 +1,10 @@
package com.droiddeck.launcher.stores.epic
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@@ -12,6 +14,103 @@ import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class EpicJsonManifestTest {
@Test
fun boundedInstallPeakCountsOnlyOneLiveChunkForSequentialChunks() {
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))
}
@Test
fun sharedCachedChunkIsReclaimedOnlyAfterItsLastPart() {
val shared = chunk(1)
val files = listOf(file(part(1, 0, 60)), file(part(1, 60, 40)))
assertEquals(
100L,
EpicDownloadManager.estimatePeakAdditionalBytes(
files, mapOf(shared.guidStr() to shared), mapOf(shared.guidStr() to 100L), true,
),
)
assertEquals(
200L,
EpicDownloadManager.estimatePeakAdditionalBytes(
files, mapOf(shared.guidStr() to shared), emptyMap(), true,
),
)
}
@Test
fun distantSharedChunksAreEvictedAndRefetchedWithinTheCacheCeiling() {
val first = chunk(1).apply { windowSize = 40 * 1024 * 1024 }
val second = chunk(2).apply { windowSize = 40 * 1024 * 1024 }
val files = listOf(
file(part(1, 0, 40 * 1024 * 1024)),
file(part(2, 0, 40 * 1024 * 1024)),
file(part(1, 0, 40 * 1024 * 1024)),
file(part(2, 0, 40 * 1024 * 1024)),
)
val chunks = mapOf(first.guidStr() to first, second.guidStr() to second)
val gamePeak = EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), true)
val cachePeak = EpicDownloadManager.estimatePeakAdditionalBytes(files, chunks, emptyMap(), false)
assertEquals(200L * 1024 * 1024, gamePeak)
assertTrue(cachePeak <= EpicDownloadManager.MAX_RETAINED_CHUNK_CACHE_BYTES + 40L * 1024 * 1024)
}
@Test
fun resumeCacheDropsCorruptAndUnneededEntriesButKeepsVerifiedChunks() {
val dir = java.io.File(System.getProperty("user.dir"), "build/epic-cache-test-${System.nanoTime()}")
assertTrue(dir.mkdirs())
try {
val bytes = ByteArray(100) { (it % 251).toByte() }
val expectedSha = java.security.MessageDigest.getInstance("SHA-1").digest(bytes)
val valid = chunk(1).apply { sha1 = expectedSha }
val corrupt = chunk(2).apply { sha1 = expectedSha }
java.io.File(dir, valid.guidStr()).writeBytes(bytes)
java.io.File(dir, corrupt.guidStr()).writeBytes(ByteArray(100) { 1 })
java.io.File(dir, "orphan").writeBytes(bytes)
val retained = EpicDownloadManager.prepareBoundedCache(dir, listOf(valid, corrupt))
assertEquals(mapOf(valid.guidStr() to 100L), retained)
assertTrue(java.io.File(dir, valid.guidStr()).exists())
assertFalse(java.io.File(dir, corrupt.guidStr()).exists())
assertFalse(java.io.File(dir, "orphan").exists())
} finally {
EpicDownloadManager.deleteDir(dir)
}
}
@Test
fun referenceCountsIncludeRepeatedPartsSoCancelledFilesCanBeReplanned() {
val pending = listOf(file(part(1, 0, 20), part(1, 20, 20)), file(part(1, 40, 60)))
assertEquals(3, EpicDownloadManager.chunkReferences(pending)["00000001000000000000000000000000"])
}
private fun chunk(id: Int) = EpicDownloadManager.ChunkInfo().apply {
guid = intArrayOf(id, 0, 0, 0)
windowSize = 100
fileSize = 100
}
private fun part(id: Int, offset: Int, size: Int) = EpicDownloadManager.ChunkPart().apply {
guid = intArrayOf(id, 0, 0, 0)
this.offset = offset
this.size = size
}
private fun file(vararg parts: EpicDownloadManager.ChunkPart) = EpicDownloadManager.FileInfo().apply {
filename = "test.bin"
this.parts.addAll(parts)
}
@Test
fun blobNumbersAreDecimalBytesLeastSignificantFirst() {
assertEquals(1L, EpicDownloadManager.blobToNum("001000000000"))
@@ -0,0 +1,43 @@
package com.droiddeck.launcher.stores.gog
import java.io.File
import java.security.MessageDigest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.shadows.ShadowStatFs
import com.droiddeck.launcher.stores.StoreInstallRoot
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogResumeSpaceTest {
@Test fun remainingWorkRejectsMeasuredZeroButNotUnknownSpace() {
val root = File(RuntimeEnvironment.getApplication().filesDir, "gog-zero").apply { mkdirs() }
ShadowStatFs.registerStats(root.path, 1024, 0, 0)
val files = listOf(GogDownloadManager.DepotFile("missing").apply { totalSize = 4 })
val needed = GogDownloadManager.remainingInstallBytes(files, root)
assertEquals(4L, needed)
assertTrue(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.availableBytes(root)))
assertFalse(StoreInstallRoot.insufficientSpace(needed, StoreInstallRoot.SPACE_UNKNOWN))
}
@Test fun remainingSpaceExcludesVerifiedFilesButIncludesCorruptAndPartialFiles() {
val root = File(RuntimeEnvironment.getApplication().filesDir, "gog-resume").apply { mkdirs() }
val data = byteArrayOf(1, 2, 3, 4)
val hash = MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) }
val files = listOf("good", "corrupt", "partial", "missing").map {
GogDownloadManager.DepotFile(it).apply { totalSize = 4; md5 = hash }
}
File(root, "good").writeBytes(data)
File(root, "corrupt").writeBytes(ByteArray(4))
File(root, "partial").writeBytes(byteArrayOf(1))
assertEquals(12L, GogDownloadManager.remainingInstallBytes(files, root))
for (file in files) File(root, file.relativePath).writeBytes(data)
assertEquals(0L, GogDownloadManager.remainingInstallBytes(files, root))
}
}
+102 -10
View File
@@ -24,15 +24,96 @@ scanned (`StoreInstallRoot.roots`): internal, every card, and the Steam library'
installs an earlier build put there. `<Store>` is `GOG`, `Epic` or `Amazon`; `<title>` is the title
with unsafe characters dropped, at most 60 characters (`StoreInstallRoot.folderName`), chosen once;
a rerun (repair, update) lands on the folder whose sidecar carries the game's id, wherever it is.
An Epic install on a card keeps its in-flight chunks in `cacheDir/stores/epic/<id>/`: the
`chunkCacheDir` of both native calls (`EpicNative.run` fetches into it, `EpicNative.assemble`
writes the files from it and drops each chunk after its last use, then the folder), and of the
manager's own loops when the engine is not there; `""` keeps the cache beside the game, as an
internal install has it. The scratch folder is removed on cancel-with-delete and on uninstall.
The cache holds whole ~1 MiB chunk windows, shared with files this device does not install, so it
is often larger than the game (Metalstorm: 9.1 GB of chunks for 4.4 GB of files); the free-space
check, made after the delta pass, counts the missing chunks and the missing files on their own
volumes. A successful run removes the cache.
An Epic install on a card keeps its in-flight chunks in `cacheDir/stores/epic/<id>/`;
`""` keeps the cache beside the game, as an internal install has it. The scratch folder is
removed on cancel-with-delete and on uninstall.
Preflight resolves an existing game's folder before selecting its target root, so a resume or
repair on a card checks and remembers that volume rather than internal storage. Fresh GOG and
Amazon installs can reject insufficient catalog-size space immediately; existing installs defer
to manifest checks of the files still needing work (GOG MD5, Amazon SHA-256 where supplied).
Free-space display probes the nearest existing ancestor without creating the target folder; if
the probe cannot determine space, it reports **Free space unknown** rather than blocking an install.
`StoreInstallRoot` uses `-1` for unknown and preserves a measured `StatFs` zero as **0 B free**.
Fresh GOG/Amazon preflight and all three Java backend space checks reject known zero when bytes
remain. The read-only probe walks existing ancestors without creating directories; a failed
`StatFs` probe can use a positive `File.usableSpace` fallback, but that API's ambiguous zero is
unknown, not a measurement of a full disk.
Preflight failures remain failed Downloads rows with Clear and Retry. Retry reruns preflight
outside the worker lifecycle and then enqueues the real backend; it never occupies a queue slot
with a placeholder job. Failures are kept in the Downloads UI, notification and logs rather than
duplicated as transient failure toasts. Active queue persistence and ordinary backend pause/retry
are unchanged.
Epic installs have three writers, all with the same per-file safety rules (below):
- **Adaptive (default when `libdroiddeckstores.so` loads)** - `EpicNative.stream`,
`epic/stream.rs`. 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; no cache. 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). 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, average MB/s).
- **Bounded Java** - when the library does not load or link, when the engine refuses the plan,
or when the adaptive space plan does not fit while this one might. 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. It logs
`epic: summary 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.
It logs `epic: summary mode=batch`.
The writer is chosen by the hidden `storesEpicMode` string in the `session` preferences:
`adaptive` (default), `batch` or `java`. There is no UI for it; set it on a test device to compare
the modes on the same game.
The adaptive space plan (`EpicDownloadManager.planAdaptiveSpace`, unit-tested in
`EpicAdaptivePlanTest`) checks each volume for what lands on it. The game volume: the sequential
staged-file peak (remaining file bytes, each replaced file's old copy credited only after its
swap), plus, for an update, the largest old file plus 256 MiB for files finishing out of order
within the fetch window, plus the cache when it is beside the game. The cache volume: the budget
plus 64 MiB of chunks in transit. The 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 names the short storage and the shortfall in the log
and hands over to the bounded writer, whose own checks decide. 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.
The Epic download bar, measured rate and ETA (adaptive and bounded) 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
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
must accept this safe staging peak; insufficient space is rejected explicitly, with no destructive
delete-first fallback. An unsupported/failed atomic rename fails the install and retains the old
destination. Completed files and
verified cached chunks are accounted for on resume. On a card, game and cache requirements
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.
## The sidecar
@@ -59,7 +140,18 @@ store root whose sidecar says `installing`, or that has no sidecar at all, is an
install: `AddedGames.scan` leaves it out (it is neither a game nor a Custom folder), and the Stores
card and page offer **Resume install**, which reuses that folder - and an Epic `.chunks` beside it -
instead of starting a fresh one (`StoreInstallRoot.existingFolder`). A finished install being
repaired keeps its finished sidecar. The launcher and the finished sidecar are written before the
repaired keeps its finished sidecar until Epic reaches the first verified file swap. Immediately
before that swap Epic atomically changes the record to `"state": "updating"`, preserves launch
choices and identifiers, and clears `installVersion`. Network/hash failures or cancellation before
that point leave the old installed record and files intact. A later failure can leave a mixture of
verified new files and untouched old files: replacement is atomic **per file**, not a transactional
whole-game update or rollback. The updating folder is excluded from installed scans and offered
for resume. Cancellation with deletion clears caches but retains that folder and its verified
swaps; retry preserves the updating record's metadata. If marking or swapping fails, no destructive
fallback is attempted (the conservative updating state can remain even when a swap fails).
Completion writes the installed record with the new version only after all selected files succeed.
An already registered live Steam shortcut is not revoked at each file swap; do not launch an
in-progress update. The launcher and the finished sidecar are written before the
art and the Steam registration; a failure writing them fails the download with its message.
`StoreGameSidecar.parse` refuses anything whose `exe` or `launcher` would point outside the folder.
+1
View File
@@ -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']