Keep SD card downloads cancellable and let uninstall stop them (#3313)

This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-27 05:26:48 -05:00
1 parent 8e25301a77
commit 281a64f6c5
13 files changed
+615 -61

No files matched your search

@@ -122,10 +122,16 @@ object StoreInstalls {
fun discard(context: Context, folder: File, caches: List<File>) {
val app = context.applicationContext
inBackground(folder) { discardNow(app, folder, caches) }
}
fun deleteLater(dir: File) = inBackground(dir) { deleteTree(dir) }
private fun inBackground(folder: File, work: () -> Unit) {
beginDiscard(folder)
val worker = Thread({
try {
discardNow(app, folder, caches)
work()
} finally {
endDiscard(folder)
}
@@ -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 -> {
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import com.droiddeck.launcher.stores.formatBytes
@@ -215,7 +216,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
val before = EpicClient.read(app)
val needApp = !(before.version == launcher.version && File(state, "app/${launcher.version}/.droiddeck-ready").isFile)
val needRuntime = !(before.runtimeVersion == runtime.version && File(state, "runtime/${runtime.version}/.droiddeck-ready").isFile)
val dir = EpicClient.downloadsDir(app).apply { mkdirs() }
val dir = EpicClient.downloadsDir(app).also { StoreInstalls.awaitDiscard(it) }.apply { mkdirs() }
val gles = EpicClientSources.gles()
val appPart = if (needApp) Part(listOf(launcher.url), File(dir, "${launcher.version}-${EpicClientSources.LAUNCHER_FILE}"), null, true) else null
val desktopParts = if (needApp) EpicClientSources.DESKTOP.map { Part(it.urls, File(dir, it.file), it.sha256, false, it.size) } else emptyList()
@@ -265,7 +266,7 @@ internal class EpicClientInstaller(private val app: Context) : DownloadQueue.Dow
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
runCatching { connection?.disconnect() }
if (deleteFiles) EpicClient.downloadsDir(app).deleteRecursively()
if (deleteFiles) StoreInstalls.deleteLater(EpicClient.downloadsDir(app))
}
private fun length(url: String): Long {
@@ -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
@@ -137,7 +137,7 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
delete = deleteFiles
val process = child
if (process == null) {
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteTree(folder)
if (deleteFiles && !item.extra["baseId"].isNullOrBlank()) StoreInstalls.deleteLater(folder)
else if (deleteFiles) StoreInstalls.discard(app, folder, emptyList())
return
}
+17 -7
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, is_cancel, 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,9 +484,16 @@ 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)
.map_err(|e| SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path))))?;
split
.front
.write_all_at(handle, start + offset, data, self.stop)
.map_err(|e| {
if is_cancel(&e) {
SinkError::Retry(format!("{}: cancelled", job.path))
} else {
SinkError::Fatal(self.fail(format!("Could not write {}: {e}", job.path)))
}
})?;
drop(file);
split.received[part].fetch_add(data.len() as u64, Ordering::Relaxed);
self.in_flight.fetch_add(data.len() as u64, Ordering::Relaxed);
@@ -698,6 +706,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 +720,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),
}
})
})
@@ -797,13 +807,13 @@ pub fn run(req: &Request, cancel: &AtomicBool, ev: &dyn Events) -> Result<Finish
return Err(Stop::Failed(message));
}
if !placed_all {
if cancel.load(Ordering::SeqCst) {
return Err(Stop::Cancelled);
}
if let Some(error) = outcome.as_ref().and_then(|o| o.error.clone()) {
ev.log(&format!("download failed: {error}"));
return Err(Stop::Failed("A file failed to download".into()));
}
if cancel.load(Ordering::SeqCst) {
return Err(Stop::Cancelled);
}
return Err(Stop::Failed("The download ended before every file was written".into()));
}
@@ -21,7 +21,14 @@ fn rejects_third_party_managed_install_before_manifest_parsing() {
}
}
fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>) -> String {
#[derive(Default)]
struct Misses {
seen: AtomicUsize,
cancel_at: usize,
cancel: Arc<AtomicBool>,
}
fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>, misses: Arc<Misses>) -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let files = Arc::new(files);
@@ -30,13 +37,14 @@ fn serve(files: HashMap<String, Vec<u8>>, hits: Arc<AtomicUsize>) -> String {
let Ok(stream) = stream else { continue };
let files = Arc::clone(&files);
let hits = Arc::clone(&hits);
std::thread::spawn(move || answer(stream, &files, &hits));
let misses = Arc::clone(&misses);
std::thread::spawn(move || answer(stream, &files, &hits, &misses));
}
});
format!("http://{addr}")
}
fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &AtomicUsize) {
fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &AtomicUsize, misses: &Misses) {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut first = String::new();
if reader.read_line(&mut first).is_err() {
@@ -54,7 +62,13 @@ fn answer(mut stream: TcpStream, files: &HashMap<String, Vec<u8>>, hits: &Atomic
hits.fetch_add(1, Ordering::Relaxed);
let (status, body) = match files.get(&path) {
Some(b) => ("200 OK", b.clone()),
None => ("404 Not Found", Vec::new()),
None => {
if misses.seen.fetch_add(1, Ordering::SeqCst) + 1 == misses.cancel_at {
std::thread::sleep(std::time::Duration::from_millis(300));
misses.cancel.store(true, Ordering::SeqCst);
}
("404 Not Found", Vec::new())
}
};
let head = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
let _ = stream.write_all(head.as_bytes());
@@ -106,6 +120,10 @@ fn pattern(seed: u8, len: usize) -> Vec<u8> {
}
fn fixture() -> Fixture {
fixture_missing(false, Arc::new(Misses::default()))
}
fn fixture_missing(last_chunk: bool, misses: Arc<Misses>) -> Fixture {
let mut c1 = chunk(1, 4096);
let mut c2 = chunk(2, 2048);
let mut c3 = chunk(3, 1000);
@@ -168,10 +186,13 @@ fn fixture() -> Fixture {
let mut served = HashMap::new();
served.insert("/Builds/x/test.manifest".to_string(), manifest_bytes);
for (info, data) in [(&c1, &d1), (&c2, &d2), (&c3, &d3)] {
if last_chunk && info.guid == c3.guid {
continue;
}
served.insert(format!("/Builds/x/{}", parsed.chunk_path(info)), encode(data, true));
}
let hits = Arc::new(AtomicUsize::new(0));
let base = serve(served, Arc::clone(&hits));
let base = serve(served, Arc::clone(&hits), misses);
Fixture {
base,
hits,
@@ -273,6 +294,40 @@ fn a_cancelled_run_reports_cancel() {
let _ = fs::remove_dir_all(&game);
}
fn kept_c(fx: &Fixture, game: &Path) -> bool {
let c = &fx.expected[1].1;
let partial = game.join(staging::DIR_NAME).join(staging::partial_name("b/c.bin", c.len() as u64, Some(Sha1::digest(c).into())));
partial.is_file() && staging::list_path(&partial).is_file()
}
#[test]
fn a_chunk_that_cannot_be_fetched_fails_and_keeps_written_parts() {
let misses = Arc::new(Misses::default());
let fx = fixture_missing(true, Arc::clone(&misses));
let game = temp_game("fetch-fail");
let cancel = AtomicBool::new(false);
let err = run(&request(&fx, &game), &cancel, &Recorder::default()).unwrap_err();
assert!(matches!(&err, Stop::Failed(m) if m.starts_with("Download failed: ")), "{err:?}");
assert_eq!(misses.seen.load(Ordering::SeqCst), crate::fetch_core::MAX_ITEM_ATTEMPTS as usize);
assert!(kept_c(&fx, &game));
let _ = fs::remove_dir_all(&game);
}
#[test]
fn a_cancel_during_the_last_fetch_attempt_reports_cancel_and_keeps_written_parts() {
let cancel = Arc::new(AtomicBool::new(false));
let last = crate::fetch_core::MAX_ITEM_ATTEMPTS as usize;
let misses = Arc::new(Misses { seen: AtomicUsize::new(0), cancel_at: last, cancel: Arc::clone(&cancel) });
let fx = fixture_missing(true, Arc::clone(&misses));
let game = temp_game("fetch-cancel");
let events = Recorder::default();
assert_eq!(run(&request(&fx, &game), &cancel, &events).unwrap_err(), Stop::Cancelled);
assert_eq!(misses.seen.load(Ordering::SeqCst), last);
assert!(events.logs.lock().unwrap().iter().any(|l| l.contains(&format!("failed after {last} attempts"))));
assert!(kept_c(&fx, &game));
let _ = fs::remove_dir_all(&game);
}
fn place_partial(fx: &Fixture, game: &Path, data: &[u8], list: &str) -> PathBuf {
let stage = staging::recover(game).unwrap();
let a = &fx.expected[0].1;
@@ -8,6 +8,7 @@ use std::time::{Duration, Instant};
use sha1::{Digest, Sha1};
use super::cache;
use crate::grow_write::{holes_supported, is_cancel, 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,
@@ -95,6 +97,17 @@ struct Engine<'a> {
total_bytes: u64,
}
enum Halt {
Cancelled,
Failed(String),
}
impl From<String> for Halt {
fn from(message: String) -> Self {
Halt::Failed(message)
}
}
enum Source<'d> {
Memory(&'d [u8]),
Cache(PathBuf),
@@ -112,6 +125,13 @@ impl<'a> Engine<'a> {
message
}
fn sink_error(&self, halt: Halt) -> SinkError {
match halt {
Halt::Cancelled => SinkError::Retry("cancelled".into()),
Halt::Failed(message) => SinkError::Fatal(self.fail(message)),
}
}
fn cache_path(&self, producer: usize) -> PathBuf {
let p = &self.input.schedule.producers[producer];
let info = &self.input.manifest.chunks[p.chunk as usize];
@@ -158,7 +178,7 @@ impl<'a> Engine<'a> {
self.input.schedule.producers[fetch[at] as usize].anchor as usize + 1
}
fn write_use(&self, u: usize, source: &Source<'_>) -> Result<(), String> {
fn write_use(&self, u: usize, source: &Source<'_>) -> Result<(), Halt> {
let schedule = &self.input.schedule;
let f = schedule.use_file[u] as usize;
let j = u - schedule.file_start[f] as usize;
@@ -175,16 +195,22 @@ impl<'a> Engine<'a> {
let start = part.chunk_offset as usize;
let end = start + part.size as usize;
if end > data.len() {
return Err(format!("A chunk is too short for {}", file.path));
return Err(format!("A chunk is too short for {}", file.path).into());
}
let piece = &data[start..end];
let handle = self.slots[f].lock().expect("slot lock").file.clone();
let Some(handle) = handle else {
return Err(format!("internal: {} is not open", file.path));
return Err(format!("internal: {} is not open", file.path).into());
};
handle
.write_all_at(piece, part.file_offset)
.map_err(|e| format!("Could not assemble or atomically replace {}: {e}", file.path))?;
self.fronts[f]
.write_all_at(&handle, part.file_offset, piece, self.stop)
.map_err(|e| {
if is_cancel(&e) {
Halt::Cancelled
} else {
Halt::Failed(format!("Could not assemble or atomically replace {}: {e}", file.path))
}
})?;
self.written.fetch_add(piece.len() as u64, Ordering::Relaxed);
let complete = {
@@ -343,14 +369,18 @@ impl<'a> Engine<'a> {
}
};
let Some(f) = candidate else { continue };
if let Err(e) = self.admit(f) {
self.fail(e);
return;
match self.admit(f) {
Ok(()) => {}
Err(Halt::Cancelled) => return,
Err(Halt::Failed(e)) => {
self.fail(e);
return;
}
}
}
}
fn admit(&self, f: usize) -> Result<(), String> {
fn admit(&self, f: usize) -> Result<(), Halt> {
self.open_stage(f)?;
let schedule = &self.input.schedule;
let file = &self.input.files[f];
@@ -415,7 +445,7 @@ impl<'a> Engine<'a> {
out
};
for u in claims {
self.write_use(u, &Source::Memory(&data)).map_err(|e| SinkError::Fatal(self.fail(e)))?;
self.write_use(u, &Source::Memory(&data)).map_err(|h| self.sink_error(h))?;
}
Ok(0)
}
@@ -446,8 +476,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()
@@ -532,7 +564,7 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
}
ready
};
let outcome = std::thread::scope(|scope| {
let (outcome, cancelled) = std::thread::scope(|scope| {
let admitter = std::thread::Builder::new()
.name("epic-admit".into())
.spawn_scoped(scope, || {
@@ -541,7 +573,7 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
});
if let Err(e) = admitter {
engine.fail(format!("could not start the install thread: {e}"));
return None;
return (None, false);
}
let outcome = if items.is_empty() {
None
@@ -552,11 +584,9 @@ pub fn run(input: &EngineInput<'_>, stop: &AtomicBool, events: &dyn Events) -> R
let mut c = engine.coord.lock().expect("coord lock");
c.fetch_done = true;
}
if outcome.as_ref().is_some_and(|o| !o.ok()) {
stop.store(true, Ordering::SeqCst);
}
let cancelled = settle(outcome.as_ref().is_some_and(|o| !o.ok()), stop);
engine.wake.notify_all();
outcome
(outcome, cancelled)
});
let failure = engine.failure.lock().expect("failure lock").take().filter(|m| !m.is_empty());
@@ -593,16 +623,35 @@ fetches={} refetches={} peak_cache_mib={} hosts={}",
hosts.join(","),
));
ending(failure, complete, fetch_error, cancelled, stop.load(Ordering::SeqCst))?;
Ok(Stats { bytes_written: written, files_written: input.files.len() })
}
fn settle(fetch_failed: bool, stop: &AtomicBool) -> bool {
let cancelled = stop.load(Ordering::SeqCst);
if fetch_failed {
stop.store(true, Ordering::SeqCst);
}
cancelled
}
fn ending(
failure: Option<String>,
complete: bool,
fetch_error: Option<String>,
cancelled: bool,
stopped: bool,
) -> Result<(), Stop> {
if let Some(message) = failure {
return Err(Stop::Failed(message));
}
if complete {
return Ok(Stats { bytes_written: written, files_written: input.files.len() });
return Ok(());
}
if let Some(message) = fetch_error {
if let Some(message) = fetch_error.filter(|_| !cancelled) {
return Err(Stop::Failed(format!("Download failed: {}", tidy_fetch_error(&message))));
}
if stop.load(Ordering::SeqCst) {
if stopped {
return Err(Stop::Cancelled);
}
Err(Stop::Failed("The download ended before every file was written".into()))
@@ -704,4 +753,37 @@ mod tests {
assert_eq!(fs::read_to_string(staging::list_path(&kept)).unwrap(), "10\n20\n");
let _ = fs::remove_dir_all(&dir);
}
fn end(fetch_error: Option<&str>, stop: &AtomicBool) -> Result<(), Stop> {
let cancelled = settle(fetch_error.is_some(), stop);
ending(None, false, fetch_error.map(str::to_string), cancelled, stop.load(Ordering::SeqCst))
}
#[test]
fn a_cancel_during_the_last_fetch_attempt_ends_as_cancelled() {
let stop = AtomicBool::new(true);
assert!(matches!(end(Some("timed out"), &stop), Err(Stop::Cancelled)));
assert!(matches!(end(None, &stop), Err(Stop::Cancelled)));
}
#[test]
fn a_fetch_failure_without_a_cancel_ends_as_failed() {
let stop = AtomicBool::new(false);
match end(Some("timed out"), &stop) {
Err(Stop::Failed(message)) => assert!(message.starts_with("Download failed: ")),
_ => panic!("a fetch failure must be reported"),
}
assert!(stop.load(Ordering::SeqCst));
let idle = AtomicBool::new(false);
assert!(matches!(end(None, &idle), Err(Stop::Failed(_))));
}
#[test]
fn a_write_failure_or_a_finished_install_wins_over_a_cancel() {
assert!(matches!(
ending(Some("disk full".into()), false, None, true, true),
Err(Stop::Failed(message)) if message == "disk full"
));
assert!(ending(None, true, Some("late".into()), true, true).is_ok());
}
}
+293
View File
@@ -0,0 +1,293 @@
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 is_cancel(err: &io::Error) -> bool {
err.kind() == io::ErrorKind::Interrupted
}
pub fn holes_supported(dir: &Path) -> bool {
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 other = dir.join(format!("{PROBE_PREFIX}game-file"));
fs::write(&other, b"kept").unwrap();
let _ = holes_supported(&dir);
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
assert_eq!(fs::read(&other).unwrap(), b"kept");
fs::remove_file(&other).unwrap();
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,13 @@ 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) {
if cancel.load(Ordering::Relaxed) {
return Err(DepotWriteOutcome {
cancelled: true,
..Default::default()
});
}
return Err(DepotWriteOutcome::fail(err));
}
}
@@ -449,6 +482,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 +710,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 +794,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 +837,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 +934,7 @@ mod tests {
chunks: &prepared.chunks,
files: &prepared.files,
depot_key: &key,
cancel: &cancel,
};
let item = |id: u64| FetchItem {
id,
@@ -886,6 +954,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) }