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
20 changes: 20 additions & 0 deletions iiab-android
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,14 @@ else
log "Not Full tier: Code on the Go build assets left off."
;;
esac

# K2GO-427: the cx_core role (content-exchange core) ships as an overlay with no
# 6-generic-apps include, so the main install does not run it; it runs on demand via
# runrole (the post-install step below does the bake-time install). Enabled on every
# tier: a tiny Python stdlib service, not a heavy mirror, and no internet needed.
sed -i -E '/^[[:space:]]*cx_core_(install|enabled)[[:space:]]*:/d' "$LOCAL_VARS_DEST"
echo "cx_core_install: True" >> "$LOCAL_VARS_DEST"
echo "cx_core_enabled: True" >> "$LOCAL_VARS_DEST"
fi

#-----------------------------
Expand Down Expand Up @@ -843,6 +851,18 @@ install_welcome_zim
# Install dashboard
install_iiaboa_dashboard

#-----------------------------
# K2GO-427: install and start the content-exchange core (cx-core) via its role. The cx_core
# role ships as an overlay with no 6-generic-apps include, so the main install does not run it;
# run it here via runrole (the same path the app uses for on-demand installs). The role copies
# the source, registers the PDSM service (proot) and writes the IIAB flags. Pure Python stdlib,
# no internet needed. Non-fatal: a failure leaves the box without cx-core but does not fail the bake.
#-----------------------------
if is_role_enabled cx_core; then
log "Installing the content-exchange core (runrole cx_core)..."
( cd /opt/iiab/iiab && ./runrole cx_core ) || warn "cx_core runrole failed; box will lack the content-exchange core"
fi

#-----------------------------
# Reclaim disk: drop downloaded .deb archives
#-----------------------------
Expand Down
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.4.5** - Relay to the content-exchange core (cx-core). dash-node now forwards `/v1/*` (reached externally at `/k2go-api/v1/*`) to the in-box cx-core REST service on `127.0.0.1:9500`: GET and POST, including the streamed `GET /v1/export/item`. dash-node only relays; the core owns the content state (one owner per fact). No proxy library (Node core `http`); the core's port is env-overridable via `CX_PORT`. Localhost-only. (K2GO-427)
- **1.4.4** - Overall progress + total ETA for the content download jobs (K2GO-503). `downloadWithAria2` now aggregates progress across the WHOLE job through aria2's RPC (piece-accurate `completedLength` summed over tellActive/Waiting/Stopped) instead of reporting the last file's percent, so a multi-file download (code-addons / code-assets) shows one monotonic bar. `GET /:type/jobs/:id` gains an `eta` field (whole-job seconds remaining, -1 unknown) alongside `percent`/`speed`. The code-addons runner passes its staged-catalog total as the denominator so the bar and ETA are accurate from the first tick; code-assets uses aria2's learned totals. aria2 is started with `--enable-rpc` on an ephemeral localhost port and shut down on queue drain (it does not exit on its own under RPC); the console readout stays as the fallback when RPC is unreachable, and pause/cancel still kill the process directly. Localhost-only. (K2GO-503)
- **1.4.3** - The offline Kolibri subtree reports each topic's size as its DISTINCT files (`subtree_bytes`), measured over the whole range. A file used by several topics counted once per topic before, which inflated folders 1.2x-1.7x; a truncated subtree now also has exact folder sizes. Same rule as the catalog generator. (K2GO-476)
- **1.4.2** - A Kolibri job waits for Kolibri to come up (up to 10 min) instead of failing at once when Kolibri is unreachable. After a box restart the engine relaunches the job while Kolibri is still starting, so the job, and the app that re-attaches to it, no longer fail and lose the order. A Kolibri that answers 5xx while starting now counts as not reachable yet, not as a protocol error. (K2GO-475)
Expand Down
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.4.4",
"version": "1.4.5",
"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 sockets/net-retry.test.ts sockets/services.test.ts sockets/log-rotate.test.ts sockets/rebuild-status.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 sockets/services.test.ts sockets/log-rotate.test.ts sockets/rebuild-status.test.ts sockets/cx-proxy.test.ts",
"test:db": "node --require ts-node/register --test sockets/jobs.test.ts",
"typecheck": "tsc --noEmit",
"build": "tsc",
Expand Down
6 changes: 6 additions & 0 deletions static/dashboard/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
import { isRestartableService, restartService } from './sockets/services';
import { getFirehoseState } from './sockets/log-rotate';
import { resolveRebuildState } from './sockets/rebuild-status';
import { cxProxy } from './sockets/cx-proxy';

// ADFA-4879: FQR helpers reached from the app (in-app region download/delete instead of the
// copy-paste-into-a-terminal flow). tile-extract.py is installed on the box by the upstream maps
Expand Down Expand Up @@ -72,6 +73,11 @@ function toApi(job: Job) {

export const apiRouter: Router = express.Router();

// --- Content-exchange core (cx-core) relay -------------------------------------------------
// K2GO-427. Forward /v1/* to the in-box cx-core service (127.0.0.1:9500). Reached externally
// at /k2go-api/v1/*. dash-node only relays; the core owns the content state (ADR D1b).
apiRouter.use('/v1', cxProxy);

// --- Books: direct (non-job) queries over the offline catalog + Calibre-Web library ---------
// ADFA-4850. Ported from the socket.io handlers; the download itself stays a durable job
// (POST /books/download). These paths don't collide with the generic /:type/* routes below.
Expand Down
141 changes: 141 additions & 0 deletions static/dashboard/sockets/cx-proxy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/// <reference types="node" />
import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'http';
import express from 'express';
import { cxProxy } from './cx-proxy';

// End-to-end over real sockets: a stub "core" plus a dash-node app mounting the proxy at
// '/v1', exactly as routes.ts does. This catches path, method, body and streaming relay
// (the pieces a mock would not).

function listen(server: http.Server): Promise<number> {
return new Promise((resolve) => server.listen(0, '127.0.0.1', () => {
resolve((server.address() as import('net').AddressInfo).port);
}));
}

// A minimal HTTP client that returns status, headers and the raw body.
function get(port: number, path: string, method = 'GET', body?: string): Promise<{ status: number; body: string; headers: http.IncomingHttpHeaders }> {
return new Promise((resolve, reject) => {
const req = http.request({ host: '127.0.0.1', port, path, method,
headers: body ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) } : {} },
(res) => {
let data = '';
res.on('data', (c) => { data += c; });
res.on('end', () => resolve({ status: res.statusCode || 0, body: data, headers: res.headers }));
});
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}

// Build the dash-node side: express.json() then the proxy at '/v1', mirroring server.ts.
async function startProxyApp(): Promise<{ port: number; close: () => void }> {
const app = express();
app.use(express.json());
app.use('/v1', cxProxy);
const server = http.createServer(app);
const port = await listen(server);
return { port, close: () => server.close() };
}

test('cxProxy relays a GET with path + query and the core status/body', async () => {
const core = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ seen: req.url, method: req.method }));
});
const corePort = await listen(core);
process.env.CX_PORT = String(corePort);
const app = await startProxyApp();
try {
const r = await get(app.port, '/v1/content?app=kiwix');
assert.equal(r.status, 200);
const j = JSON.parse(r.body);
// The core must see the full /v1 path and the query, not the mount-stripped path.
assert.equal(j.seen, '/v1/content?app=kiwix');
assert.equal(j.method, 'GET');
} finally {
app.close(); core.close();
}
});

test('cxProxy forwards a POST JSON body to the core', async () => {
const core = http.createServer((req, res) => {
let data = '';
req.on('data', (c) => { data += c; });
req.on('end', () => {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ echo: JSON.parse(data || '{}'), path: req.url }));
});
});
const corePort = await listen(core);
process.env.CX_PORT = String(corePort);
const app = await startProxyApp();
try {
const r = await get(app.port, '/v1/export/plan', 'POST', JSON.stringify({ items: ['a', 'b'] }));
assert.equal(r.status, 200);
const j = JSON.parse(r.body);
assert.deepEqual(j.echo, { items: ['a', 'b'] });
assert.equal(j.path, '/v1/export/plan');
} finally {
app.close(); core.close();
}
});

test('cxProxy streams a chunked response intact (the export path)', async () => {
const payload = 'Z'.repeat(50000); // bigger than one write block
const core = http.createServer((req, res) => {
res.writeHead(200, { 'content-type': 'application/octet-stream' }); // no content-length -> chunked
res.write(payload.slice(0, 25000));
res.write(payload.slice(25000));
res.end();
});
const corePort = await listen(core);
process.env.CX_PORT = String(corePort);
const app = await startProxyApp();
try {
const r = await get(app.port, '/v1/export/item/kiwix/foo.zim');
assert.equal(r.status, 200);
assert.equal(r.body.length, payload.length);
assert.equal(r.body, payload);
} finally {
app.close(); core.close();
}
});

test('cxProxy passes Content-Disposition through (the export filename)', async () => {
const core = http.createServer((req, res) => {
res.writeHead(200, {
'content-type': 'application/octet-stream',
'content-disposition': 'attachment; filename="foo.zim"',
});
res.end('zim-bytes');
});
const corePort = await listen(core);
process.env.CX_PORT = String(corePort);
const app = await startProxyApp();
try {
const r = await get(app.port, '/v1/export/item/kiwix/foo.zim');
assert.equal(r.status, 200);
assert.equal(r.headers['content-disposition'], 'attachment; filename="foo.zim"');
} finally {
app.close(); core.close();
}
});

test('cxProxy returns 502 when the core is unreachable', async () => {
// Point at a port with nothing listening.
const dead = http.createServer();
const deadPort = await listen(dead);
dead.close();
process.env.CX_PORT = String(deadPort);
const app = await startProxyApp();
try {
const r = await get(app.port, '/v1/apps');
assert.equal(r.status, 502);
} finally {
app.close();
}
});
61 changes: 61 additions & 0 deletions static/dashboard/sockets/cx-proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// cx-proxy.ts - K2GO-427
//
// Thin relay from dash-node to the content-exchange core (cx-core), a separate in-box
// REST service on 127.0.0.1:9500. The app reaches dash-node (its BFF); dash-node forwards
// /v1/* to the core and streams the answer back. dash-node is a relay here, NOT a second
// brain: it owns none of the content state (one owner per fact, ADR Decision 1 / D1b). No
// proxy library: Node's core http is enough for a localhost passthrough.
import { Request, Response } from 'express';
import http from 'http';

const CX_HOST = '127.0.0.1';

// The core's port, env-overridable to match its own CX_PORT default (9500).
function cxPort(): number {
return Number(process.env.CX_PORT) || 9500;
}

// Forward one request to the core and pipe the response back. Mounted at '/v1', so req.url
// is the path after it (e.g. '/apps', '/export/item/kiwix/foo.zim?x=1'), query included.
// The streaming endpoint (GET /v1/export/item) returns chunked; piping handles it.
export function cxProxy(req: Request, res: Response): void {
const corePath = '/v1' + req.url;

// express.json() already parsed any JSON body upstream of this handler, so re-serialize
// it. The cx-core contract carries only small JSON bodies (export/plan, import/validate,
// import/item with a payloadPath); item payloads never pass through dash-node.
const isWrite = req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH';
const hasBody = isWrite && req.body && Object.keys(req.body).length > 0;
const payload = hasBody ? Buffer.from(JSON.stringify(req.body)) : null;

const headers: Record<string, string> = {};
if (payload) {
headers['content-type'] = 'application/json';
headers['content-length'] = String(payload.length);
}

const upstream = http.request(
{ host: CX_HOST, port: cxPort(), method: req.method, path: corePath, headers },
(up) => {
res.status(up.statusCode || 502);
// Pass through the headers the client needs: content type, the download filename
// (GET /v1/export/item sets Content-Disposition), and the length when the core knows
// it. A streamed (chunked) export has no content-length, so Node frames it as chunked.
const ct = up.headers['content-type'];
if (ct) res.setHeader('content-type', ct);
const cd = up.headers['content-disposition'];
if (cd) res.setHeader('content-disposition', cd);
const cl = up.headers['content-length'];
if (cl) res.setHeader('content-length', cl);
up.pipe(res);
},
);

upstream.on('error', () => {
if (!res.headersSent) res.status(502).json({ error: 'cx-core unreachable' });
else res.end();
});

if (payload) upstream.write(payload);
upstream.end();
}
108 changes: 108 additions & 0 deletions static/pdsm/cx-core
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#!/bin/sh
# /usr/local/pdsm/services-available/cx-core
# PDSM service wrapper for the content-exchange core (Python stdlib REST service).
# K2GO-427: run `python3 -m cx_core` from the install dir, with a respawn supervisor
# and a health probe. Same shape as the dash-node wrapper; the core is identical on
# every environment, only the supervisor differs (pdsm here, systemd on IIAB).

PDSM_COMMON="/usr/local/pdsm/lib/pdsm-common.sh"
[ -r "$PDSM_COMMON" ] && . "$PDSM_COMMON"

SERVICE_NAME="cx-core"
APP_DIR="/opt/cx-core"
# The port the health probe and the service agree on. The service reads CX_PORT from
# the environment (default 9500); keep this one value so the probe cannot drift.
CX_PORT="${CX_PORT:-9500}"
export CX_PORT
LOGFILE="/var/log/cx-core.log"
SUP_PIDFILE="/var/run/cx-core.sup.pid"

running() {
# Liveness-approximate: this also matches the supervisor shell, not only the server.
# health() (curl GET /v1/apps) is the authoritative liveness gate. Kept identical to the
# dash-node wrapper on purpose; unifying the two is a follow-up, not a per-service fix.
pgrep -f "python3 -m cx_core" >/dev/null 2>&1
}

start() {
if running; then
echo "[pdsm:$SERVICE_NAME] already running"
return 0
fi

echo "[pdsm:$SERVICE_NAME] starting..."
cd "$APP_DIR" || return 1

# Supervisor: respawn the server if it exits. Its PID is recorded so stop() can end
# the respawn loop before killing the server. LOGFILE is passed via the env so the
# inner shell expands it at runtime (avoids brittle nested quoting).
LOGFILE="$LOGFILE" nohup sh -c \
'while :; do python3 -m cx_core >> "$LOGFILE" 2>&1; echo "[cx-core] exited ($?); respawning in 2s" >> "$LOGFILE"; sleep 2; done' \
>/dev/null 2>&1 &
echo $! > "$SUP_PIDFILE"

for i in $(seq 1 "${PDSM_START_TIMEOUT:-8}"); do
if running; then
echo "[pdsm:$SERVICE_NAME] started"
return 0
fi
sleep 1
done

echo "[pdsm:$SERVICE_NAME] failed to start" >&2
return 1
}

stop() {
# Kill the supervisor first so it stops respawning, then the server itself.
if [ -f "$SUP_PIDFILE" ]; then
kill "$(cat "$SUP_PIDFILE")" 2>/dev/null || true
rm -f "$SUP_PIDFILE"
fi

if ! running; then
echo "[pdsm:$SERVICE_NAME] already stopped"
return 0
fi

echo "[pdsm:$SERVICE_NAME] stopping..."
pkill -f "python3 -m cx_core" 2>/dev/null || true

for i in $(seq 1 "${PDSM_START_TIMEOUT:-5}"); do
if ! running; then
echo "[pdsm:$SERVICE_NAME] stopped"
return 0
fi
sleep 1
done

pkill -9 -f "python3 -m cx_core" 2>/dev/null || true
echo "[pdsm:$SERVICE_NAME] forced stop"
return 1
}

status() {
if running; then
echo "[pdsm:$SERVICE_NAME] running (PID: $(pgrep -f "python3 -m cx_core" | head -n 1))"
return 0
fi
echo "[pdsm:$SERVICE_NAME] not running"
return 3
}

health() {
# Liveness: the REST API answers 2xx on loopback (the apps list is always 200).
if command -v curl >/dev/null 2>&1 && \
curl -fs -o /dev/null "http://127.0.0.1:${CX_PORT}/v1/apps"; then
echo "[pdsm:$SERVICE_NAME] healthy"
return 0
fi
echo "[pdsm:$SERVICE_NAME] unhealthy"
return 1
}

case "$1" in
start|stop|status|health) "$1" ;;
restart) stop; start ;;
*) echo "Usage: $0 {start|stop|restart|status|health}" >&2; exit 1 ;;
esac
2 changes: 2 additions & 0 deletions tools/rootfs-builder/build-iiab-rootfs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,8 @@ chk "PDSM installed (/usr/local/bin/pdsm)" "test -e '$ROOTFS/usr/local/bin/p
chk "flag_install_ready present" "test -e '$ROOTFS/usr/local/pdsm/flag_install_ready'"
chk "local_vars.yml has is_proot: True" "grep -qiE '^[[:space:]]*is_proot[[:space:]]*:[[:space:]]*True' '$ROOTFS/etc/iiab/local_vars.yml'"
chk "IIAB-oA repo cloned (/opt/iiab-android)" "test -d '$ROOTFS/opt/iiab-android'"
chk "cx-core installed (/opt/cx-core/cx_core)" "test -d '$ROOTFS/opt/cx-core/cx_core'"
chk "cx-core PDSM service registered" "test -x '$ROOTFS/usr/local/pdsm/services-available/cx-core'"

# Ansible result: use the PLAY RECAP (authoritative). We do NOT count loose
# 'fatal:'/'FAILED!' lines, because block/rescue tasks (e.g. the WiFi-AP probe
Expand Down
Loading
Loading