diff --git a/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java b/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java index a7cf0ead6..abb7f3960 100644 --- a/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java +++ b/controller/app/src/main/java/org/iiab/controller/content/RestContentClient.java @@ -10,12 +10,17 @@ * job and then POLLs its structured status every ~1s. The job lives in * the dashboard process (durable, resumable), so there is no connection * to lose — the app can drop and re-attach by polling the same jobId. + * ADFA-4897: start() acts as start-or-attach — before creating a job it + * checks GET /:type/jobs for an ACTIVE job with the same target ids and, + * if found, polls that one instead, so a queue re-drained after process + * death re-attaches to the in-flight download rather than duplicating it. * Still driven by the foreground InstallService so polling continues * across UI/config changes. * * Contract (static/dashboard/routes.ts + sockets/jobs.ts), per content * ("kiwix", "books", ...) — ADFA-4893 made this client type-parametric: * POST /api//download -> { id, ... } + * GET /api//jobs -> [ { id, ids, phase, ... }, ... ] * GET /api//jobs/:id -> { phase, percent, speed(bytes/s), * detail, error, retryAttempt, retryTotal } * POST /api//jobs/:id/{cancel,pause,resume} -> { ok:true } @@ -95,6 +100,18 @@ public void addZim(@NonNull String zimFilename, @NonNull Listener l) { public void start(@NonNull JSONObject body, @NonNull Listener l) { this.listener = l; AppExecutors.get().io().execute(() -> { + // ADFA-4897: re-attach instead of re-POST. The server job engine is durable (jobs.db + + // reconcileOnBoot), so a job we started before a process death survives. Before creating a + // new job, look for an ACTIVE one whose target ids match this body's items and, if found, + // just poll it — so a relaunched queue re-attaches to the in-flight download instead of + // starting a duplicate. Any error here falls through to a normal fresh POST. + String existing = findActiveJob(body); + if (finished) return; // a cancel landed during the lookup + if (existing != null) { + jobId = existing; + main.postDelayed(pollTask, POLL_MS); + return; + } // ADFA-4893: retry ONLY the kickoff POST (connectivity blip / server still warming) a few // times. An empty id is a server refusal, not a blip, so it fails without retrying. Once the // job exists, the server owns reconnection (visible), not this loop. @@ -233,6 +250,76 @@ private static String formatRate(long bps) { : String.format(java.util.Locale.US, "%.1f %s", v, units[i]); } + /** ADFA-4897: id of an ACTIVE server job whose target ids intersect this body's item ids, or null + * if none / on any error (so a fresh start just POSTs a new job). */ + private String findActiveJob(JSONObject body) { + try { + java.util.Set want = idsFromBody(body); + if (want.isEmpty()) return null; + JSONArray list = httpArray("GET", base + "/jobs"); + for (int i = 0; i < list.length(); i++) { + JSONObject job = list.optJSONObject(i); + if (job == null || !isActivePhase(job.optString("phase", ""))) continue; + java.util.Set have = idsFromJob(job); + for (String id : want) if (have.contains(id)) { + String jid = job.optString("id", ""); + if (!jid.isEmpty()) return jid; + } + } + } catch (Exception ignore) { /* fall through to a fresh POST */ } + return null; + } + + /** Item ids in a start body: kiwix {ids:[..]} (strings), books {items:[{id,..}]} (objects). */ + private static java.util.Set idsFromBody(JSONObject body) { + java.util.Set out = new java.util.HashSet<>(); + JSONArray ids = body.optJSONArray("ids"); + if (ids != null) for (int i = 0; i < ids.length(); i++) { + String s = ids.optString(i, ""); if (!s.isEmpty()) out.add(s); + } + JSONArray items = body.optJSONArray("items"); + if (items != null) for (int i = 0; i < items.length(); i++) { + JSONObject o = items.optJSONObject(i); + if (o != null) { String s = o.optString("id", ""); if (!s.isEmpty()) out.add(s); } + } + return out; + } + + /** Item ids in a job's target (toApi 'ids'): kiwix elements are strings, books elements are objects. */ + private static java.util.Set idsFromJob(JSONObject job) { + java.util.Set out = new java.util.HashSet<>(); + JSONArray arr = job.optJSONArray("ids"); + if (arr != null) for (int i = 0; i < arr.length(); i++) { + Object el = arr.opt(i); + if (el instanceof JSONObject) { String s = ((JSONObject) el).optString("id", ""); if (!s.isEmpty()) out.add(s); } + else if (el != null) { String s = String.valueOf(el); if (!s.isEmpty()) out.add(s); } + } + return out; + } + + /** Non-terminal phase — worth attaching to (queued/downloading/indexing/processing/paused). */ + private static boolean isActivePhase(String phase) { + return !("done".equals(phase) || "error".equals(phase) || "canceled".equals(phase)); + } + + private static JSONArray httpArray(String method, String urlStr) throws Exception { + HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection(); + try { + c.setUseCaches(false); + c.setConnectTimeout(4000); + c.setReadTimeout(4000); + c.setRequestMethod(method); + c.setRequestProperty("Accept", "application/json"); + int code = c.getResponseCode(); + boolean ok = code >= 200 && code < 400; + String text = readAll(ok ? c.getInputStream() : c.getErrorStream()); + if (!ok) throw new Exception("HTTP " + code + ": " + text); + return new JSONArray(text.isEmpty() ? "[]" : text); + } finally { + c.disconnect(); + } + } + private static JSONObject httpJson(String method, String urlStr, JSONObject body) throws Exception { HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection(); try { diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java index 32d1c2038..0b53147b0 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/BooksDownloadService.java @@ -110,7 +110,13 @@ public int onStartCommand(Intent intent, int flags, int startId) { SESSION.attach(this); String action = intent != null ? intent.getAction() : null; - if (ACTION_CANCEL.equals(action)) { SESSION.cancelAndPurge(); return START_NOT_STICKY; } + if (ACTION_CANCEL.equals(action)) { + // ADFA-4897: Cancel abandons the order -> drop the remaining wishlist (DONE books were + // already removed one by one via onItemDone) so a later drain does not re-add them. + BooksWishlist.clear(getApplicationContext()); + SESSION.cancelAndPurge(); + return START_NOT_STICKY; + } if (ACTION_PAUSE.equals(action)) { SESSION.pauseActive(); return START_NOT_STICKY; } if (ACTION_RESUME.equals(action)) { SESSION.resumeActive(); return START_NOT_STICKY; } @@ -135,7 +141,8 @@ public int onStartCommand(Intent intent, int flags, int startId) { } catch (Exception e) { bodies[i] = new JSONObject(); } } startForeground(NOTIFICATION_ID, buildNotification(titles.length > 0 ? titles[0] : "")); - SESSION.begin(titles, null, bodies); // books: no per-item byte size -> count-based percent + // keys = ids: the book id is both the download id and the wishlist key (ADFA-4897). + SESSION.begin(ids, titles, null, bodies); // books: no per-item byte size -> count-based percent } return START_NOT_STICKY; } @@ -149,6 +156,11 @@ public int onStartCommand(Intent intent, int flags, int startId) { @Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); } + /** ADFA-4897: book confirmed added to the library -> drop it from the durable wishlist. */ + @Override public void onItemDone(String key) { + if (key != null && !key.isEmpty()) BooksWishlist.remove(getApplicationContext(), key); + } + private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel ch = new NotificationChannel( diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/BooksProvisioner.java b/controller/app/src/main/java/org/iiab/controller/redesign/BooksProvisioner.java index c787bc7b2..7b9590014 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/BooksProvisioner.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/BooksProvisioner.java @@ -8,8 +8,9 @@ * order to the existing BooksDownloadService — the same foreground, one-at-a-time, * per-item-retry engine used by Get More — so provisioning is seamless and needs no * new download machinery. Books is a LIVE operation (server up), so this must only be - * called when the server is alive. Idempotent: the wishlist is cleared once handed - * off (the service then owns retry), so it won't re-drain. + * called when the server is alive. ADFA-4897: the wishlist is NOT cleared at hand-off; + * the service drops each entry only once its book is confirmed added, so a process death + * re-drains only what did not finish. Re-entrant: a running session short-circuits drain(). * ============================================================================ */ package org.iiab.controller.redesign; @@ -67,11 +68,10 @@ public static void drain(Context ctx) { } if (ids.isEmpty()) { BooksWishlist.clear(ctx); return; } Log.i(TAG, "books drain: handing " + ids.size() + " to BooksDownloadService"); + // ADFA-4897: do NOT clear the wishlist here. The service drops each book from the wishlist only + // when it is confirmed added (BooksDownloadService.onItemDone), and clears the rest on an + // explicit Cancel — so a process death leaves the not-done books banked for the next drain. BooksDownloadService.start(ctx.getApplicationContext(), ids.toArray(new String[0]), titles.toArray(new String[0]), urls.toArray(new String[0])); - // TODO(ADFA-4874): clearing here means that if the process dies mid-download both the - // wishlist and the service's in-memory state are lost (orphaned partial). The durable - // background-jobs monitor should own this hand-off so it survives process death. - BooksWishlist.clear(ctx); // handed off; the service owns retry from here } } diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java index af0d4a1ae..ed2c7d753 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ContentDownloadSession.java @@ -38,6 +38,7 @@ public interface Listener { void onUpdate(); } public interface Host { void notify(String label); // update the foreground notification for the current item void stop(); // stopForeground(true) + stopSelf() + void onItemDone(String key); // item confirmed DONE -> drop its wishlist entry (ADFA-4897) } private final String type; // "kiwix" / "books" -> /api/ @@ -55,7 +56,10 @@ public interface Host { private int[] status = new int[0]; // Per-item snapshot — same length as status by construction (set together in begin(), cleared // together in purge()). bodies[i] is the REST start request for item i (kiwix {ids:[..]}, books - // {items:[..]}); sizes[i] is the byte weight (0 for books -> count-based percent). + // {items:[..]}); sizes[i] is the byte weight (0 for books -> count-based percent); keys[i] is the + // owning wishlist key, so the service can drop the entry the moment item i is confirmed DONE + // (ADFA-4897 — the wishlist is the durable order, kept until each item completes). + private String[] keys = new String[0]; private String[] labels = new String[0]; private long[] sizes = new long[0]; private JSONObject[] bodies = new JSONObject[0]; @@ -82,6 +86,7 @@ public interface Host { public long[] sizes() { return sizes; } public String label(int i) { return i >= 0 && i < labels.length ? labels[i] : ""; } public long size(int i) { return i >= 0 && i < sizes.length ? sizes[i] : 0L; } + public String key(int i) { return i >= 0 && i < keys.length ? keys[i] : ""; } public boolean hasSession() { return status.length > 0; } public boolean isComplete() { if (status.length == 0 || running) return false; @@ -124,8 +129,9 @@ else if (i == index && (status[i] == ACTIVE || status[i] == PROCESSING) && perce /** Fresh session over the given items (status all PENDING), then start pumping the queue. The * labels/sizes/bodies snapshot is held here so it stays the same length as status for the whole * session — the service passes it in and never keeps its own copy. */ - public void begin(String[] labels, long[] sizes, JSONObject[] bodies) { + public void begin(String[] keys, String[] labels, long[] sizes, JSONObject[] bodies) { int count = labels != null ? labels.length : 0; + this.keys = keys != null && keys.length == count ? keys : new String[count]; this.labels = labels != null ? labels : new String[0]; this.sizes = sizes != null && sizes.length == count ? sizes : new long[count]; this.bodies = bodies != null && bodies.length == count ? bodies : new JSONObject[count]; @@ -174,7 +180,7 @@ public void cancelAndPurge() { * never read a length mismatch after a Cancel (ADFA-4893). */ public void purge() { status = new int[0]; - labels = new String[0]; sizes = new long[0]; bodies = new JSONObject[0]; + keys = new String[0]; labels = new String[0]; sizes = new long[0]; bodies = new JSONObject[0]; index = 0; percent = 0; speed = 0; running = false; paused = false; reconnectAttempt = 0; reconnectTotal = 0; lastProgressAt = 0L; @@ -218,7 +224,14 @@ private void startItem(final int i) { lastProgressAt = SystemClock.elapsedRealtime(); publish(); } @Override public void onLog(String line) { /* logcat only */ } - @Override public void onDone() { status[i] = DONE; publish(); pump(); } + @Override public void onDone() { + status[i] = DONE; publish(); + // ADFA-4897: item confirmed done -> drop its wishlist entry, so a later process death + // only re-drains what actually did NOT finish (no re-download of completed items). + String k = key(i); + if (host != null && !k.isEmpty()) host.onItemDone(k); + pump(); + } @Override public void onError(String message) { // ADFA-4893: server owns reconnection (visible); on give-up, FAILED for a manual Retry. android.util.Log.w("K2Go-Provision", "[" + type + "] job [" + i + "] error: " + message); diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java b/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java index 512560995..7acc646a1 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ZimDownloadService.java @@ -45,6 +45,7 @@ public final class ZimDownloadService extends Service implements ContentDownload public static final String EXTRA_FILES = "files"; public static final String EXTRA_LABELS = "labels"; public static final String EXTRA_BYTES = "bytes"; + public static final String EXTRA_KEYS = "keys"; // ADFA-4897: wishlist keys, one per file // Per-item status — same values the UI/checklist already use, sourced from the shared session. public static final int PENDING = ContentDownloadSession.PENDING; @@ -78,9 +79,10 @@ public interface Listener { void onUpdate(); } public static long[] bytes() { return SESSION.sizes(); } public static void setListener(Listener l) { SESSION.setListener(l == null ? null : l::onUpdate); } - public static void start(Context ctx, String[] files, String[] labels, long[] bytes) { + public static void start(Context ctx, String[] keys, String[] files, String[] labels, long[] bytes) { Intent i = new Intent(ctx, ZimDownloadService.class).setAction(ACTION_START) - .putExtra(EXTRA_FILES, files).putExtra(EXTRA_LABELS, labels).putExtra(EXTRA_BYTES, bytes); + .putExtra(EXTRA_KEYS, keys).putExtra(EXTRA_FILES, files) + .putExtra(EXTRA_LABELS, labels).putExtra(EXTRA_BYTES, bytes); ContextCompat.startForegroundService(ctx, i); } @@ -112,7 +114,13 @@ public int onStartCommand(Intent intent, int flags, int startId) { SESSION.attach(this); String action = intent != null ? intent.getAction() : null; - if (ACTION_CANCEL.equals(action)) { SESSION.cancelAndPurge(); return START_NOT_STICKY; } + if (ACTION_CANCEL.equals(action)) { + // ADFA-4897: Cancel abandons the order -> drop the remaining wishlist so a later drain does + // not re-download it (DONE items were already removed one by one via onItemDone). + ZimWishlist.clear(getApplicationContext()); + SESSION.cancelAndPurge(); + return START_NOT_STICKY; + } if (ACTION_PAUSE.equals(action)) { SESSION.pauseActive(); return START_NOT_STICKY; } if (ACTION_RESUME.equals(action)) { SESSION.resumeActive(); return START_NOT_STICKY; } @@ -127,6 +135,7 @@ public int onStartCommand(Intent intent, int flags, int startId) { if (files == null || files.length == 0) { stopSelf(); return START_NOT_STICKY; } String[] labels = intent.getStringArrayExtra(EXTRA_LABELS); long[] bytes = intent.getLongArrayExtra(EXTRA_BYTES); + String[] keys = intent.getStringArrayExtra(EXTRA_KEYS); if (labels == null) labels = files; JSONObject[] bodies = new JSONObject[files.length]; for (int i = 0; i < files.length; i++) { @@ -134,7 +143,7 @@ public int onStartCommand(Intent intent, int flags, int startId) { catch (Exception e) { bodies[i] = new JSONObject(); } } startForeground(NOTIFICATION_ID, buildNotification(labels.length > 0 ? labels[0] : "")); - SESSION.begin(labels, bytes, bodies); // session owns the snapshot from here on + SESSION.begin(keys, labels, bytes, bodies); // session owns the snapshot from here on } return START_NOT_STICKY; } @@ -148,6 +157,12 @@ public int onStartCommand(Intent intent, int flags, int startId) { @Override public void stop() { main.post(() -> { stopForeground(true); stopSelf(); }); } + /** ADFA-4897: item confirmed downloaded -> drop it from the durable wishlist, so a process death + * after this point never re-downloads it. */ + @Override public void onItemDone(String key) { + if (key != null && !key.isEmpty()) ZimWishlist.remove(getApplicationContext(), key); + } + private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/ZimProvisioner.java b/controller/app/src/main/java/org/iiab/controller/redesign/ZimProvisioner.java index ebb7c1fed..2b6e32c54 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/ZimProvisioner.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/ZimProvisioner.java @@ -9,7 +9,9 @@ * (kiwix_catalog.csv, via KiwixCatalog) into a real ZIM file + label + size, then * hands them to the existing ZimDownloadService (the live REST route, foreground, * per-item retry). ZIM is a LIVE operation (server up), so this must only run when - * the server is alive. Idempotent: the wishlist is cleared once handed off. + * the server is alive. ADFA-4897: the wishlist is NOT cleared at hand-off; the service + * drops each entry only once its item is confirmed done, so a process death re-drains + * only what did not finish. Re-entrant: a running session short-circuits drain(). * ============================================================================ */ package org.iiab.controller.redesign; @@ -66,13 +68,15 @@ public static void drain(Context ctx) { private static void resolveAndStart(Context app, JSONObject catalog) { JSONArray order = ZimWishlist.all(app); - List files = new ArrayList<>(), labels = new ArrayList<>(); + List keys = new ArrayList<>(), files = new ArrayList<>(), labels = new ArrayList<>(); List bytes = new ArrayList<>(); for (int i = 0; i < order.length(); i++) { JSONObject o = order.optJSONObject(i); if (o == null) continue; - ZimSelection.Item it = ZimSelection.resolve(catalog, o.optString("key", "")); + String key = o.optString("key", ""); + ZimSelection.Item it = ZimSelection.resolve(catalog, key); if (it == null) continue; + keys.add(key); // wishlist key ("project|lang|flavour") — dropped per-item once done files.add(it.id); // "/" (ADFA-5042) labels.add(ZimItemLabel.of(it.project, it.entry.optString("creator"), it.entry.optString("flavour"))); @@ -82,11 +86,12 @@ private static void resolveAndStart(Context app, JSONObject catalog) { long[] b = new long[bytes.size()]; for (int i = 0; i < b.length; i++) b[i] = bytes.get(i); Log.i(TAG, "zim drain: handing " + files.size() + " to ZimDownloadService"); - ZimDownloadService.start(app, files.toArray(new String[0]), labels.toArray(new String[0]), b); - // TODO(ADFA-4874): clearing here means that if the process dies mid-download both the - // wishlist and the service's in-memory state are lost (orphaned partial). The durable - // background-jobs monitor should own this hand-off so it survives process death. - ZimWishlist.clear(app); // handed off; the service owns retry from here + // ADFA-4897: do NOT clear the wishlist here. The service now drops each item from the wishlist + // only when it is confirmed DONE (ZimDownloadService.onItemDone), and clears the rest on an + // explicit Cancel. So a process death mid-download leaves exactly the not-done items banked, + // and the next drain re-hands them off — no orphaned partial, no re-download of finished items. + ZimDownloadService.start(app, keys.toArray(new String[0]), files.toArray(new String[0]), + labels.toArray(new String[0]), b); } // ADFA-5074: a private label() lived here and a different one lived in the Get More path, so