Compare commits

...
1 Commits
Author SHA1 Message Date
maxjivi05 84d5fb5ba9 Keep SD card downloads cancellable and let uninstall stop them
exFAT cannot store sparse files, so a write far past the end of a file
makes the kernel zero-fill the whole gap in one uninterruptible call.
Steam, Epic and EA installs write chunks out of order, so a single write
on an SD card could block for minutes, holding up cancel, uninstall and
the storage service.

Probe each install folder for hole support once. On storage without it,
grow files in bounded zero-filled steps that check the cancel flag, and
queue Steam chunks in file offset order. Uninstall now cancels a running
download or update of the game and waits for it to stop instead of
refusing.
2026-11-26 21:24:26 -05:00
9 changed files with 433 additions and 30 deletions

No files matched your search

@@ -318,7 +318,7 @@ object StoresState {
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
uninstalling[key] = 0f
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
if (!com.droiddeck.launcher.stores.download.DownloadQueue.holdForRemovalWhenFree(key)) {
if (!com.droiddeck.launcher.stores.download.DownloadQueue.stopForRemoval(app, key)) {
logLine("kept \"${game.sidecar.title}\": its download or update is still running")
main.post { uninstalling.remove(key); onDone() }
return@background
@@ -9,6 +9,7 @@ import java.util.concurrent.atomic.AtomicBoolean
object DownloadQueue {
private const val TAG = "StoreDownloads"
private const val REMOVAL_WAIT_MS = 30_000L
interface DownloadJob {
fun run(handle: JobHandle): String?
@@ -120,17 +121,24 @@ object DownloadQueue {
fun releaseRemoval(key: String) { synchronized(lock) { removing.remove(key); (lock as Object).notifyAll() } }
fun holdForRemovalWhenFree(key: String): Boolean = synchronized(lock) {
while (true) {
val item = items[key]
if (item?.entry?.isActive == true || item?.job != null) return@synchronized false
if (key !in cleaningUp && key !in removing) break
(lock as Object).wait()
fun stopForRemoval(context: Context, key: String): Boolean {
if (synchronized(lock) { busyLocked(key) }) cancel(context, key)
val deadline = android.os.SystemClock.uptimeMillis() + REMOVAL_WAIT_MS
return synchronized(lock) {
while (true) {
val busy = busyLocked(key)
if (!busy && key !in cleaningUp && key !in removing) break
val left = deadline - android.os.SystemClock.uptimeMillis()
if (busy && left <= 0) return@synchronized false
(lock as Object).wait(if (busy) left else 0L)
}
removing.add(key)
true
}
removing.add(key)
true
}
private fun busyLocked(key: String): Boolean = items[key].let { it?.entry?.isActive == true || it?.job != null }
private fun beginCleanup(key: String): Boolean = synchronized(lock) {
if (key in removing) return@synchronized false
cleaningUp.merge(key, 1, Int::plus)
@@ -412,6 +420,7 @@ object DownloadQueue {
}
item.job = null
publishLocked()
(lock as Object).notifyAll()
}
when (item.entry.state) {
DownloadState.INSTALLED -> {
@@ -282,7 +282,7 @@ internal object SteamStore {
if (key in StoresState.uninstalling) return
StoresState.uninstalling[key] = 0f
Thread({
if (!DownloadQueue.holdForRemovalWhenFree(key)) {
if (!DownloadQueue.stopForRemoval(app, key)) {
StoresState.logLine("Steam: kept $appId, its download is still running")
StoresState.post { StoresState.uninstalling.remove(key); onDone() }
return@Thread
+7 -3
View File
@@ -5,7 +5,6 @@
use std::collections::{HashMap, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Write};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Mutex;
@@ -18,6 +17,7 @@ use super::net;
use super::zip::{self, Entry};
use crate::amazon::install::check::{free_bytes, space_problem};
use crate::amazon::install::{Events, ReplaceGate, Stop};
use crate::grow_write::{holes_supported, GrowFront};
use crate::fetch_core::{distinct_host_count, run_fetch, FetchItem, FetchOptions, FetchSink, SinkError};
pub const LEDGER: &str = ".droiddeck-ea-files";
@@ -37,6 +37,7 @@ struct Split {
file: Mutex<Option<File>>,
received: Vec<AtomicU64>,
left: AtomicUsize,
front: GrowFront,
}
#[derive(Clone, Copy)]
@@ -483,8 +484,9 @@ impl Placer<'_> {
let old = split.received[part].swap(0, Ordering::Relaxed);
self.in_flight.fetch_sub(old, Ordering::Relaxed);
}
handle
.write_all_at(data, start + offset)
split
.front
.write_all_at(handle, start + offset, data, self.stop)
.map_err(|e| SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path))))?;
drop(file);
split.received[part].fetch_add(data.len() as u64, Ordering::Relaxed);
@@ -698,6 +700,7 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
let host = origin(&req.url);
let works = works(&remote, req.part_bytes);
let holes = holes_supported(&req.game_dir);
let splits: Vec<Option<Split>> = remote
.iter()
.enumerate()
@@ -711,6 +714,7 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
file: Mutex::new(None),
received: (0..parts).map(|_| AtomicU64::new(0)).collect(),
left: AtomicUsize::new(parts),
front: GrowFront::new(holes),
}
})
})
@@ -8,6 +8,7 @@ use std::time::{Duration, Instant};
use sha1::{Digest, Sha1};
use super::cache;
use crate::grow_write::{holes_supported, GrowFront};
use super::schedule::{PlanPart, Schedule, NONE};
use super::{staging, Events, Stop};
use crate::epic::chunk;
@@ -80,6 +81,7 @@ struct Coord {
struct Engine<'a> {
input: &'a EngineInput<'a>,
slots: Vec<Mutex<Slot>>,
fronts: Vec<GrowFront>,
coord: Mutex<Coord>,
wake: Condvar,
admitted: AtomicUsize,
@@ -182,8 +184,8 @@ impl<'a> Engine<'a> {
let Some(handle) = handle else {
return Err(format!("internal: {} is not open", file.path));
};
handle
.write_all_at(piece, part.file_offset)
self.fronts[f]
.write_all_at(&handle, part.file_offset, piece, self.stop)
.map_err(|e| format!("Could not assemble or atomically replace {}: {e}", file.path))?;
self.written.fetch_add(piece.len() as u64, Ordering::Relaxed);
@@ -446,8 +448,10 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
cached[i] = true;
}
}
let holes = holes_supported(&input.stage_dir);
let engine = Engine {
input,
fronts: input.files.iter().map(|_| GrowFront::new(holes)).collect(),
slots: input
.files
.iter()
+294
View File
@@ -0,0 +1,294 @@
use std::fs::{self, File, OpenOptions};
use std::io;
use std::os::unix::fs::{FileExt, MetadataExt, OpenOptionsExt};
use std::path::Path;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Mutex;
pub const FILL_STEP: usize = 4 * 1024 * 1024;
pub const DIRECT_GAP: u64 = 4 * 1024 * 1024;
const PROBE_GAP: u64 = 1024 * 1024;
static PROBE_SEQ: AtomicU64 = AtomicU64::new(0);
const PROBE_PREFIX: &str = ".droiddeck-hole-probe-";
pub fn holes_supported(dir: &Path) -> bool {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
let stale = entry.file_name().to_string_lossy().starts_with(PROBE_PREFIX)
&& entry.file_type().map(|t| t.is_file()).unwrap_or(false);
if stale {
let _ = fs::remove_file(entry.path());
}
}
}
let probe = dir.join(format!(
"{PROBE_PREFIX}{}-{}",
std::process::id(),
PROBE_SEQ.fetch_add(1, Ordering::Relaxed)
));
let Ok(file) = OpenOptions::new()
.write(true)
.create_new(true)
.custom_flags(libc::O_NOFOLLOW)
.open(&probe)
else {
return true;
};
let written = file.write_all_at(&[0u8], PROBE_GAP - 1);
drop(file);
let measured = written.and_then(|_| fs::symlink_metadata(&probe));
let _ = fs::remove_file(&probe);
measured
.map(|meta| meta.blocks().saturating_mul(512) < PROBE_GAP)
.unwrap_or(true)
}
pub struct GrowFront {
holes: bool,
size: AtomicU64,
known: AtomicBool,
fill: Mutex<()>,
}
impl GrowFront {
pub fn new(holes: bool) -> Self {
GrowFront {
holes,
size: AtomicU64::new(0),
known: AtomicBool::new(false),
fill: Mutex::new(()),
}
}
pub fn reset(&self) {
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
self.known.store(false, Ordering::Release);
self.size.store(0, Ordering::Release);
}
pub fn write_all_at(
&self,
file: &File,
offset: u64,
data: &[u8],
cancel: &AtomicBool,
) -> io::Result<()> {
let end = offset.saturating_add(data.len() as u64);
if self.holes
|| (self.known.load(Ordering::Acquire) && end <= self.size.load(Ordering::Acquire))
{
return file.write_all_at(data, offset);
}
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
let mut size = self.current(file)?;
if offset > size.saturating_add(DIRECT_GAP) {
self.fill_to(file, &mut size, offset - DIRECT_GAP, cancel)?;
}
if let Err(err) = file.write_all_at(data, offset) {
self.known.store(false, Ordering::Release);
return Err(err);
}
self.publish(size.max(end));
Ok(())
}
pub fn extend_to(&self, file: &File, len: u64, cancel: &AtomicBool) -> io::Result<()> {
if self.holes {
return file.set_len(len);
}
let _guard = self.fill.lock().unwrap_or_else(|e| e.into_inner());
let mut size = self.current(file)?;
if size < len {
self.fill_to(file, &mut size, len, cancel)?;
}
Ok(())
}
fn current(&self, file: &File) -> io::Result<u64> {
if self.known.load(Ordering::Acquire) {
Ok(self.size.load(Ordering::Acquire))
} else {
Ok(file.metadata()?.len())
}
}
fn fill_to(
&self,
file: &File,
size: &mut u64,
target: u64,
cancel: &AtomicBool,
) -> io::Result<()> {
let zeros = vec![0u8; FILL_STEP];
while *size < target {
if cancel.load(Ordering::Relaxed) {
self.publish(*size);
return Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled"));
}
let step = ((target - *size) as usize).min(FILL_STEP);
if let Err(err) = file.write_all_at(&zeros[..step], *size) {
self.known.store(false, Ordering::Release);
return Err(err);
}
*size += step as u64;
self.publish(*size);
}
Ok(())
}
fn publish(&self, size: u64) {
self.size.store(size, Ordering::Release);
self.known.store(true, Ordering::Release);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
fn temp_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!(
"grow-write-{tag}-{}-{}",
std::process::id(),
PROBE_SEQ.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&dir).unwrap();
dir
}
fn open(path: &Path) -> File {
OpenOptions::new()
.create(true)
.read(true)
.write(true)
.truncate(false)
.open(path)
.unwrap()
}
#[test]
fn far_write_fills_the_gap_in_bounded_steps_and_keeps_data() {
let dir = temp_dir("far");
let path = dir.join("f.bin");
let file = open(&path);
let front = GrowFront::new(false);
let cancel = AtomicBool::new(false);
front.write_all_at(&file, 0, b"head", &cancel).unwrap();
let far = 3 * FILL_STEP as u64 + 123;
front.write_all_at(&file, far, b"tail", &cancel).unwrap();
front.write_all_at(&file, 100, b"mid", &cancel).unwrap();
let bytes = fs::read(&path).unwrap();
assert_eq!(bytes.len() as u64, far + 4);
assert_eq!(&bytes[0..4], b"head");
assert_eq!(&bytes[100..103], b"mid");
assert_eq!(&bytes[far as usize..], b"tail");
assert!(bytes[103..far as usize].iter().all(|b| *b == 0));
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn cancel_stops_a_gap_fill_between_steps() {
let dir = temp_dir("cancel");
let path = dir.join("f.bin");
let file = open(&path);
let front = GrowFront::new(false);
let cancel = AtomicBool::new(true);
let err = front
.write_all_at(&file, 8 * FILL_STEP as u64, b"x", &cancel)
.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::Interrupted);
assert_eq!(fs::metadata(&path).unwrap().len(), 0);
cancel.store(false, Ordering::Relaxed);
front.write_all_at(&file, 10, b"ok", &cancel).unwrap();
assert_eq!(&fs::read(&path).unwrap()[10..], b"ok");
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn concurrent_writers_never_lose_data_to_the_fill() {
let dir = temp_dir("race");
let path = dir.join("f.bin");
let file = Arc::new(open(&path));
let front = Arc::new(GrowFront::new(false));
let piece = 64 * 1024u64;
let count = 256u64;
let mut order: Vec<u64> = (0..count).collect();
order.reverse();
let lanes: Vec<Vec<u64>> = (0..4)
.map(|lane| order.iter().copied().filter(|i| i % 4 == lane).collect())
.collect();
let handles: Vec<_> = lanes
.into_iter()
.map(|lane| {
let file = Arc::clone(&file);
let front = Arc::clone(&front);
std::thread::spawn(move || {
let cancel = AtomicBool::new(false);
for i in lane {
let data = vec![(i % 251) as u8 + 1; piece as usize];
front.write_all_at(&file, i * piece, &data, &cancel).unwrap();
}
})
})
.collect();
for handle in handles {
handle.join().unwrap();
}
let bytes = fs::read(&path).unwrap();
assert_eq!(bytes.len() as u64, piece * count);
for i in 0..count {
let start = (i * piece) as usize;
assert!(bytes[start..start + piece as usize]
.iter()
.all(|b| *b == (i % 251) as u8 + 1));
}
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn extend_to_grows_in_steps_and_never_shrinks() {
let dir = temp_dir("extend");
let path = dir.join("f.bin");
let file = open(&path);
let front = GrowFront::new(false);
let cancel = AtomicBool::new(false);
front.write_all_at(&file, 0, b"data", &cancel).unwrap();
let len = 2 * FILL_STEP as u64 + 7;
front.extend_to(&file, len, &cancel).unwrap();
front.extend_to(&file, 2, &cancel).unwrap();
let bytes = fs::read(&path).unwrap();
assert_eq!(bytes.len() as u64, len);
assert_eq!(&bytes[0..4], b"data");
assert!(bytes[4..].iter().all(|b| *b == 0));
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn hole_capable_storage_writes_directly() {
let dir = temp_dir("holes");
let path = dir.join("f.bin");
let file = open(&path);
let front = GrowFront::new(true);
let cancel = AtomicBool::new(true);
front
.write_all_at(&file, 8 * FILL_STEP as u64, b"x", &cancel)
.unwrap();
assert_eq!(fs::metadata(&path).unwrap().len(), 8 * FILL_STEP as u64 + 1);
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[test]
fn probe_leaves_nothing_behind() {
let dir = temp_dir("probe");
let _ = holes_supported(&dir);
assert_eq!(fs::read_dir(&dir).unwrap().count(), 0);
fs::remove_dir(&dir).unwrap();
}
}
+1
View File
@@ -9,6 +9,7 @@ pub mod epic;
pub mod fetch_core;
pub mod fetch_tuning;
pub mod gog;
pub mod grow_write;
pub mod md5_small;
pub mod priority;
pub mod steam;
@@ -9,6 +9,7 @@
//! read back and checked before anything is fetched.
use crate::fetch_core::{run_fetch, FetchItem, FetchOptions, FetchSink, SinkError};
use crate::grow_write::{holes_supported, GrowFront};
use crate::steam::cdn;
use crate::steam::content_manifest::{ChunkData, ContentManifest};
use crate::steam::depot_chunk::{process_depot_chunk, steam_adler_hash};
@@ -110,6 +111,7 @@ struct FileSlot {
size: u64,
path: PathBuf,
mode: u32,
front: GrowFront,
}
struct DepotFiles {
@@ -155,17 +157,23 @@ impl DepotFiles {
}
}
fn write(&self, file_idx: usize, offset: u64, data: &[u8]) -> Result<(), String> {
fn write(
&self,
file_idx: usize,
offset: u64,
data: &[u8],
cancel: &AtomicBool,
) -> Result<(), String> {
let file = self.acquire(file_idx)?;
pwrite_all_at(&file, offset, data).map_err(|err| {
let slot = &self.slots[file_idx];
slot.front.write_all_at(&file, offset, data, cancel).map_err(|err| {
format!(
"write '{}' at {offset}: {err}",
self.slots[file_idx].path.display()
)
})?;
let slot = &self.slots[file_idx];
if slot.remaining.fetch_sub(1, Ordering::AcqRel) == 1 {
finalize(&file, slot)?;
finalize(&file, slot, cancel)?;
drop(file);
self.release(file_idx);
} else if self.open_count.load(Ordering::Relaxed) > MAX_OPEN_FILES {
@@ -176,7 +184,7 @@ impl DepotFiles {
}
/// Files with nothing left to fetch (zero chunks, or every chunk already correct on disk).
fn finalize_untouched(&self, idx: usize) -> Result<(), String> {
fn finalize_untouched(&self, idx: usize, cancel: &AtomicBool) -> Result<(), String> {
let slot = &self.slots[idx];
make_parent_dirs(&self.root, &slot.path)?;
check_file_target(&self.root, &slot.path)?;
@@ -188,6 +196,11 @@ impl DepotFiles {
.map_err(|err| format!("open '{}': {err}", slot.path.display()))?;
set_file_mode(&file, &slot.path, slot.mode)?;
let current = file.metadata().map(|m| m.len()).unwrap_or(u64::MAX);
if current < slot.size {
slot.front
.extend_to(&file, slot.size, cancel)
.map_err(|err| format!("extend '{}': {err}", slot.path.display()))?;
}
if current != slot.size {
file.set_len(slot.size)
.map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?;
@@ -196,7 +209,10 @@ impl DepotFiles {
}
}
fn finalize(file: &File, slot: &FileSlot) -> Result<(), String> {
fn finalize(file: &File, slot: &FileSlot, cancel: &AtomicBool) -> Result<(), String> {
slot.front
.extend_to(file, slot.size, cancel)
.map_err(|err| format!("extend '{}': {err}", slot.path.display()))?;
file.set_len(slot.size)
.map_err(|err| format!("set_len '{}': {err}", slot.path.display()))?;
file.sync_all()
@@ -207,6 +223,7 @@ struct ChunkSink<'a> {
chunks: &'a [UniqueChunk],
files: &'a DepotFiles,
depot_key: &'a [u8],
cancel: &'a AtomicBool,
}
impl FetchSink for ChunkSink<'_> {
@@ -225,7 +242,12 @@ impl FetchSink for ChunkSink<'_> {
let mut credited = 0u64;
for target in &chunk.targets {
self.files
.write(target.file_idx as usize, target.offset, &processed.data)
.write(
target.file_idx as usize,
target.offset,
&processed.data,
self.cancel,
)
.map_err(SinkError::Fatal)?;
credited += processed.data.len() as u64;
}
@@ -276,6 +298,7 @@ fn prepare(
}
};
let holes = holes_supported(&root);
let mut slots = Vec::with_capacity(manifest.files.len());
let mut existing = Vec::with_capacity(manifest.files.len());
for file in &manifest.files {
@@ -297,6 +320,7 @@ fn prepare(
} else {
0o644
},
front: GrowFront::new(holes),
});
}
@@ -354,7 +378,10 @@ fn prepare(
continue;
}
let mut remaining = 0usize;
for (chunk_idx, chunk) in file.chunks.iter().enumerate() {
let mut by_offset: Vec<usize> = (0..file.chunks.len()).collect();
by_offset.sort_by_key(|&idx| file.chunks[idx].offset);
for chunk_idx in by_offset {
let chunk = &file.chunks[chunk_idx];
if verified[file_idx].get(chunk_idx).copied().unwrap_or(false) {
bytes_verified += chunk.cb_original as u64;
continue;
@@ -393,7 +420,7 @@ fn prepare(
if is_regular(file.flags, &file.linktarget)
&& files.slots[idx].remaining.load(Ordering::Relaxed) == 0
{
if let Err(err) = files.finalize_untouched(idx) {
if let Err(err) = files.finalize_untouched(idx, cancel) {
return Err(DepotWriteOutcome::fail(err));
}
}
@@ -449,6 +476,7 @@ pub fn write_depot(
chunks: &chunks,
files: &files,
depot_key: request.depot_key,
cancel,
};
let depot_id = manifest.metadata.depot_id;
let done_before = AtomicU64::new(bytes_verified);
@@ -676,12 +704,6 @@ fn set_file_mode(_file: &File, _path: &Path, _mode: u32) -> Result<(), String> {
Ok(())
}
#[cfg(unix)]
fn pwrite_all_at(file: &File, offset: u64, data: &[u8]) -> std::io::Result<()> {
use std::os::unix::fs::FileExt;
file.write_all_at(data, offset)
}
#[cfg(unix)]
fn pread_exact_at(file: &File, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
use std::os::unix::fs::FileExt;
@@ -766,6 +788,7 @@ mod tests {
size: 10,
path: path.clone(),
mode: 0o644,
front: GrowFront::new(true),
}];
let root = fs::canonicalize(&dir).unwrap();
let flags = verify_existing(&manifest, &slots, &[10], &root, 2, &AtomicBool::new(false));
@@ -808,6 +831,44 @@ mod tests {
}
}
#[test]
fn queues_each_files_chunks_in_offset_order() {
let dir = std::env::temp_dir().join(format!(
"droiddeck_steam_order_{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let key = [5u8; 32];
let manifest = ContentManifest {
files: vec![FileMapping {
filename: "big.pak".into(),
size: 15,
chunks: vec![chunk(b"three", 10), chunk(b"first", 0), chunk(b"other", 5)],
..Default::default()
}],
..Default::default()
};
let request = DepotWriteRequest {
manifest: &manifest,
depot_key: &key,
servers: &[],
target_dir: &dir,
ca_bundle_path: "",
max_workers: 1,
process_workers: 1,
};
let prepared = prepare(&request, &AtomicBool::new(false)).unwrap();
let offsets: Vec<u64> = prepared
.chunks
.iter()
.map(|c| c.targets[0].offset)
.collect();
assert_eq!(offsets, vec![0, 5, 10]);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn writes_in_place_dedupes_chunks_and_resumes_from_disk() {
let dir = std::env::temp_dir().join(format!(
@@ -867,6 +928,7 @@ mod tests {
chunks: &prepared.chunks,
files: &prepared.files,
depot_key: &key,
cancel: &cancel,
};
let item = |id: u64| FetchItem {
id,
@@ -886,6 +948,7 @@ mod tests {
chunks: &wrong,
files: &prepared.files,
depot_key: &key,
cancel: &cancel,
};
assert!(matches!(
wrong_sink.process(&item(0), encrypted_chunk(&key, b"HELLO")),
@@ -188,6 +188,34 @@ class DownloadQueueRemovalTest {
assertFalse(folder.exists())
}
@Test fun uninstallStopsARunningDownloadThenRemovesTheGame() {
val running = CountDownLatch(1)
val cancels = AtomicInteger()
val entry = DownloadEntry(Store.GOG, "uninstall-while-running", "Running")
DownloadQueue.enqueue(app, entry) {
object : DownloadQueue.DownloadJob {
override fun run(handle: DownloadQueue.JobHandle): String? {
running.countDown()
val until = System.nanoTime() + TimeUnit.SECONDS.toNanos(10)
while (!handle.isCancelled && System.nanoTime() < until) Thread.sleep(10)
return null
}
override fun cancel(deleteFiles: Boolean) { cancels.incrementAndGet() }
}
}
assertTrue(running.await(5, TimeUnit.SECONDS))
val folder = File(app.filesDir, "uninstall-while-running").apply { mkdirs() }
File(folder, "game.bin").writeText("x")
val game = InstalledStoreGame(StoreGameSidecar(Store.GOG, "uninstall-while-running", "Running", exe = "game.bin"), folder)
assertEquals(entry.key, game.key)
val done = CountDownLatch(1)
StoresState.uninstall(app, game) { done.countDown() }
assertTrue(idleUntil { done.count == 0L })
assertEquals(1, cancels.get())
assertTrue(DownloadQueue.entry(entry.key)?.state.let { it == null || it == DownloadState.CANCELLED })
assertFalse(folder.exists())
}
private fun blockDiscards(): CountDownLatch {
val release = CountDownLatch(1)
StoreInstalls.beforeDiscard = { release.await(5, TimeUnit.SECONDS) }