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
1 change: 1 addition & 0 deletions static/dashboard/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ One line per version, newest first. Every REST-facing change bumps the version i
(the app surfaces it via `/system/dashboard/update-check` and the "Update available" pill), so this
file is the human record of what each bump enables. Keep entries short: `version - change (TICKET)`.

- **1.2.3-dev** - Resilient content downloads (ADFA-4894, Area 1 of the ADFA-4893 contract). A network drop mid-job recovers or fails cleanly instead of failing the whole batch at the first blip: a shared `withRetry` backoff helper; job cancel now aborts an in-flight `fetch` (new `AbortSignal` on the runner), not just child processes; **books** get a per-attempt timeout + per-item retry/backoff and no longer fail a batch on one dropped EPUB; **kiwix** prunes the partial `.zim` + `.aria2` on cancel (clean-on-cancel) and gains aria2 reconnect flags (`--max-tries`/`--retry-wait`/`--timeout`, documented divergence from the app's `--max-tries=1` outer-loop model). kiwix also gets an **outer** reconnect loop (`withRetry` around aria2) so a full Wi-Fi drop — where aria2 exits on DNS (code 19) and can't retry itself — recovers across the handoff, resuming via `--continue`; books' retry budget widened to ~30s to outlast a real reassociation. Maps per-layer checkpoint is pending the on-box `tile-extract.py`. Version stays `1.2.3-dev.N` through the PR (device-verified on -dev.1); final bump to `1.2.3` at merge. (ADFA-4894)
- **1.2.2** - New `GET /kolibri/subtree/:nodeId`: serves a channel's topic tree in Studio's `contentnode_tree` shape, with per-node byte sizes summed from the local content DB over each node's MPTT range, so the app browses an imported channel's whole tree offline (parsed by the same mapper it uses for Studio). Read-only; **404** when the channel's metadata is not imported, which the app reads as "fall back to Studio". Ships the endpoint PR added without a version bump. (ADFA-5094)
- **1.2.1** - Four Kolibri defects found by testing against a real device. `/kolibri/estimate` now reports free space (the call was missing the mandatory `?path=Content` and had been failing silently since it was written) and answers **409** with a readable message for a channel that is not installed, instead of letting Kolibri return a bare 500; `/kolibri/catalog` reports real sizes and resource counts (it was reading Studio's field names on an endpoint that uses Kolibri's); a failed import now carries the cause instead of just the exception class name. Also finishes the English pass: `routes.ts` was the last file the 1.1.6 sweep missed — REST-facing too, since one response string changes (`POST /credentials/kolibri` on 401). (ADFA-4954)
- **1.2.0** - Self-update cutover baseline: no endpoint change, but from this version the app updates the dash-node core **live over REST** (`POST /system/dashboard/rebuild`, the blue-green rebuild from ADFA-5011) instead of a proot rebuild. Installs on < 1.2.0 still use the proot path to reach 1.2.0; 1.2.0+ update to 1.2.1+ via REST. (ADFA-5051)
Expand Down
4 changes: 2 additions & 2 deletions static/dashboard/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions static/dashboard/package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "dashboard-console",
"version": "1.2.2",
"version": "1.2.3-dev.2",
"description": "",
"main": "index.js",
"scripts": {
"test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts sockets/credentials.test.ts",
"test": "node --require ts-node/register --test sockets/maps.socket.test.ts sockets/rolling-log.test.ts sockets/kolibri.session.test.ts sockets/credentials.test.ts sockets/net-retry.test.ts",
"typecheck": "tsc --noEmit",
"build": "tsc",
"start": "node dist/server.js"
Expand Down
84 changes: 66 additions & 18 deletions static/dashboard/sockets/books.exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,25 @@
// the EPUB and upload it to the local Calibre-Web. Ported from the Phase 1 books.socket
// download_books_batch handler (auth/CSRF + fetch + upload), made durable and reporting
// structured per-book progress. A job item is { id, title, url }.
import { jobs, RunnerContext } from './jobs';
import { jobs, RunnerContext, CanceledError } from './jobs';
import { getCredential } from './credentials';
import { withRetry, Aborted } from './net-retry';
import fs from 'fs';
import path from 'path';

// ADFA-4894: a stalled Gutenberg fetch must not hang the job forever, and a transient
// drop must not fail the whole batch at one book. Per-book: bound each attempt with a
// timeout, retry the transient ones with backoff, and make the job's cancel abort an
// in-flight fetch (ctx.signal). A Gutenberg EPUB is a few MB, so a failed attempt is
// re-fetched whole rather than byte-ranged — resume at the item granularity, not the byte.
const FETCH_TIMEOUT_MS = 60_000;
// The retry budget has to outlast a real mobile Wi-Fi drop, not just a sub-second blip: on a
// device, disabling Wi-Fi and re-associating takes several seconds (measured on ADFA-4894).
// 6 tries with 1/2/4/8/15s backoff ≈ a 30s window across the handoff, then the item fails.
const BOOK_TRIES = 6;
const BOOK_RETRY_BASE_MS = 1_000;
const BOOK_RETRY_MAX_MS = 15_000;

const CALIBRE_WEB_LOCAL_URL = 'http://127.0.0.1:8083';
const TMP_DIR = '/tmp/books_downloader/';
const SYSTEM_USER_AGENT = 'K2Go Dashboard/1.0 (https://github.com/appdevforall/KnowledgeToGo)';
Expand Down Expand Up @@ -89,24 +103,58 @@ const booksRunner: (ctx: RunnerContext) => Promise<void> = async (ctx) => {

const tmp = path.join(TMP_DIR, `pg_${id}.epub`);
try {
const response = await fetch(url, {
headers: { 'User-Agent': SYSTEM_USER_AGENT, Accept: 'application/epub+zip' },
});
if (!response.ok) throw new Error(`HTTP ${response.status} from Gutenberg`);

const fileBuffer = await response.arrayBuffer();
fs.writeFileSync(tmp, Buffer.from(fileBuffer));

const form = new FormData();
form.append('csrf_token', session.csrfToken);
form.append('btn-upload', new Blob([fileBuffer], { type: 'application/epub+zip' }), `${title}.epub`);

const uploadRes = await fetch(`${CALIBRE_WEB_LOCAL_URL}/upload`, {
method: 'POST',
headers: { Cookie: session.cookie, Referer: `${CALIBRE_WEB_LOCAL_URL}/` },
body: form,
await withRetry(async () => {
// Cancel (ctx.signal) is terminal; a per-attempt timeout is retryable. Combine both
// for the fetch so a stall aborts, then let withRetry decide whether to try again.
const signal = AbortSignal.any([ctx.signal, AbortSignal.timeout(FETCH_TIMEOUT_MS)]);

const response = await fetch(url, {
headers: { 'User-Agent': SYSTEM_USER_AGENT, Accept: 'application/epub+zip' },
signal,
});
if (!response.ok) {
const e = new Error(`HTTP ${response.status} from Gutenberg`);
(e as { status?: number }).status = response.status;
throw e;
}

const fileBuffer = await response.arrayBuffer();
fs.writeFileSync(tmp, Buffer.from(fileBuffer));

const form = new FormData();
form.append('csrf_token', session.csrfToken);
form.append('btn-upload', new Blob([fileBuffer], { type: 'application/epub+zip' }), `${title}.epub`);

const uploadRes = await fetch(`${CALIBRE_WEB_LOCAL_URL}/upload`, {
method: 'POST',
headers: { Cookie: session.cookie, Referer: `${CALIBRE_WEB_LOCAL_URL}/` },
body: form,
signal,
});
if (!uploadRes.ok) {
const e = new Error(`Calibre-Web rejected upload: ${uploadRes.status}`);
(e as { status?: number }).status = uploadRes.status;
throw e;
}
}, {
tries: BOOK_TRIES,
baseMs: BOOK_RETRY_BASE_MS,
maxMs: BOOK_RETRY_MAX_MS,
signal: ctx.signal,
isCanceled: ctx.isCanceled,
// Retry network drops and timeouts and 5xx; a 4xx is the server's final word.
isTransient: (err) => {
const status = (err as { status?: number })?.status;
if (typeof status === 'number') return status >= 500;
return true;
},
onRetry: ({ attempt, err }) => ctx.log(`[books] retry ${attempt} for "${title}": ${err instanceof Error ? err.message : String(err)}`),
});
if (!uploadRes.ok) throw new Error(`Calibre-Web rejected upload: ${uploadRes.status}`);
} catch (err) {
// withRetry throws Aborted on cancel; surface it as the engine's CanceledError so the
// job lands on 'canceled', not 'error'.
if (err instanceof Aborted || ctx.isCanceled()) throw new CanceledError();
throw err;
} finally {
if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
}
Expand Down
9 changes: 7 additions & 2 deletions static/dashboard/sockets/jobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ export interface RunnerContext {
update(patch: JobUpdate): void;
isCanceled(): boolean;
throwIfCanceled(): void;
/** ADFA-4894: aborted when the job is canceled, so an in-flight fetch (books) can be
* interrupted — a child process is killed via SIGKILL, but a fetch has no process. */
readonly signal: AbortSignal;
/** Spawn a child that is killed automatically on cancel and untracked on exit. */
spawn(cmd: string, args: string[], opts?: SpawnOptions): ChildProcess;
log(line: string): void;
Expand All @@ -68,7 +71,7 @@ const ACTIVE: JobPhase[] = ['queued', 'downloading', 'indexing', 'processing'];
class JobManager {
private db: Database.Database;
private runners = new Map<JobType, Runner>();
private runtime = new Map<string, { canceled: boolean; procs: Set<ChildProcess> }>();
private runtime = new Map<string, { canceled: boolean; procs: Set<ChildProcess>; ac: AbortController }>();
// ADFA-4879: bounded rolling log tail per job for the live-log REST endpoint.
private readonly logTail = new RollingLog();

Expand Down Expand Up @@ -134,6 +137,7 @@ class JobManager {
if (rt) {
rt.canceled = true;
for (const p of rt.procs) { try { p.kill('SIGKILL'); } catch { /* already gone */ } }
try { rt.ac.abort(); } catch { /* ADFA-4894: interrupt an in-flight fetch too */ }
}
if (ACTIVE.includes(job.phase)) this.patch(id, { phase: 'canceled' });
return true;
Expand Down Expand Up @@ -168,7 +172,7 @@ class JobManager {
const runner = this.runners.get(job.type);
if (!runner) { this.patch(job.id, { phase: 'error', error: `no runner for ${job.type}` }); return; }

const rt = { canceled: false, procs: new Set<ChildProcess>() };
const rt = { canceled: false, procs: new Set<ChildProcess>(), ac: new AbortController() };
this.runtime.set(job.id, rt);

let items: unknown[] = [];
Expand All @@ -180,6 +184,7 @@ class JobManager {
update: (p) => this.patch(job.id, p),
isCanceled: () => rt.canceled,
throwIfCanceled: () => { if (rt.canceled) throw new CanceledError(); },
signal: rt.ac.signal,
spawn: (cmd, args, opts) => {
const child = opts ? spawn(cmd, args, opts) : spawn(cmd, args);
rt.procs.add(child);
Expand Down
117 changes: 94 additions & 23 deletions static/dashboard/sockets/kiwix.exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
// kiwix.socket handler, minus the socket/closure lifetime — the job outlives any
// client (see jobs.ts).
import { jobs, RunnerContext, CanceledError } from './jobs';
import { withRetry, Aborted } from './net-retry';
import { execSync } from 'child_process';
import fs from 'fs';
import path from 'path';
Expand All @@ -19,9 +20,17 @@ const SAFE_ID = /^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/;
const INDEXER = '/usr/bin/iiab-make-kiwix-lib';
const SAFETY_BUFFER_BYTES = 5 * 1024 * 1024 * 1024; // keep >=5 GB free

// ADFA-4832 sync note: these aria2 flags mirror the app-side downloader
// (controller/app/.../Aria2Manager.java) and the Phase 1 socket handler. Keep the
// three in sync; if you change one, change the others and document any divergence.
// ADFA-4832 CANONICAL aria2 flag set — mirrored in three places. If you change a flag here,
// change the others and update this note (nothing enforces it; a silent drift is the risk):
// 1. this file (REST/dash-node kiwix runner)
// 2. controller/app/.../Aria2Manager.java (the Android app downloader)
// 3. the Phase 1 socket handler
// Shared intent: --continue, --check-integrity, --max-connection-per-server=4, --split, no
// --lowest-speed-limit. Two DOCUMENTED divergences from the app, both about the retry model:
// - retry count: app uses --max-tries=1 (its outer InstallService loop re-drives); REST uses
// --max-tries=5 so aria2 absorbs in-flight blips itself (see the outer loop below for the
// total-interface-loss case aria2 can't retry).
// - timeouts: app 10s/5s (aggressive, its loop re-drives fast); REST 60s/15s (no fast re-drive).
const ARIA2_ARGS: string[] = [
'-d', ZIMS_DIR,
'--continue=true',
Expand All @@ -35,10 +44,31 @@ const ARIA2_ARGS: string[] = [
'--summary-interval=1',
'--download-result=hide',
'--async-dns=false',
// ADFA-4894: aria2 absorbs in-flight blips itself (retry-wait never 0 — a 0-wait retry hammers a
// struggling server). A FULL interface loss (exit 19, DNS can't resolve) is not something aria2
// retries, so that case is handled by the outer withRetry loop below, not here. See the canonical
// note above for the documented divergence from the app's --max-tries=1 model.
'--max-tries=5',
'--retry-wait=5',
'--timeout=60',
'--connect-timeout=15',
// No --lowest-speed-limit, same as the app: it turns a slow link into a hard abort, which is the
// opposite of resilient on the intermittent 3G this contract exists for.
'-Z',
'-j', '5',
];

// ADFA-4894: the outer reconnect loop for a FULL interface loss. aria2's --max-tries handles
// in-flight blips, but when Wi-Fi drops entirely aria2 exits (19 = name resolution failed) and
// can't retry a name it can't resolve. So we re-run aria2 — which resumes via --continue — on the
// transient exit codes, across a mobile handoff. NOT retried: 3/4 (not found), 9 (no space), 13
// (file exists) — those are terminal. Budget ~30s to outlast a Wi-Fi reassociation.
// 1 unknown · 2 timeout · 6 network · 7 unfinished · 19 DNS · 29 HTTP 503
const ARIA2_TRANSIENT_EXITS = new Set<number>([1, 2, 6, 7, 19, 29]);
const KIWIX_DL_TRIES = 5;
const KIWIX_RETRY_BASE_MS = 2_000;
const KIWIX_RETRY_MAX_MS = 15_000;

/** Convert an aria2 rate token ("34MiB", "512KiB", "1.2MB") to bytes/sec. */
function parseRate(token: string): number {
const m = /^([\d.]+)\s*([KMGT]?i?B)?/i.exec(token);
Expand Down Expand Up @@ -78,6 +108,26 @@ function cleanupMetadata(): void {
} catch { /* non-fatal */ }
}

/**
* ADFA-4894: clean-on-cancel. aria2 keeps a partial `.zim` + `.aria2` control file so a resume can
* continue — right after a pause, wrong after a cancel, where the user gave the download up. So on
* cancel we prune each requested file's partial and its control/metadata siblings, leaving nothing
* half-written. A file with no `.aria2` is treated as already complete and left alone.
*/
function cleanupPartials(files: string[]): void {
for (const f of files) {
try {
const control = path.join(ZIMS_DIR, `${f}.aria2`);
if (!fs.existsSync(control)) continue; // no control file -> complete, don't delete it
fs.unlinkSync(control);
for (const sibling of [f, `${f}.meta4`, `${f}.torrent`]) {
const p = path.join(ZIMS_DIR, sibling);
if (fs.existsSync(p)) fs.unlinkSync(p);
}
} catch { /* best-effort */ }
}
}

const kiwixRunner: (ctx: RunnerContext) => Promise<void> = async (ctx) => {
// ADFA-5042: keep each id's project subdir for the URL; use basename only for the local file/display.
const ids = ctx.ids.map(String).map((z) => z.replace(/^\/+/, '')).filter((z) => z.endsWith('.zim'));
Expand All @@ -98,27 +148,48 @@ const kiwixRunner: (ctx: RunnerContext) => Promise<void> = async (ctx) => {
// Each id already carries its project subdir on the mirror (/zim/<project>/<file>).
const urls = ids.map((z) => BASE_URL + z);

await new Promise<void>((resolve, reject) => {
const dl = ctx.spawn('/usr/bin/aria2c', [...ARIA2_ARGS, ...urls]);
const onData = (buf: Buffer) => {
const text = buf.toString();
// A single chunk can carry several summary lines; take the LAST %/rate.
const re = /\((\d+)%\).*?DL:([^\s]+)/g;
let m: RegExpExecArray | null;
let lastPct = -1;
let lastRate = '';
while ((m = re.exec(text)) !== null) { lastPct = parseInt(m[1], 10); lastRate = m[2]; }
if (lastPct >= 0) ctx.update({ phase: 'downloading', percent: lastPct, speed: parseRate(lastRate) });
};
dl.stdout?.on('data', onData);
dl.stderr?.on('data', onData);
dl.on('error', reject);
dl.on('exit', (code, signal) => {
if (signal === 'SIGKILL' || ctx.isCanceled()) return reject(new CanceledError());
if (code === 0) resolve();
else reject(new Error(`aria2 exited with code ${code}`));
try {
await withRetry(() => new Promise<void>((resolve, reject) => {
const dl = ctx.spawn('/usr/bin/aria2c', [...ARIA2_ARGS, ...urls]);
const onData = (buf: Buffer) => {
const text = buf.toString();
// A single chunk can carry several summary lines; take the LAST %/rate.
const re = /\((\d+)%\).*?DL:([^\s]+)/g;
let m: RegExpExecArray | null;
let lastPct = -1;
let lastRate = '';
while ((m = re.exec(text)) !== null) { lastPct = parseInt(m[1], 10); lastRate = m[2]; }
if (lastPct >= 0) ctx.update({ phase: 'downloading', percent: lastPct, speed: parseRate(lastRate) });
};
dl.stdout?.on('data', onData);
dl.stderr?.on('data', onData);
dl.on('error', reject);
dl.on('exit', (code, signal) => {
if (signal === 'SIGKILL' || ctx.isCanceled()) return reject(new CanceledError());
if (code === 0) return resolve();
// Carry the aria2 exit code so the outer loop can tell a transient network failure
// (retry, resuming via --continue) from a terminal one (not found / no space).
const err = new Error(`aria2 exited with code ${code}`);
(err as { code?: number }).code = code ?? -1;
reject(err);
});
}), {
tries: KIWIX_DL_TRIES,
baseMs: KIWIX_RETRY_BASE_MS,
maxMs: KIWIX_RETRY_MAX_MS,
isCanceled: ctx.isCanceled,
isTransient: (e) => ARIA2_TRANSIENT_EXITS.has((e as { code?: number }).code ?? -1),
onRetry: ({ attempt, err }) => ctx.log(`[kiwix] reconnect attempt ${attempt} after: ${err instanceof Error ? err.message : String(err)}`),
});
});
} catch (e) {
// ADFA-4894: a canceled download leaves nothing half-written; a real error KEEPS the partial
// (+ .aria2) so a later run resumes it via --continue rather than starting from zero.
if (e instanceof CanceledError || e instanceof Aborted || ctx.isCanceled()) {
cleanupPartials(files);
throw new CanceledError();
}
throw e;
}

cleanupMetadata();
ctx.throwIfCanceled();
Expand Down
Loading
Loading