diff --git a/controller/app/build.gradle b/controller/app/build.gradle index f11bdec9c..16e02dcba 100644 --- a/controller/app/build.gradle +++ b/controller/app/build.gradle @@ -492,32 +492,39 @@ task refreshRootfsSizes { def tiers = ['basic', 'standard', 'full'] def abis = ['arm64-v8a', 'armeabi-v7a'] def sizePat = ~/(\d+)<\/size>/ + // ADFA-5105: capture BOTH the compressed download size (.meta4 ) and the + // uncompressed installed size (.installed sidecar, ADFA-5110). The installed value is + // what the destructive free-space guard needs; keep both columns in sync per build. + def fetch = { String url -> + def conn = (HttpURLConnection) new URL(url).openConnection() + conn.setRequestProperty('User-Agent', 'iiab-android-build') + conn.connectTimeout = 6000 + conn.readTimeout = 6000 + if (conn.responseCode != 200) { conn.disconnect(); return null } + def body = conn.inputStream.getText('UTF-8') + conn.disconnect() + return body + } def fetched = [:] + def fetchedInst = [:] for (t in tiers) { for (a in abis) { - def url = "${base}latest_${t}_${a}.meta4" try { - def conn = (HttpURLConnection) new URL(url).openConnection() - conn.setRequestProperty('User-Agent', 'iiab-android-build') - conn.connectTimeout = 6000 - conn.readTimeout = 6000 - if (conn.responseCode != 200) { - logger.warn(">> [rootfs sizes] HTTP ${conn.responseCode} for ${url}") - conn.disconnect(); continue - } - def body = conn.inputStream.getText('UTF-8') - conn.disconnect() - def m = sizePat.matcher(body) - if (m.find()) { fetched["${t}|${a}".toString()] = m.group(1) } - else { logger.warn(">> [rootfs sizes] no element in ${url}") } + def meta = fetch("${base}latest_${t}_${a}.meta4") + def m = meta != null ? sizePat.matcher(meta) : null + if (m != null && m.find()) { fetched["${t}|${a}".toString()] = m.group(1) } + else { logger.warn(">> [rootfs sizes] no compressed size for ${t}/${a}") } + def inst = fetch("${base}latest_${t}_${a}.installed") + if (inst != null && inst.trim() ==~ /\d+/) { fetchedInst["${t}|${a}".toString()] = inst.trim() } + else { logger.warn(">> [rootfs sizes] no installed size for ${t}/${a}") } } catch (Exception e) { - logger.warn(">> [rootfs sizes] fetch failed for ${url}: ${e.message}") + logger.warn(">> [rootfs sizes] fetch failed for ${t}/${a}: ${e.message}") } } } def expected = tiers.size() * abis.size() - if (fetched.size() != expected) { - logger.warn(">> [rootfs sizes] incomplete fetch (${fetched.size()}/${expected}); keeping existing ${csv.name} (last known).") + if (fetched.size() != expected || fetchedInst.size() != expected) { + logger.warn(">> [rootfs sizes] incomplete fetch (compressed ${fetched.size()}/${expected}, installed ${fetchedInst.size()}/${expected}); keeping existing ${csv.name} (last known).") return } def existing = [:] @@ -526,18 +533,23 @@ task refreshRootfsSizes { line = line.trim() if (line.isEmpty() || line.startsWith('#')) return def p = line.split(',') - if (p.length >= 3) existing["${p[0].trim()}|${p[1].trim()}".toString()] = p[2].trim() + if (p.length >= 5) existing["${p[0].trim()}|${p[1].trim()}".toString()] = "${p[2].trim()}|${p[4].trim()}".toString() } } - if (existing == fetched) { - println ">> [rootfs sizes] up to date (${fetched.size()} entries unchanged)." + def current = [:] + for (t in tiers) for (a in abis) current["${t}|${a}".toString()] = "${fetched[("${t}|${a}").toString()]}|${fetchedInst[("${t}|${a}").toString()]}".toString() + if (existing == current) { + println ">> [rootfs sizes] up to date (${current.size()} entries unchanged)." return } def today = new Date().format('yyyy-MM-dd') def rows = [] - for (t in tiers) for (a in abis) rows << "${t},${a},${fetched[("${t}|${a}").toString()]},${today}".toString() + for (t in tiers) for (a in abis) { + def k = "${t}|${a}".toString() + rows << "${t},${a},${fetched[k]},${today},${fetchedInst[k]}".toString() + } if (!csv.parentFile.exists()) csv.parentFile.mkdirs() - csv.text = '# tier,abi,bytes,fetched_date -- AUTO-GENERATED by the refreshRootfsSizes Gradle task; do not edit by hand\n' + rows.join('\n') + '\n' + csv.text = '# tier,abi,bytes,fetched_date,installed_bytes -- AUTO-GENERATED by the refreshRootfsSizes Gradle task; do not edit by hand\n' + rows.join('\n') + '\n' println ">> [rootfs sizes] updated ${rows.size()} entries in ${csv.name} (${today})." } } diff --git a/controller/app/src/main/assets/rootfs_sizes.csv b/controller/app/src/main/assets/rootfs_sizes.csv index cd858022b..6b738d14c 100644 --- a/controller/app/src/main/assets/rootfs_sizes.csv +++ b/controller/app/src/main/assets/rootfs_sizes.csv @@ -1,7 +1,7 @@ -# tier,abi,bytes,fetched_date -- AUTO-GENERATED by the refreshRootfsSizes Gradle task; do not edit by hand -basic,arm64-v8a,1931026680,2026-08-03 -basic,armeabi-v7a,1933300053,2026-08-03 -standard,arm64-v8a,2140334409,2026-08-03 -standard,armeabi-v7a,2142535092,2026-08-03 -full,arm64-v8a,2834585013,2026-08-03 -full,armeabi-v7a,2827035164,2026-08-03 +# tier,abi,bytes,fetched_date,installed_bytes -- AUTO-GENERATED by the refreshRootfsSizes Gradle task; do not edit by hand +basic,arm64-v8a,1936814083,2026-08-12,3294993334 +basic,armeabi-v7a,1937574673,2026-08-12,3162669853 +standard,arm64-v8a,2146100011,2026-08-12,3675639489 +standard,armeabi-v7a,2146813777,2026-08-12,3542808901 +full,arm64-v8a,2841912764,2026-08-12,5103603118 +full,armeabi-v7a,2833106837,2026-08-12,4856267277 diff --git a/controller/app/src/main/java/org/iiab/controller/deepop/DeepOpService.java b/controller/app/src/main/java/org/iiab/controller/deepop/DeepOpService.java index 6c4c62ee2..e49cc671a 100644 --- a/controller/app/src/main/java/org/iiab/controller/deepop/DeepOpService.java +++ b/controller/app/src/main/java/org/iiab/controller/deepop/DeepOpService.java @@ -150,6 +150,20 @@ private void runBackup(final String uriStr) { // ---- RESTORE (destructive) ---- private void runRestore(final String path) { if (done) return; + // ADFA-5105: the restore overwrites the rootfs with the backup's contents. Refuse before + // anything is touched when the uncompressed backup plainly won't fit (fail-safe on UNKNOWN + // free space too). The "needed" is estimated from the backup archive already on disk. + long needed = org.iiab.controller.storage.SpaceEstimate.fromCompressed(new File(path).length()); + org.iiab.controller.storage.FreeSpacePreflight.Result pf = + org.iiab.controller.storage.FreeSpacePreflight.check(this, needed); + if (!pf.ok) { + File tmp = new File(path); + if (tmp.exists()) tmp.delete(); + finishJob(false, getString(R.string.k2go_br_restore_done), + getString(R.string.install_error_no_storage) + " (" + + org.iiab.controller.util.ByteFormatter.toHuman(pf.amountToReport()) + ")"); + return; + } // ADFA-5070: stop the downloads before the tar starts overwriting the rootfs // they were writing into. The pending orders are not touched yet — a tar that // will not open leaves the system intact, and discarding them here would have diff --git a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java index bec8c4695..15d8f326f 100644 --- a/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java +++ b/controller/app/src/main/java/org/iiab/controller/install/presentation/InstallService.java @@ -260,6 +260,10 @@ private void runPipeline() { else finishSuccess(); return; } + // ADFA-5105: from here on the pipeline extracts a rootfs (and, on reinstall, wipes the + // existing one first). Refuse before any destructive step when it plainly won't fit — + // UNKNOWN free space refuses too (a wipe that then runs out of disk leaves no bootable OS). + if (!ensureSpaceForRootfs()) return; if (reinstall && debianRootfs.exists() && debianRootfs.isDirectory()) { // ADFA-5023: a reinstall wipes the LIVE rootfs. Doing rm -rf while the server proot is up // is the corruption the legacy reset/delete guarded against (they refused when alive). If a @@ -402,6 +406,10 @@ public void onComplete(String destDir) { @Override public void onError(String error) { + // ADFA-5105: don't leave the compressed .tar.gz behind on a failed extract — + // on success it's deleted below, but a failure used to keep it, silently + // holding ~2–3 GB until the next attempt. + downloadedArchive.delete(); org.iiab.controller.analytics.AnalyticsClient.with(InstallService.this).logInstallFailed("extract", "extract_error"); fail(getString(R.string.install_error_extraction, error)); } @@ -581,6 +589,9 @@ private void editLocalVarsForMaps(File debianRootfs, InstallationPlanner.Tier ti */ private void runResetPipeline() { try { + // ADFA-5105: reset wipes the rootfs and re-extracts a base one. Refuse before the wipe + // when it won't fit (fail-safe on UNKNOWN free space too). + if (!ensureSpaceForRootfs()) return; // ADFA-5070: stop and forget the downloads before the rootfs they were // writing into goes away. org.iiab.controller.system.data.ContentStateInvalidator.replacementStarting(this, @@ -912,6 +923,30 @@ private void fail(String message) { teardown(); } + /** + * ADFA-5105: destructive-run free-space preflight. This gate runs BEFORE the download, and the + * pipeline then writes the compressed .tar.gz and the uncompressed tree, which coexist during + * extraction — so the "needed" is the PEAK (compressed + uncompressed) for this tier+abi, from + * RootfsCatalog (measured via ADFA-5110 when published, estimate otherwise). Returns true to + * proceed; on a refusal it reports the shortfall through fail() and returns false so the caller + * stops before wiping. + */ + private boolean ensureSpaceForRootfs() { + if (cancelled) return false; + org.iiab.controller.rootfs.data.RootfsCatalog cat = + new org.iiab.controller.rootfs.data.RootfsCatalog(this); + org.iiab.controller.rootfs.domain.RootfsTier rTier = + (tier == null) ? org.iiab.controller.rootfs.domain.RootfsTier.BASIC + : org.iiab.controller.rootfs.domain.RootfsTier.valueOf(tier.name()); + long needed = cat.peakInstallBytes(rTier, cat.detectAbi()); + org.iiab.controller.storage.FreeSpacePreflight.Result pf = + org.iiab.controller.storage.FreeSpacePreflight.check(this, needed); + if (pf.ok) return true; + fail(getString(R.string.install_error_no_storage) + " (" + + org.iiab.controller.util.ByteFormatter.toHuman(pf.amountToReport()) + ")"); + return false; + } + private void doCancel() { if (finished) return; cancelled = true; diff --git a/controller/app/src/main/java/org/iiab/controller/install/presentation/PlannerController.java b/controller/app/src/main/java/org/iiab/controller/install/presentation/PlannerController.java index 82b501d2a..0a7311e0b 100644 --- a/controller/app/src/main/java/org/iiab/controller/install/presentation/PlannerController.java +++ b/controller/app/src/main/java/org/iiab/controller/install/presentation/PlannerController.java @@ -294,6 +294,16 @@ private void recalculateProjection() { } } + /** ADFA-5105: the wizard tier -> the rootfs slice's tier enum (same names, null -> BASIC). */ + private static org.iiab.controller.rootfs.domain.RootfsTier mapRootfsTier(org.iiab.controller.InstallationPlanner.Tier t) { + if (t == null) return org.iiab.controller.rootfs.domain.RootfsTier.BASIC; + switch (t) { + case FULL: return org.iiab.controller.rootfs.domain.RootfsTier.FULL; + case STANDARD: return org.iiab.controller.rootfs.domain.RootfsTier.STANDARD; + default: return org.iiab.controller.rootfs.domain.RootfsTier.BASIC; + } + } + private void onRootfsSizeResolved(RootfsUiState rootfsState) { if (!fragment.isAdded() || rootfsState == null) return; if (rootfsState.status == RootfsUiState.Status.LOADING) return; @@ -322,17 +332,36 @@ public void onCalculated(InstallationPlanner.StorageProjection projection) { double totalSpaceGb = path.getTotalSpace() / (1024.0 * 1024.0 * 1024.0); double usedSpaceGb = totalSpaceGb - freeSpaceGb; - double pOs = (host.getSelectedTier() == null) ? 0.0 : projection.osSize; - double pMaps = (host.getSelectedTier() == null) ? 0.0 : projection.mapsSize; + final double GB = 1024.0 * 1024.0 * 1024.0; + boolean hasTier = host.getSelectedTier() != null; // --- DETECT ARCHITECTURE --- String arch = host.getTermuxArch(); boolean is64Bit = arch != null && arch.contains("64"); + // ADFA-5105: size the OS by its UNCOMPRESSED footprint (what actually lands), the + // same figure the destructive gate uses — not the compressed download — so the + // legend and the "fits" decision agree with the hard preflight in InstallService. + org.iiab.controller.rootfs.data.RootfsCatalog rc = + new org.iiab.controller.rootfs.data.RootfsCatalog(fragment.requireContext()); + org.iiab.controller.rootfs.domain.RootfsAbi rAbi = rc.detectAbi(); + org.iiab.controller.rootfs.domain.RootfsTier rTier = mapRootfsTier(host.getSelectedTier()); + + double pOs = hasTier ? rc.installedBytes(rTier, rAbi) / GB : 0.0; + double pMaps = hasTier ? projection.mapsSize : 0.0; + // --- FORCE KIWIX TO ZERO IN 32-BITS (change if kiwix gets support for 32bits somehow) --- - double pKiwix = (host.getSelectedTier() == null || !is64Bit) ? 0.0 : projection.kiwixSize; + double pKiwix = (!hasTier || !is64Bit) ? 0.0 : projection.kiwixSize; double pTotal = pOs + pMaps + pKiwix; - host.setStorageSafe(pTotal <= (freeSpaceGb - 5.0)); + // Gate on the same PEAK the install needs — the compressed download and the + // uncompressed tree coexist during extraction (RootfsCatalog.peakInstallBytes) — plus + // the content, on the real write target. UNKNOWN free space stays "safe" (advisory); + // the hard preflight in InstallService refuses for real before any wipe. + long neededBytes = (hasTier ? rc.peakInstallBytes(rTier, rAbi) : 0L) + + (long) Math.ceil((pMaps + pKiwix) * GB); + Long freeBytes = org.iiab.controller.storage.StorageProbe.freeBytes(fragment.requireContext()); + host.setStorageSafe(org.iiab.controller.storage.StorageGuard.evaluate(freeBytes, neededBytes) + != org.iiab.controller.storage.StorageGuard.Verdict.DOES_NOT_FIT); if (txtLegendIiab != null) txtLegendIiab.setText(String.format(java.util.Locale.US, "%.1fG", pOs)); diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriBrowseFragment.java b/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriBrowseFragment.java index 5db6a999f..80948e49d 100644 --- a/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriBrowseFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriBrowseFragment.java @@ -13,7 +13,6 @@ import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; -import android.os.StatFs; import android.text.Editable; import android.text.TextWatcher; import android.view.Gravity; @@ -198,9 +197,10 @@ private String langDisplay(String code) { private void readFreeSpace() { try { - StatFs st = new StatFs(requireContext().getFilesDir().getPath()); - freeMb = st.getAvailableBytes() / (1024L * 1024L); - totalMb = st.getTotalBytes() / (1024L * 1024L); + Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); // ADFA-5105: shared probe + Long tb = org.iiab.controller.storage.StorageProbe.totalBytes(requireContext()); + freeMb = (fb == null ? 0L : fb) / (1024L * 1024L); + totalMb = (tb == null ? 0L : tb) / (1024L * 1024L); } catch (Exception e) { freeMb = 0L; totalMb = 0L; diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriConfirmFragment.java b/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriConfirmFragment.java index 46475ef40..433af6ff5 100644 --- a/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriConfirmFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriConfirmFragment.java @@ -11,7 +11,6 @@ import android.content.Context; import android.os.Bundle; -import android.os.StatFs; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; @@ -341,7 +340,7 @@ private long totalCost(List chosen) { /** Free bytes on the data partition, or null when it cannot be read. */ private Long readFreeBytes() { try { - return new StatFs(requireContext().getFilesDir().getPath()).getAvailableBytes(); + return org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); // ADFA-5105: shared probe } catch (Exception e) { return null; } diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriTopicsFragment.java b/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriTopicsFragment.java index d0e4ec744..9bfb28daf 100644 --- a/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriTopicsFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/presentation/KolibriTopicsFragment.java @@ -12,7 +12,6 @@ import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; -import android.os.StatFs; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; @@ -225,9 +224,10 @@ private Channel resolveChannel() { private void readFreeSpace() { try { - StatFs st = new StatFs(requireContext().getFilesDir().getPath()); - freeMb = st.getAvailableBytes() / (1024L * 1024L); - totalMb = st.getTotalBytes() / (1024L * 1024L); + Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); // ADFA-5105: shared probe + Long tb = org.iiab.controller.storage.StorageProbe.totalBytes(requireContext()); + freeMb = (fb == null ? 0L : fb) / (1024L * 1024L); + totalMb = (tb == null ? 0L : tb) / (1024L * 1024L); } catch (Exception e) { freeMb = 0L; totalMb = 0L; diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/MapsChooseFragment.java b/controller/app/src/main/java/org/iiab/controller/redesign/MapsChooseFragment.java index 3ba72b422..54e5af944 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/MapsChooseFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/MapsChooseFragment.java @@ -18,7 +18,6 @@ import android.graphics.Typeface; import android.os.Bundle; -import android.os.StatFs; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; @@ -109,11 +108,9 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c fit = root.findViewById(R.id.k2go_fit); download = root.findViewById(R.id.k2go_download_btn); - try { - freeMb = new StatFs(requireContext().getFilesDir().getPath()).getAvailableBytes() / (1024L * 1024L); - } catch (Exception e) { - freeMb = 0; - } + // ADFA-5105: read free space through the shared probe, not a per-screen StatFs copy. + Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); + freeMb = (fb == null ? 0L : fb) / (1024L * 1024L); resolveSizes(); buildGroups(root.findViewById(R.id.k2go_maps_groups)); diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ZimCategoryFragment.java b/controller/app/src/main/java/org/iiab/controller/redesign/ZimCategoryFragment.java index d1bcb74a2..e148689bf 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ZimCategoryFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ZimCategoryFragment.java @@ -15,7 +15,6 @@ package org.iiab.controller.redesign; import android.os.Bundle; -import android.os.StatFs; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; @@ -121,11 +120,11 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c sortGroup.setOnClickListener(v -> { view = "group"; render(); }); sortGroup.setVisibility(isWiki() ? View.VISIBLE : View.GONE); - try { - StatFs st = new StatFs(requireContext().getFilesDir().getPath()); - freeMb = st.getAvailableBytes() / (1024L * 1024L); - totalMb = st.getTotalBytes() / (1024L * 1024L); - } catch (Exception e) { freeMb = 0; totalMb = 0; } + // ADFA-5105: shared free-space probe instead of a per-screen StatFs copy. + Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); + Long tb = org.iiab.controller.storage.StorageProbe.totalBytes(requireContext()); + freeMb = (fb == null ? 0L : fb) / (1024L * 1024L); + totalMb = (tb == null ? 0L : tb) / (1024L * 1024L); KiwixCatalog.getOrFetch(requireContext(), new KiwixCatalog.Listener() { @Override public void onReady(JSONObject c) { if (!isAdded()) return; catalog = c; rebuild(); } diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ZimConfirmFragment.java b/controller/app/src/main/java/org/iiab/controller/redesign/ZimConfirmFragment.java index 6cfc0caaa..4251a2f9b 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ZimConfirmFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ZimConfirmFragment.java @@ -13,7 +13,6 @@ import android.graphics.Typeface; import android.os.Bundle; -import android.os.StatFs; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; @@ -75,9 +74,9 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c box.addView(row(getString(R.string.k2go_zim_total), "", gb(total / (1024L * 1024L)), true)); long totalMb = total / (1024L * 1024L); - long freeMb; - try { freeMb = new StatFs(requireContext().getFilesDir().getPath()).getAvailableBytes() / (1024L * 1024L); } - catch (Exception e) { freeMb = 0; } + // ADFA-5105: shared free-space probe instead of a per-screen StatFs copy. + Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); + long freeMb = (fb == null ? 0L : fb) / (1024L * 1024L); boolean fits = freeMb <= 0 || totalMb <= freeMb; TextView fitsView = root.findViewById(R.id.k2go_zconf_fits); fitsView.setText(fits diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ZimLandingFragment.java b/controller/app/src/main/java/org/iiab/controller/redesign/ZimLandingFragment.java index becc4576e..80dc3e070 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ZimLandingFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ZimLandingFragment.java @@ -13,7 +13,6 @@ package org.iiab.controller.redesign; import android.os.Bundle; -import android.os.StatFs; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; @@ -97,11 +96,11 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c }); root.findViewById(R.id.k2go_zim_lang_box).setOnClickListener(v -> pickLanguage()); - try { - StatFs st = new StatFs(requireContext().getFilesDir().getPath()); - freeMb = st.getAvailableBytes() / (1024L * 1024L); - totalMb = st.getTotalBytes() / (1024L * 1024L); - } catch (Exception e) { freeMb = 0; totalMb = 0; } + // ADFA-5105: shared free-space probe instead of a per-screen StatFs copy. + Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); + Long tb = org.iiab.controller.storage.StorageProbe.totalBytes(requireContext()); + freeMb = (fb == null ? 0L : fb) / (1024L * 1024L); + totalMb = (tb == null ? 0L : tb) / (1024L * 1024L); updateLangLabel(); updateStorage(); diff --git a/controller/app/src/main/java/org/iiab/controller/rootfs/data/RootfsCatalog.java b/controller/app/src/main/java/org/iiab/controller/rootfs/data/RootfsCatalog.java index 307afb40d..06584463a 100644 --- a/controller/app/src/main/java/org/iiab/controller/rootfs/data/RootfsCatalog.java +++ b/controller/app/src/main/java/org/iiab/controller/rootfs/data/RootfsCatalog.java @@ -29,16 +29,33 @@ public class RootfsCatalog { private static final String CSV_ASSET = "rootfs_sizes.csv"; private static final String BASE_URL = "https://iiab.switnet.org/android/rootfs/"; - // Emergency-net fallbacks (used only if the CSV is missing/unreadable). - private static final long FALLBACK_BASIC_ARM64 = 1_219_422_532L; // 1.14 GiB - private static final long FALLBACK_STANDARD_ARM64 = 1_428_970_336L; // 1.33 GiB - private static final long FALLBACK_FULL_ARM64 = 2_926_676_923L; // 2.73 GiB - private static final long FALLBACK_BASIC_ARMV7 = 1_220_401_364L; // 1.14 GiB - private static final long FALLBACK_STANDARD_ARMV7 = 1_429_892_132L; // 1.33 GiB - private static final long FALLBACK_FULL_ARMV7 = 2_917_715_443L; // 2.72 GiB - - /** Parsed CSV, loaded once per process. Empty map => use the emergency-net constants. */ + // Emergency-net COMPRESSED (download) fallbacks — used only if the CSV is missing/unreadable. + // Captured from latest_*.meta4, build 2026.224 (sha 8d15d79, 2026-08-12). + private static final long FALLBACK_BASIC_ARM64 = 1_936_814_083L; // ~1.80 GiB + private static final long FALLBACK_STANDARD_ARM64 = 2_146_100_011L; // ~2.00 GiB + private static final long FALLBACK_FULL_ARM64 = 2_841_912_764L; // ~2.65 GiB + private static final long FALLBACK_BASIC_ARMV7 = 1_937_574_673L; // ~1.80 GiB + private static final long FALLBACK_STANDARD_ARMV7 = 2_146_813_777L; // ~2.00 GiB + private static final long FALLBACK_FULL_ARMV7 = 2_833_106_837L; // ~2.64 GiB + + // Emergency-net UNCOMPRESSED (installed) fallbacks — the destructive guard's "needed", measured + // by the builder (ADFA-5110) and published as latest_*.installed. Same build as above. + private static final long INSTALLED_BASIC_ARM64 = 3_294_993_334L; // ~3.07 GiB + private static final long INSTALLED_STANDARD_ARM64 = 3_675_639_489L; // ~3.42 GiB + private static final long INSTALLED_FULL_ARM64 = 5_103_603_118L; // ~4.75 GiB + private static final long INSTALLED_BASIC_ARMV7 = 3_162_669_853L; // ~2.95 GiB + private static final long INSTALLED_STANDARD_ARMV7 = 3_542_808_901L; // ~3.30 GiB + private static final long INSTALLED_FULL_ARMV7 = 4_856_267_277L; // ~4.52 GiB + + // ADFA-5105: the destructive free-space guard needs the UNCOMPRESSED (installed) footprint — + // what an extraction actually writes — not the compressed download above. It comes from the + // installed_bytes CSV column (refreshed from the latest_*.installed sidecar the builder now + // publishes, ADFA-5110), with the measured emergency-net constants above as the offline fallback. + + /** Parsed CSV of COMPRESSED download sizes, loaded once per process. Empty => emergency-net. */ private static volatile Map csvSizes; + /** Parsed CSV of UNCOMPRESSED sizes (optional 5th column, ADFA-5110). Absent => estimate. */ + private static volatile Map csvInstalled; /** No-arg: emergency-net only (no CSV). Kept for callers without a Context. */ public RootfsCatalog() { } @@ -51,6 +68,7 @@ private static void ensureCsvLoaded(Context context) { synchronized (RootfsCatalog.class) { if (csvSizes != null) return; Map m = new HashMap<>(); + Map mi = new HashMap<>(); try (BufferedReader r = new BufferedReader( new InputStreamReader(context.getAssets().open(CSV_ASSET)))) { String line; @@ -63,11 +81,19 @@ private static void ensureCsvLoaded(Context context) { m.put(key(p[0].trim(), p[1].trim()), Long.parseLong(p[2].trim())); } catch (NumberFormatException ignore) { /* skip malformed row */ } } + // Optional installed_bytes column (ADFA-5110). Absent in the current CSV, so this + // stays empty until the build publishes it; installedBytes() then estimates. + if (p.length >= 5) { + try { + mi.put(key(p[0].trim(), p[1].trim()), Long.parseLong(p[4].trim())); + } catch (NumberFormatException ignore) { /* not the installed column yet */ } + } } } catch (Exception e) { Log.w(TAG, "rootfs_sizes.csv not read (" + e.getMessage() + "); using emergency-net sizes"); } csvSizes = m; + csvInstalled = mi; } } @@ -80,6 +106,56 @@ public String metaUrl(RootfsTier tier, RootfsAbi abi) { return BASE_URL + "latest_" + tier.name().toLowerCase(Locale.US) + "_" + abi.id() + ".meta4"; } + /** Stable sidecar URL for the UNCOMPRESSED size (ADFA-5110), + * e.g. {@code .../latest_full_arm64-v8a.installed} — a single integer, bytes. */ + public String installedUrl(RootfsTier tier, RootfsAbi abi) { + return BASE_URL + "latest_" + tier.name().toLowerCase(Locale.US) + "_" + abi.id() + ".installed"; + } + + /** + * Uncompressed (installed) size in bytes for a tier+abi — what an extraction actually writes, + * and the "needed" figure the destructive free-space guard (ADFA-5105) checks. Prefers the + * measured value from the CSV installed column (ADFA-5110); until that is published it returns a + * conservative estimate from the compressed download size. Never returns {@code <= 0}. + */ + public long installedBytes(RootfsTier tier, RootfsAbi abi) { + Map csv = csvInstalled; + if (csv != null) { + Long v = csv.get(key(tier.name(), abi.id())); + if (v != null && v > 0) return v; + } + return installedFallbackBytes(tier, abi); + } + + /** + * Peak disk a fresh rootfs install needs (ADFA-5105): the compressed download and the + * uncompressed tree COEXIST during extraction (the .tar.gz is only deleted after it finishes), + * and the free-space gate runs before the download — so both get written after it. The peak the + * device must hold is compressed + uncompressed, not just the final footprint. + */ + public long peakInstallBytes(RootfsTier tier, RootfsAbi abi) { + long peak = installedBytes(tier, abi) + fallbackBytes(tier, abi); + return peak < 0 ? Long.MAX_VALUE : peak; // saturate on the (impossible) overflow + } + + /** Last-known measured uncompressed size (emergency net) for a tier+abi. Never {@code <= 0}. */ + private long installedFallbackBytes(RootfsTier tier, RootfsAbi abi) { + if (abi == RootfsAbi.ARMEABI_V7A) { + switch (tier) { + case BASIC: return INSTALLED_BASIC_ARMV7; + case STANDARD: return INSTALLED_STANDARD_ARMV7; + case FULL: return INSTALLED_FULL_ARMV7; + } + } else { + switch (tier) { + case BASIC: return INSTALLED_BASIC_ARM64; + case STANDARD: return INSTALLED_STANDARD_ARM64; + case FULL: return INSTALLED_FULL_ARM64; + } + } + return INSTALLED_BASIC_ARM64; + } + /** Last-known fallback size in bytes for a tier+abi: CSV first, constants as the net. */ public long fallbackBytes(RootfsTier tier, RootfsAbi abi) { Map csv = csvSizes; diff --git a/controller/app/src/main/java/org/iiab/controller/storage/FreeSpacePreflight.java b/controller/app/src/main/java/org/iiab/controller/storage/FreeSpacePreflight.java new file mode 100644 index 000000000..df4c7765c --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/storage/FreeSpacePreflight.java @@ -0,0 +1,53 @@ +/* + * ============================================================================ + * Name : FreeSpacePreflight.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5105. The one preflight every destructive route calls + * before it wipes: reads free space (StorageProbe, on the real + * write target), asks the single rule (StorageGuard), and returns + * a proceed/refuse result with the shortfall for the message. + * + * Fail-safe by construction for destructive callers: it proceeds + * only on FITS, so both DOES_NOT_FIT and UNKNOWN free space refuse + * (a wipe that then runs out of disk leaves an unbootable rootfs). + * Advisory callers that want "allow on unknown" should read + * StorageGuard directly instead of this. + * ============================================================================ + */ +package org.iiab.controller.storage; + +import android.content.Context; + +public final class FreeSpacePreflight { + + private FreeSpacePreflight() {} + + /** Outcome of a destructive preflight. */ + public static final class Result { + /** True only when the run fits with the margin; false means refuse. */ + public final boolean ok; + /** Bytes the run needs (the "needed" that was checked). */ + public final long neededBytes; + /** Bytes short of fitting (0 when it fits, or when free space is unknown). */ + public final long shortfallBytes; + + Result(boolean ok, long neededBytes, long shortfallBytes) { + this.ok = ok; + this.neededBytes = neededBytes; + this.shortfallBytes = shortfallBytes; + } + + /** The amount to surface in a refusal message: the shortfall if known, else the need. */ + public long amountToReport() { + return shortfallBytes > 0 ? shortfallBytes : neededBytes; + } + } + + /** Check {@code neededBytes} against the free space on the app's files filesystem. */ + public static Result check(Context ctx, long neededBytes) { + Long free = StorageProbe.freeBytes(ctx); + boolean ok = StorageGuard.evaluate(free, neededBytes) == StorageGuard.Verdict.FITS; + return new Result(ok, neededBytes, StorageGuard.shortfallBytes(free, neededBytes)); + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/storage/SpaceEstimate.java b/controller/app/src/main/java/org/iiab/controller/storage/SpaceEstimate.java new file mode 100644 index 000000000..bb5cc9731 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/storage/SpaceEstimate.java @@ -0,0 +1,36 @@ +/* + * ============================================================================ + * Name : SpaceEstimate.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5105. Estimate the extracted (uncompressed) footprint of a + * compressed archive when no measured value exists. The rootfs now + * carries a measured size (ADFA-5110), so this only backs RESTORE: + * user backups are created on-device and don't record their + * original size, so all we have is the archive's compressed size + * (File.length() when the file is picked) times a factor. 2.2x sits + * above the ~1.63–1.80x a rootfs-shaped archive expands (the max + * measured across tiers), so the guard errs toward refusing; the + * StorageGuard margin adds more slack on top. A heuristic — a + * principled replacement (read the archive's real size) is a + * follow-up. Pure JVM, unit-testable, overflow-safe. + * ============================================================================ + */ +package org.iiab.controller.storage; + +public final class SpaceEstimate { + + private SpaceEstimate() {} + + // 2.2x. Kept as a fraction (not a double) so the math is exact and overflow-safe. + public static final int UNCOMPRESSED_NUMERATOR = 22; + public static final int UNCOMPRESSED_DENOMINATOR = 10; + + /** Conservative uncompressed-size estimate from a compressed size, in bytes. */ + public static long fromCompressed(long compressedBytes) { + long c = Math.max(0L, compressedBytes); + long est = (c / UNCOMPRESSED_DENOMINATOR) * UNCOMPRESSED_NUMERATOR + + ((c % UNCOMPRESSED_DENOMINATOR) * UNCOMPRESSED_NUMERATOR) / UNCOMPRESSED_DENOMINATOR; + return est < c ? Long.MAX_VALUE : est; // saturate on overflow (factor >= 1, so est >= c) + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/storage/StorageGuard.java b/controller/app/src/main/java/org/iiab/controller/storage/StorageGuard.java new file mode 100644 index 000000000..2d1fa937d --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/storage/StorageGuard.java @@ -0,0 +1,77 @@ +/* + * ============================================================================ + * Name : StorageGuard.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5105. The single free-space rule, asked before any + * destructive run (install / reinstall / restore / reset) and by + * the advisory "does this fit" labels on the content pickers. + * + * Replaces sixteen hand-rolled readers with two magic margins + * (-5.0 GB absolute in the legacy install + clone-receive, +10% + * relative in the Kolibri seed plan). One margin, decided once + * (ADFA-5105): the headroom required is the LARGER of an absolute + * floor and a fraction of the operation size, so small ops are + * protected by the floor and large ops by the fraction. + * + * Pure JVM (no android.*) so it is unit-testable — the Android + * StatFs read of the actual write target is a thin caller, kept + * out of here on purpose (same split as SeedPlan). Three-state + * verdict: destructive callers must treat UNKNOWN as "refuse" + * (fail-safe, since a wipe that runs out of disk leaves an + * unbootable rootfs); advisory labels may treat UNKNOWN as + * "allow" — one helper, the interpretation lives at the call site. + * ============================================================================ + */ +package org.iiab.controller.storage; + +public final class StorageGuard { + + /** Absolute headroom floor (2 GiB): the minimum slack left free after any op. */ + public static final long DEFAULT_FLOOR_BYTES = 2L * 1024 * 1024 * 1024; + /** Relative headroom (10% of the operation size), used when it exceeds the floor. */ + public static final int DEFAULT_MARGIN_PERCENT = 10; + + public enum Verdict { FITS, DOES_NOT_FIT, UNKNOWN } + + private StorageGuard() {} + + /** Bytes that must be free for {@code neededBytes} to fit, headroom included. */ + public static long requiredBytes(long neededBytes) { + return requiredBytes(neededBytes, DEFAULT_FLOOR_BYTES, DEFAULT_MARGIN_PERCENT); + } + + /** As above with an explicit policy. Overflow-safe and never returns less than {@code needed}. */ + public static long requiredBytes(long neededBytes, long floorBytes, int marginPercent) { + long need = Math.max(0L, neededBytes); + long floor = Math.max(0L, floorBytes); + int pct = Math.max(0, marginPercent); + // need * pct / 100 without the intermediate overflow of a full multiply. + long relative = (need / 100L) * pct + ((need % 100L) * pct) / 100L; + long headroom = Math.max(floor, relative); + long required = need + headroom; + return required < need ? Long.MAX_VALUE : required; // saturate on overflow + } + + /** FITS / DOES_NOT_FIT / UNKNOWN (null or negative free space) with the default policy. */ + public static Verdict evaluate(Long freeBytes, long neededBytes) { + return evaluate(freeBytes, neededBytes, DEFAULT_FLOOR_BYTES, DEFAULT_MARGIN_PERCENT); + } + + public static Verdict evaluate(Long freeBytes, long neededBytes, long floorBytes, int marginPercent) { + if (freeBytes == null || freeBytes < 0L) return Verdict.UNKNOWN; + return freeBytes >= requiredBytes(neededBytes, floorBytes, marginPercent) + ? Verdict.FITS : Verdict.DOES_NOT_FIT; + } + + /** How many more bytes are needed to fit (0 when it fits, or when free space is unknown). */ + public static long shortfallBytes(Long freeBytes, long neededBytes) { + return shortfallBytes(freeBytes, neededBytes, DEFAULT_FLOOR_BYTES, DEFAULT_MARGIN_PERCENT); + } + + public static long shortfallBytes(Long freeBytes, long neededBytes, long floorBytes, int marginPercent) { + if (freeBytes == null || freeBytes < 0L) return 0L; + long deficit = requiredBytes(neededBytes, floorBytes, marginPercent) - freeBytes; + return Math.max(0L, deficit); + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/storage/StorageProbe.java b/controller/app/src/main/java/org/iiab/controller/storage/StorageProbe.java new file mode 100644 index 000000000..e2f888f78 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/storage/StorageProbe.java @@ -0,0 +1,62 @@ +/* + * ============================================================================ + * Name : StorageProbe.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5105. The single Android read of free space — the thin + * android.* half of the storage guard (StorageGuard holds the + * pure rule). Measures the filesystem that actually receives the + * write: the app's private files dir, where the rootfs lives + * (getFilesDir()/rootfs for InstallService and DeepOpService). + * + * This replaces the split the ticket flags — some callers read + * Environment.getDataDirectory() (/data) instead of getFilesDir(), + * which can be a different filesystem (notably under proot). One + * reader, one target, in bytes. Returns null when it can't be + * read, so a destructive caller (StorageGuard UNKNOWN) refuses + * rather than guesses. + * ============================================================================ + */ +package org.iiab.controller.storage; + +import android.content.Context; +import android.os.StatFs; + +import java.io.File; + +public final class StorageProbe { + + private StorageProbe() {} + + /** Free bytes on the filesystem holding the app's private files (where the rootfs is written), + * or null if it can't be read. */ + public static Long freeBytes(Context ctx) { + return ctx == null ? null : freeBytesAt(ctx.getFilesDir()); + } + + /** Free bytes on the filesystem holding {@code target}, measured at its nearest existing + * ancestor (StatFs needs a path that exists — the rootfs dir may not yet), or null on failure. */ + public static Long freeBytesAt(File target) { + File p = target; + while (p != null && !p.exists()) p = p.getParentFile(); + if (p == null) return null; + try { + return new StatFs(p.getAbsolutePath()).getAvailableBytes(); + } catch (Exception e) { + return null; + } + } + + /** Total bytes on the app's files filesystem (for "used / free" labels), or null if unreadable. */ + public static Long totalBytes(Context ctx) { + if (ctx == null) return null; + File p = ctx.getFilesDir(); + while (p != null && !p.exists()) p = p.getParentFile(); + if (p == null) return null; + try { + return new StatFs(p.getAbsolutePath()).getTotalBytes(); + } catch (Exception e) { + return null; + } + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/sync/presentation/SyncStateViewModel.java b/controller/app/src/main/java/org/iiab/controller/sync/presentation/SyncStateViewModel.java index e678cab5c..b8a64a2fe 100644 --- a/controller/app/src/main/java/org/iiab/controller/sync/presentation/SyncStateViewModel.java +++ b/controller/app/src/main/java/org/iiab/controller/sync/presentation/SyncStateViewModel.java @@ -111,9 +111,14 @@ public void startProbe(Context appCtx, ShareConfig shareConfig, SyncHandshakeHel @Override public void onCalculated(long bytesToTransfer) { double gigabytes = bytesToTransfer / (1024.0 * 1024.0 * 1024.0); - double freeSpaceGb = android.os.Environment.getDataDirectory().getFreeSpace() - / (1024.0 * 1024.0 * 1024.0); - if (gigabytes > (freeSpaceGb - 5.0)) { + // ADFA-5105: one margin (StorageGuard) on the real write target (StorageProbe), + // not a second -5 GB copy. Clone-receive overwrites the library, so refuse on + // UNKNOWN free space too (anything but FITS). + Long freeBytes = org.iiab.controller.storage.StorageProbe.freeBytes(appCtx); + if (org.iiab.controller.storage.StorageGuard.evaluate(freeBytes, bytesToTransfer) + != org.iiab.controller.storage.StorageGuard.Verdict.FITS) { + double freeSpaceGb = (freeBytes == null ? 0.0 : freeBytes) + / (1024.0 * 1024.0 * 1024.0); repo.postAborted(appCtx.getString(R.string.sync_error_storage_title), appCtx.getString(R.string.sync_error_storage_msg, gigabytes, freeSpaceGb)); return; diff --git a/controller/app/src/main/res/values/strings.xml b/controller/app/src/main/res/values/strings.xml index 94a91e5bc..b65f0185b 100644 --- a/controller/app/src/main/res/values/strings.xml +++ b/controller/app/src/main/res/values/strings.xml @@ -321,7 +321,7 @@ Export failed: %1$s Hey! Select an edition to install (Basic, Standard, or Full). - Not enough storage! Please free up space or choose a smaller edition. (5GB safety buffer required) + Not enough storage. Free up space or choose a smaller edition, then try again. OS: %1$d%% | %2$s Extracting System...\n(This takes a while) Error: Downloaded archive not found. @@ -401,7 +401,7 @@ Analyzing system differences...\nThis may take a couple of minutes. Insufficient Storage - The update requires %1$.2f GB, but you only have %2$.2f GB available (considering a 5GB safety buffer). + The update requires %1$.2f GB, but only %2$.2f GB is available (with a safety margin). Update System Install System You are about to download %.2f GB.\nYou have enough storage space.\n\nDo you want to start the transfer now? diff --git a/controller/app/src/test/java/org/iiab/controller/storage/SpaceEstimateTest.java b/controller/app/src/test/java/org/iiab/controller/storage/SpaceEstimateTest.java new file mode 100644 index 000000000..db629c29b --- /dev/null +++ b/controller/app/src/test/java/org/iiab/controller/storage/SpaceEstimateTest.java @@ -0,0 +1,40 @@ +/* + * ============================================================================ + * Name : SpaceEstimateTest.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5105. Unit tests for the compressed -> uncompressed + * estimate: the 2.3x factor, zero/negative handling, and overflow + * saturation. + * ============================================================================ + */ +package org.iiab.controller.storage; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class SpaceEstimateTest { + + @Test + public void appliesTheFactor() { + assertEquals(2200L, SpaceEstimate.fromCompressed(1000L)); + } + + @Test + public void isExactOnAwkwardRemainders() { + // 2_834_585_013 * 22 / 10 = 6_236_087_028 (floor) + assertEquals(6_236_087_028L, SpaceEstimate.fromCompressed(2_834_585_013L)); + } + + @Test + public void zeroAndNegativeAreZero() { + assertEquals(0L, SpaceEstimate.fromCompressed(0L)); + assertEquals(0L, SpaceEstimate.fromCompressed(-5L)); + } + + @Test + public void saturatesInsteadOfOverflowing() { + assertEquals(Long.MAX_VALUE, SpaceEstimate.fromCompressed(Long.MAX_VALUE)); + } +} diff --git a/controller/app/src/test/java/org/iiab/controller/storage/StorageGuardTest.java b/controller/app/src/test/java/org/iiab/controller/storage/StorageGuardTest.java new file mode 100644 index 000000000..bab086c0b --- /dev/null +++ b/controller/app/src/test/java/org/iiab/controller/storage/StorageGuardTest.java @@ -0,0 +1,111 @@ +/* + * ============================================================================ + * Name : StorageGuardTest.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : ADFA-5105. Unit tests for the single free-space rule: the + * hybrid margin max(floor, %), the FITS/DOES_NOT_FIT/UNKNOWN + * verdict (UNKNOWN on null/negative free space), the shortfall, + * the margin clamp, and overflow saturation. + * ============================================================================ + */ +package org.iiab.controller.storage; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class StorageGuardTest { + + private static final long GB = 1024L * 1024 * 1024; + + // ---- requiredBytes: hybrid margin max(floor, %) -------------------------- + + @Test + public void floorDominatesForSmallOperations() { + // 1 GB op: 10% = 0.1 GB < 2 GB floor, so headroom is the floor. + assertEquals(3L * GB, StorageGuard.requiredBytes(1L * GB)); + } + + @Test + public void percentDominatesForLargeOperations() { + // 50 GB op: 10% = 5 GB > 2 GB floor, so headroom is the fraction. + assertEquals(55L * GB, StorageGuard.requiredBytes(50L * GB)); + } + + @Test + public void zeroNeededStillRequiresTheFloor() { + assertEquals(2L * GB, StorageGuard.requiredBytes(0L)); + } + + @Test + public void negativeNeededIsTreatedAsZero() { + assertEquals(2L * GB, StorageGuard.requiredBytes(-123L)); + } + + // ---- evaluate: three-state verdict -------------------------------------- + + @Test + public void fitsExactlyAtTheRequiredBoundary() { + assertEquals(StorageGuard.Verdict.FITS, StorageGuard.evaluate(3L * GB, 1L * GB)); + } + + @Test + public void doesNotFitOneByteBelowRequired() { + assertEquals(StorageGuard.Verdict.DOES_NOT_FIT, StorageGuard.evaluate(3L * GB - 1L, 1L * GB)); + } + + @Test + public void unknownWhenFreeSpaceIsNull() { + assertEquals(StorageGuard.Verdict.UNKNOWN, StorageGuard.evaluate(null, 1L * GB)); + } + + @Test + public void unknownWhenFreeSpaceIsNegative() { + assertEquals(StorageGuard.Verdict.UNKNOWN, StorageGuard.evaluate(-1L, 1L * GB)); + } + + // ---- shortfall ---------------------------------------------------------- + + @Test + public void shortfallIsHowMuchMoreIsNeeded() { + // needs 3 GB, has 2 GB -> 1 GB short. + assertEquals(1L * GB, StorageGuard.shortfallBytes(2L * GB, 1L * GB)); + } + + @Test + public void shortfallIsZeroWhenItFits() { + assertEquals(0L, StorageGuard.shortfallBytes(3L * GB, 1L * GB)); + } + + @Test + public void shortfallIsZeroWhenFreeSpaceIsUnknown() { + assertEquals(0L, StorageGuard.shortfallBytes(null, 1L * GB)); + } + + // ---- policy overrides --------------------------------------------------- + + @Test + public void aMarginBelowZeroIsClampedToTheFloorOnly() { + // pct clamped to 0 -> headroom is exactly the floor. + assertEquals(12L * GB, StorageGuard.requiredBytes(10L * GB, 2L * GB, -5)); + } + + @Test + public void anExplicitPolicyIsHonoured() { + // 20 GB op, 1 GB floor, 25% -> headroom = max(1, 5) GB = 5 GB. + assertEquals(25L * GB, StorageGuard.requiredBytes(20L * GB, 1L * GB, 25)); + } + + // ---- overflow safety ---------------------------------------------------- + + @Test + public void requiredSaturatesInsteadOfOverflowing() { + assertEquals(Long.MAX_VALUE, StorageGuard.requiredBytes(Long.MAX_VALUE)); + } + + @Test + public void anImpossiblyLargeOperationDoesNotFit() { + assertEquals(StorageGuard.Verdict.DOES_NOT_FIT, StorageGuard.evaluate(100L * GB, Long.MAX_VALUE)); + } +}