Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* it is TRUE while a deep-env op is in progress, regardless of the server state.
*
* Generalizes the older, fragmented pieces: InstallGuard (durable "install in progress"
* marker) + InstallJobs.isBusy() (process-scoped "a runrole/download is running"). Adds a
* marker) + the process-scoped "a runrole/download is running" signal (isBusyNow). Adds a
* durable OWNER marker for ops that have no process-scoped repository of their own
* (backup/restore/clone).
*
Expand Down Expand Up @@ -49,6 +49,10 @@ public final class EnvironmentLock {
/** Who holds (or would hold) the lock. */
public enum Owner { INSTALL, MODULE, BACKUP, RESTORE, CLONE }

/** ADFA-5146: what is actually holding the environment, for a refusal message that names the
* real cause instead of always saying "an install". */
public enum Holder { CLONE, BACKUP, RESTORE, INSTALL, DOWNLOAD, NONE }

// Owner marker: line 1 = Owner.name(), line 2 = epoch millis, line 3 = session token.
private static final String MARKER = ".env_lock";
// Unique per process launch: re-generated when the class is (re)loaded in a fresh process, so a
Expand All @@ -63,26 +67,21 @@ private static File marker(Context ctx) {

/**
* Process-scoped signal: a runrole is in flight, or a REST download is running (a deep-env op would
* kill it by stopping the server). Matches the legacy {@code InstallJobs.isBusy()} exactly, so its
* callers keep the same behavior when they delegate here.
* kill it by stopping the server). ADFA-5146: content-download sources count only while their poll
* heartbeat is fresh (isActiveNow), so a killed service's stale session no longer blocks forever.
*/
public static boolean isBusyNow() {
if (org.iiab.controller.install.presentation.ModuleQueueRepository.get().isRunning()) return true;
if (org.iiab.controller.redesign.ZimDownloadService.hasSession()
&& !org.iiab.controller.redesign.ZimDownloadService.isComplete()) return true;
if (org.iiab.controller.redesign.BooksDownloadService.hasSession()
&& !org.iiab.controller.redesign.BooksDownloadService.isComplete()) return true;
// ADFA-5074: Courses were never added here. A backup, restore, clone or maps runrole
// could start on top of a live seeding session and stop the server underneath it —
// exactly what the note above says this guard exists to prevent. The third content
// type arrived after the list and nobody registered it, the same way it was missed in
// the post-install drain and in the index's completion check.
//
// Same idiom as its neighbours on purpose: a session that has FINISHED protects
// nothing, so it must not gate a deep-env op. Only work in flight does.
org.iiab.controller.kolibri.presentation.KolibriSeedRepository kolibri =
org.iiab.controller.kolibri.presentation.KolibriSeedRepository.get();
if (kolibri.hasSession() && !kolibri.isComplete()) return true;
// ADFA-5146: the three content downloads (ZIM, Books, Courses) count as busy only while a
// non-terminal session's poll heartbeat is still fresh. A service killed before a terminal
// state used to leave hasSession() && !isComplete() true forever, blocking every deep-env op
// with no exit but force-stopping the app; isActiveNow() folds the freshness check in, so a
// dead session ages out. A live download (even a long, slow one) refreshes every poll and
// keeps blocking; a finished one never blocks. The module queue keeps its own signal — its
// stuck case is dominated by the durable install guard (ADFA-5147-adjacent), not this flag.
if (org.iiab.controller.redesign.ZimDownloadService.isActiveNow()) return true;
if (org.iiab.controller.redesign.BooksDownloadService.isActiveNow()) return true;
if (org.iiab.controller.kolibri.presentation.KolibriSeedRepository.get().isActiveNow()) return true;
return false;
}

Expand All @@ -104,11 +103,15 @@ public static boolean isBusyNow() {
* operation already in progress (or is it unsafe to start one)? Combines the process-scoped signal,
* the durable install guard, and this-process's owner marker. Ask THIS, not
* {@code ServerStateRepository.alive}.
*
* ADFA-5146: derived from {@link #currentHolder} so "is it held" and "what holds it" can never
* disagree. currentHolder is the ONE place that enumerates the lock sources; anything added there is
* picked up here for free. Do NOT re-list the sources in this method — a second copy is exactly the
* drift this derivation exists to prevent (isHeld would block while the refusal message named the
* wrong holder, or fell back to "an install").
*/
public static boolean isHeld(Context ctx) {
return isBusyNow()
|| org.iiab.controller.InstallGuard.inProgress(ctx)
|| ownerHeld(ctx);
return currentHolder(ctx) != Holder.NONE;
}

/**
Expand Down Expand Up @@ -154,6 +157,33 @@ public static synchronized Owner currentOwner(Context ctx) {
}
}

/**
* ADFA-5146: which operation holds the environment right now, AND the single source of truth for
* "is it held at all" — {@link #isHeld} derives from this ({@code != NONE}). Priority (highest
* first, so the label names the dominant op): the owner marker (clone / backup / restore, or a
* write-op install), then the durable install guard, then a live content download (post-expiry, so
* a dead session never shows). Returns {@code NONE} when nothing holds it.
*
* To add a new lock source, add it HERE (with a Holder value + a k2go_busy_* string). isHeld and
* every deep-op gate then pick it up automatically — that is the whole point of routing both
* questions through one method.
*/
public static Holder currentHolder(Context ctx) {
Owner owner = currentOwner(ctx);
if (owner != null) {
switch (owner) {
case CLONE: return Holder.CLONE;
case BACKUP: return Holder.BACKUP;
case RESTORE: return Holder.RESTORE;
case INSTALL:
case MODULE: return Holder.INSTALL;
}
}
if (org.iiab.controller.InstallGuard.inProgress(ctx)) return Holder.INSTALL;
if (isBusyNow()) return Holder.DOWNLOAD; // module installs are caught above by the guard
return Holder.NONE;
}

/** Epoch millis when this-process's owner acquired the lock, or 0 if not held (or stale). */
public static synchronized long heldSince(Context ctx) {
if (!ownerHeld(ctx)) return 0L;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* ============================================================================
* Name : Freshness.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : ADFA-5146. One definition of "is this in-memory session still alive?" — a
* last-progress heartbeat compared against a staleness window. A live download
* refreshes its timestamp every poll; a service killed before a terminal state
* lets it go cold, so EnvironmentLock.isBusyNow() can stop treating a dead
* session as work in flight without the app being force-stopped. Pure JVM (no
* android.*): the caller passes a monotonic 'now' (SystemClock.elapsedRealtime),
* which keeps this unit-testable and immune to wall-clock changes.
* ============================================================================
*/
package org.iiab.controller.env;

public final class Freshness {

private Freshness() {
}

/** Shared staleness window for the content-download sources (they poll ~1s, so 30s is well
* above the cadence and normal hiccups, and well below a user's patience). Generous on
* purpose: a too-short window could treat a live-but-slow download as dead and let a deep
* operation start on top of it. ADFA-5146. */
public static final long STALE_MS = 30_000L;

/** True when {@code lastAtMs} sits within {@code thresholdMs} of {@code nowMs}. A never-stamped
* session (0) is not fresh. {@code nowMs} must come from a monotonic clock
* (SystemClock.elapsedRealtime), the same source the stamp was taken from. */
public static boolean fresh(long lastAtMs, long nowMs, long thresholdMs) {
if (lastAtMs <= 0L) return false;
return nowMs - lastAtMs <= thresholdMs;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ public static KolibriSeedRepository get() {
* a download is exactly long enough for that to happen.
*/
private long startedAtMs = 0L;
private volatile long lastProgressAtMs = 0L; // ADFA-5146: last-progress heartbeat (elapsedRealtime)

private KolibriSeedRepository() {
}
Expand All @@ -95,6 +96,15 @@ public boolean isComplete() {
return current().isComplete();
}

/** ADFA-5146: busy only while the seed's poll heartbeat is fresh — a killed seed service lets
* it go cold, so a dead session stops blocking deep operations. */
public boolean isActiveNow() {
return hasSession() && !isComplete()
&& org.iiab.controller.env.Freshness.fresh(
lastProgressAtMs, android.os.SystemClock.elapsedRealtime(),
org.iiab.controller.env.Freshness.STALE_MS);
}

// ---- writes (service only) --------------------------------------------

/**
Expand All @@ -116,6 +126,7 @@ private interface Transition {
/** Replaces any previous session. */
public synchronized void startSession(List<KolibriSeedState.Item> queued) {
startedAtMs = android.os.SystemClock.elapsedRealtime();
lastProgressAtMs = startedAtMs; // ADFA-5146: seed the heartbeat at session start
mutate(from -> KolibriSeedState.of(queued));
}

Expand All @@ -140,6 +151,7 @@ public void itemStarted(int index) {
*/
public synchronized void itemProgress(int index, int percent, long speedBytesPerSec) {
final long now = android.os.SystemClock.elapsedRealtime();
lastProgressAtMs = now; // ADFA-5146: heartbeat on each seed poll
mutate(from -> {
KolibriSeedState next = from.progress(index, percent, speedBytesPerSec);
if (speedBytesPerSec > 0L || startedAtMs <= 0L) {
Expand Down Expand Up @@ -174,6 +186,7 @@ public void sessionStopped() {
/** Clears the session so a new selection can start clean. */
public synchronized void clearSession() {
startedAtMs = 0L; // ADFA-5074: the next session brings its own start time
lastProgressAtMs = 0L; // ADFA-5146
mutate(from -> KolibriSeedState.idle());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c

private void launchPicker() {
if (EnvironmentLock.isHeld(requireContext())) { // another deep-env op owns the environment
Snackbars.make(requireView(), R.string.k2go_install_busy).show();
Snackbars.make(requireView(), org.iiab.controller.util.BusyMessage.resFor(requireContext())).show();
popToIntro(false);
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ public interface Listener { void onUpdate(); }
private static String[] sUrls = new String[0];
private static int[] sStatus = new int[0];
private static int sIndex = 0;
private static volatile long sLastProgressAt = 0L; // ADFA-5146: last-progress heartbeat (elapsedRealtime)
private static Listener sListener;

public static boolean isRunning() { return sRunning; }
Expand All @@ -76,6 +77,13 @@ public static boolean isComplete() {
for (int st : sStatus) if (st == PENDING || st == ACTIVE || st == ADDING) return false;
return true;
}
/** ADFA-5146: busy only while the poll heartbeat is fresh — a killed service lets it go cold. */
public static boolean isActiveNow() {
return hasSession() && !isComplete()
&& org.iiab.controller.env.Freshness.fresh(
sLastProgressAt, android.os.SystemClock.elapsedRealtime(),
org.iiab.controller.env.Freshness.STALE_MS);
}
public static String[] titles() { return sTitles; }
public static int[] status() { return sStatus; }
public static int index() { return sIndex; }
Expand All @@ -96,7 +104,7 @@ public static void retry(Context ctx, int i) {

public static void finishSession() {
sIds = new String[0]; sTitles = new String[0]; sUrls = new String[0]; sStatus = new int[0];
sIndex = 0; sRunning = false;
sIndex = 0; sRunning = false; sLastProgressAt = 0L;
}

private static final int MAX_ATTEMPTS = 3; // total tries per book before marking it failed
Expand Down Expand Up @@ -135,6 +143,7 @@ public int onStartCommand(Intent intent, int flags, int startId) {
}
canceled = false;
sRunning = true;
sLastProgressAt = android.os.SystemClock.elapsedRealtime(); // ADFA-5146: seed the heartbeat
startForeground(NOTIFICATION_ID, buildNotification(currentTitle()));
processNext();
return START_NOT_STICKY;
Expand Down Expand Up @@ -192,6 +201,7 @@ private void poll(int i) {
try {
JSONObject j = httpJson("GET", BASE + "/jobs/" + currentJobId, null);
String phase = j.optString("phase", "");
sLastProgressAt = android.os.SystemClock.elapsedRealtime(); // ADFA-5146: heartbeat on each answered poll
switch (phase) {
case "done":
android.util.Log.i("K2Go-Provision", "books job done [" + i + "]");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@ private enum Page { PREPARE, COPY }
private String apkFileName;

private ActivityResultLauncher<String> locationPerm;
// ADFA-5146: request the location permission at most once per attempt. ensureHotspot() runs on every
// render, and the permission callback re-renders; on OEMs that return a denied permission result
// synchronously that becomes unbounded recursion (render -> ensureHotspot -> launch -> sync-deny ->
// callback -> render …), overflowing the stack. This latch breaks the loop; setMode() clears it so a
// Hotspot/Wi-Fi switch is a natural retry path.
private boolean locationAsked = false;

private TextView tabSend, tabReceive, tabHotspot, tabWifi, caption, subCaption, advance, stop, footer;
// ADFA-4785: intent fork (Send / Receive) replaces the persistent top toggle.
Expand Down Expand Up @@ -423,6 +429,7 @@ private void requestMode(Mode target) {
private void setMode(Mode m) {
mode = m;
apRetries = 0; // ADFA-5158: fresh AP-IP poll budget on a mode switch
locationAsked = false; // ADFA-5146: a mode switch is a fresh attempt — allow one more perm prompt
netHandler.removeCallbacks(netRetry);
if (secJoin != null) secJoin.fbOpen = false; // ADFA-4815: each mode starts with ①'s fallback collapsed
if (m == Mode.HOTSPOT) ensureHotspot();
Expand All @@ -442,7 +449,10 @@ private void ensureHotspot() {
if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
hs.start(requireContext().getApplicationContext());
} else {
} else if (!locationAsked) {
// ADFA-5146: launch the request exactly once. Do NOT re-launch on later renders (incl. the one
// the permission callback triggers) — a synchronous deny would otherwise recurse into overflow.
locationAsked = true;
locationPerm.launch(Manifest.permission.ACCESS_FINE_LOCATION);
}
}
Expand All @@ -457,7 +467,7 @@ private void ensureDaemon(String ip) {
// another one (install/backup/restore) holds the lock, else acquire(CLONE) and stop the server
// so the served tree is static; the daemon starts only after the stop completes.
if (!cloneLockHeld && EnvironmentLock.isHeld(requireContext())) {
Toast.makeText(requireContext(), getString(R.string.k2go_install_busy), Toast.LENGTH_LONG).show();
Toast.makeText(requireContext(), org.iiab.controller.util.BusyMessage.resFor(requireContext()), Toast.LENGTH_LONG).show();
return;
}
daemonStarting = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public static void confirmAndStart(@NonNull Fragment host, @NonNull View anchor,
@Nullable Runnable onLiveUpdated) {
Context ctx = host.requireContext();
if (org.iiab.controller.env.EnvironmentLock.isHeld(ctx)) {
Snackbars.make(anchor, R.string.k2go_install_busy).show();
Snackbars.make(anchor, org.iiab.controller.util.BusyMessage.resFor(ctx)).show();
return;
}
if (!hasInternet(ctx)) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
} else if (org.iiab.controller.env.EnvironmentLock.isHeld(requireContext())) {
// ADFA-4919/4951: proot (Maps) acts on the live system, so it must not overlap ANY
// deep-env op (runrole, download, backup/restore/clone). Refuse and tell the user to wait.
Snackbars.make(v, R.string.k2go_install_busy).show();
Snackbars.make(v, org.iiab.controller.util.BusyMessage.resFor(requireContext())).show();
} else {
// ADFA-4919: route Get More Maps through the install index (gated), same as the
// wizard — banks to MapsWishlist and opens SetupProgressActivity. Replaces the old
Expand Down
Loading
Loading