From 615c57b6f2b733e41715069b24baf0aa568167ce Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Thu, 22 Oct 2026 12:59:14 -0600 Subject: [PATCH 1/3] K2GO-427 chore(cx-core): run as a supervised box service on both envs New PDSM wrapper (static/pdsm/cx-core) and cx_core Ansible role: PDSM under proot, a systemd unit otherwise, chosen by is_proot; health on GET /v1/apps; writes the install/installed IIAB flags like the code_assets role. The iiab-android bootstrap installs cx-core next to dash-node (the K2Go bake driver); the rootfs-builder asserts the source and the PDSM service baked. --- iiab-android | 49 ++++++++ static/pdsm/cx-core | 106 ++++++++++++++++++ tools/rootfs-builder/build-iiab-rootfs.sh | 2 + .../overlays/roles/cx_core/defaults/main.yml | 28 +++++ .../roles/cx_core/tasks/enable-or-disable.yml | 23 ++++ .../overlays/roles/cx_core/tasks/install.yml | 81 +++++++++++++ .../overlays/roles/cx_core/tasks/main.yml | 46 ++++++++ .../cx_core/templates/cx-core.service.j2 | 16 +++ 8 files changed, 351 insertions(+) create mode 100755 static/pdsm/cx-core create mode 100644 tools/upstream-patches/overlays/roles/cx_core/defaults/main.yml create mode 100644 tools/upstream-patches/overlays/roles/cx_core/tasks/enable-or-disable.yml create mode 100644 tools/upstream-patches/overlays/roles/cx_core/tasks/install.yml create mode 100644 tools/upstream-patches/overlays/roles/cx_core/tasks/main.yml create mode 100644 tools/upstream-patches/overlays/roles/cx_core/templates/cx-core.service.j2 diff --git a/iiab-android b/iiab-android index e66defc70..6789d19f5 100644 --- a/iiab-android +++ b/iiab-android @@ -545,6 +545,52 @@ install_iiaboa_dashboard() { ok "IIAB-oA Dashboard installed and running!" } +#----------------------------- +# Install content-exchange core (K2GO-427) +#----------------------------- +# The core is Python 3 stdlib (no pip install, no build): "install" is a file copy plus +# registering the PDSM service. Same shape as install_iiaboa_dashboard, minus the Node +# build. On IIAB the cx_core Ansible role installs a systemd unit instead; this bootstrap +# is the K2Go (proot) driver. +install_iiaboa_cx_core() { + log "Installing the content-exchange core (cx-core)..." + local cx_src="${K2GO_OPT_DIR}/static/cx-core" + local cx_dest="/opt/cx-core" + + if [ ! -d "$cx_src" ]; then + warn "cx-core source not found at $cx_src; skipping." + return 0 + fi + + mkdir -p "$cx_dest" + cp -a "${cx_src}/." "$cx_dest/" + + # Export staging lives on the content volume, not /tmp (the core's CX_STAGING_DIR default). + mkdir -p /library/.cx-staging + + log "Configuring cx-core PDSM service..." + cp "${K2GO_OPT_DIR}/static/pdsm/cx-core" "/usr/local/pdsm/services-available/cx-core" + chmod +x "/usr/local/pdsm/services-available/cx-core" + /usr/local/bin/pdsm enable cx-core + /usr/local/bin/pdsm restart cx-core + + # Record the IIAB flags, the same contract the Code on the Go roles use: intent in + # local_vars.yml, completion in iiab_state.yml. The completion marker keeps the cx_core + # Ansible role idempotent (it gates install on 'cx_core_installed is undefined'), so a + # later runrole does not redo what this bootstrap already installed. + 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" + + local state_file="/etc/iiab/iiab_state.yml" + if [ -f "$state_file" ]; then + sed -i -E '/^[[:space:]]*cx_core_installed[[:space:]]*:/d' "$state_file" + echo "cx_core_installed: True" >> "$state_file" + fi + + ok "Content-exchange core installed and running!" +} + #----------------------------- # Update package db + deps #----------------------------- @@ -843,6 +889,9 @@ install_welcome_zim # Install dashboard install_iiaboa_dashboard +# Install the content-exchange core (depends on nothing above; runs next to dash-node) +install_iiaboa_cx_core + #----------------------------- # Reclaim disk: drop downloaded .deb archives #----------------------------- diff --git a/static/pdsm/cx-core b/static/pdsm/cx-core new file mode 100755 index 000000000..ce1e4d64f --- /dev/null +++ b/static/pdsm/cx-core @@ -0,0 +1,106 @@ +#!/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() { + # Match the actual server process, not the supervisor shell. + 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 diff --git a/tools/rootfs-builder/build-iiab-rootfs.sh b/tools/rootfs-builder/build-iiab-rootfs.sh index e2d5f7f44..b9e0fa7a1 100755 --- a/tools/rootfs-builder/build-iiab-rootfs.sh +++ b/tools/rootfs-builder/build-iiab-rootfs.sh @@ -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 diff --git a/tools/upstream-patches/overlays/roles/cx_core/defaults/main.yml b/tools/upstream-patches/overlays/roles/cx_core/defaults/main.yml new file mode 100644 index 000000000..9b7f2e344 --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/defaults/main.yml @@ -0,0 +1,28 @@ +# cx_core_install: True +# cx_core_enabled: True + +# The content-exchange core: an in-box REST service (Python stdlib, no third-party +# deps) that lists, exports and imports content per item across Kiwix, Kolibri and +# Calibre. It is client-agnostic: dash-node (K2Go) or the IIAB Console reach it over +# its localhost REST API. Design: controller/docs/ADR-content-exchange.md (K2GO-427). +# +# The core code is identical on every environment; only the supervisor differs. Under +# proot (K2Go) it runs as a PDSM service; on a systemd host (IIAB) it runs as a systemd +# unit. This role installs the source and the right wrapper, chosen by is_proot. + +# Where the source tree is copied FROM. Default is the K2Go repo path on the box +# (/opt/iiab-android). An IIAB deploy overrides this to wherever it stages the source. +cx_core_src_dir: /opt/iiab-android/static/cx-core + +# Where the core is installed TO (app code, a fixed path). `python3 -m cx_core` runs +# from here. The CX_* runtime paths (zims, kolibri db, staging) default to the box +# layout inside the core itself, so this role sets none of them. +cx_core_serve_path: /opt/cx-core + +# The localhost port the core binds. Matches the core's own default and the health +# probe in the service wrappers. +cx_core_port: 9500 + +# The PDSM service wrapper to install under proot. Ships in the repo next to the +# dash-node wrapper; both drivers (this role and the iiab-android bootstrap) copy it. +cx_core_pdsm_src: "{{ cx_core_src_dir }}/../pdsm/cx-core" diff --git a/tools/upstream-patches/overlays/roles/cx_core/tasks/enable-or-disable.yml b/tools/upstream-patches/overlays/roles/cx_core/tasks/enable-or-disable.yml new file mode 100644 index 000000000..ff291548d --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/tasks/enable-or-disable.yml @@ -0,0 +1,23 @@ +# Reflect cx_core_enabled on the running service. Idempotent verbs (pdsm start reports +# "already running"; systemd state=started does not bounce a live unit), so this runs on +# every play without churning the service. install.yml already did the first start. + +- name: Start cx-core via PDSM (proot) + command: pdsm start cx-core + when: is_proot and cx_core_enabled + +- name: Stop cx-core via PDSM (proot) + command: pdsm stop cx-core + when: is_proot and not cx_core_enabled + +- name: Start cx-core via systemd (not proot) + systemd: + name: cx-core + state: started + when: not is_proot and cx_core_enabled + +- name: Stop cx-core via systemd (not proot) + systemd: + name: cx-core + state: stopped + when: not is_proot and not cx_core_enabled diff --git a/tools/upstream-patches/overlays/roles/cx_core/tasks/install.yml b/tools/upstream-patches/overlays/roles/cx_core/tasks/install.yml new file mode 100644 index 000000000..b220988ba --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/tasks/install.yml @@ -0,0 +1,81 @@ +# Install the content-exchange core and its launch wrapper. The core is pure Python 3 +# stdlib (no pip install), so "install" is a file copy plus registering a supervisor. +# The supervisor is PDSM under proot and systemd otherwise, chosen by is_proot. + +- name: Create the install dir {{ cx_core_serve_path }} + file: + path: "{{ cx_core_serve_path }}" # /opt/cx-core + state: directory + mode: "0755" + +- name: Copy the core source into {{ cx_core_serve_path }} + copy: + src: "{{ cx_core_src_dir }}/" # trailing slash: copy the contents + dest: "{{ cx_core_serve_path }}/" + remote_src: yes + mode: preserve + +- name: Create the export staging dir (on the content volume, not /tmp) + file: + path: "{{ content_base }}/.cx-staging" # /library/.cx-staging (core CX_STAGING_DIR default) + state: directory + mode: "0755" + + +# ---- Launch wrapper: PDSM under proot ---- + +- name: Install the PDSM service wrapper (proot) + copy: + src: "{{ cx_core_pdsm_src }}" # static/pdsm/cx-core + dest: /usr/local/pdsm/services-available/cx-core + remote_src: yes + mode: "0755" + when: is_proot + +- name: Enable + start cx-core via PDSM (proot) + command: "pdsm {{ item }} cx-core" + with_items: + - enable + - restart + when: is_proot + + +# ---- Launch wrapper: systemd otherwise (IIAB) ---- + +- name: Install the systemd unit (not proot) + template: + src: cx-core.service.j2 + dest: /etc/systemd/system/cx-core.service + mode: "0644" + when: not is_proot + +- name: Enable + start cx-core via systemd (not proot) + systemd: + name: cx-core + enabled: yes + state: restarted + daemon_reload: yes + when: not is_proot + + +# ---- Health check: the REST API answers on loopback ---- + +- name: Wait for the core to answer GET /v1/apps on 127.0.0.1:{{ cx_core_port }} + uri: + url: "http://127.0.0.1:{{ cx_core_port }}/v1/apps" + status_code: 200 + register: cx_core_health + until: cx_core_health.status == 200 + retries: 10 + delay: 2 + + +- name: "Set 'cx_core_installed: True'" + set_fact: + cx_core_installed: True + +- name: "Add 'cx_core_installed: True' to {{ iiab_state_file }}" + lineinfile: + path: "{{ iiab_state_file }}" # /etc/iiab/iiab_state.yml + regexp: '^cx_core_installed' + line: 'cx_core_installed: True' diff --git a/tools/upstream-patches/overlays/roles/cx_core/tasks/main.yml b/tools/upstream-patches/overlays/roles/cx_core/tasks/main.yml new file mode 100644 index 000000000..33b3e9d89 --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/tasks/main.yml @@ -0,0 +1,46 @@ +- name: Assert that "cx_core_install is sameas true" (boolean not string etc) + assert: + that: cx_core_install is sameas true + fail_msg: "PLEASE SET 'cx_core_install: True' e.g. IN: /etc/iiab/local_vars.yml" + quiet: yes + +- name: Assert that "cx_core_enabled | type_debug == 'bool'" (boolean not string etc) + assert: + that: cx_core_enabled | type_debug == 'bool' + fail_msg: "PLEASE GIVE VARIABLE 'cx_core_enabled' A PROPER (UNQUOTED) ANSIBLE BOOLEAN VALUE e.g. IN: /etc/iiab/local_vars.yml" + quiet: yes + + +- block: + + - name: Install the content-exchange core if 'cx_core_installed' not defined, e.g. in {{ iiab_state_file }} + include_tasks: install.yml + when: cx_core_installed is undefined + + - name: Enable/Disable the content-exchange core service + include_tasks: enable-or-disable.yml + + - name: Add 'cx_core' variable values to {{ iiab_ini_file }} + ini_file: + path: "{{ iiab_ini_file }}" # /etc/iiab/iiab.ini + section: cx_core + option: "{{ item.option }}" + value: "{{ item.value | string }}" + with_items: + - option: name + value: Content exchange core + - option: description + value: 'In-box REST service for granular content exchange (Kiwix, Kolibri, Calibre).' + - option: cx_core_install + value: "{{ cx_core_install }}" + - option: cx_core_enabled + value: "{{ cx_core_enabled }}" + - option: cx_core_port + value: "{{ cx_core_port }}" + + rescue: + + - name: 'SEE ERROR ABOVE (skip_role_on_error: {{ skip_role_on_error }})' + fail: + msg: "" + when: not skip_role_on_error diff --git a/tools/upstream-patches/overlays/roles/cx_core/templates/cx-core.service.j2 b/tools/upstream-patches/overlays/roles/cx_core/templates/cx-core.service.j2 new file mode 100644 index 000000000..a2e81e602 --- /dev/null +++ b/tools/upstream-patches/overlays/roles/cx_core/templates/cx-core.service.j2 @@ -0,0 +1,16 @@ +# cx-core: content-exchange core (K2GO-427). systemd unit for IIAB hosts; the proot +# (K2Go) path uses the PDSM wrapper instead. The core is Python stdlib, localhost-only. +[Unit] +Description=Content exchange core (REST service for Kiwix/Kolibri/Calibre) +After=network.target + +[Service] +Type=simple +WorkingDirectory={{ cx_core_serve_path }} +Environment=CX_PORT={{ cx_core_port }} +ExecStart=/usr/bin/python3 -m cx_core +Restart=always +RestartSec=2 + +[Install] +WantedBy=multi-user.target From 03e296a4c35de366e97fddd246c7377b3fc58d24 Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Thu, 22 Oct 2026 12:59:22 -0600 Subject: [PATCH 2/3] K2GO-427 feat(dash-node): relay /v1/* to cx-core Thin Node-core proxy forwards /v1/* (GET and POST, including the streamed GET /v1/export/item) to the in-box cx-core service on 127.0.0.1:9500. Reached externally at /k2go-api/v1/*. dash-node only relays; the core owns the content state. Bump 1.5.0 + changelog; add a proxy unit test. --- static/dashboard/CHANGELOG.md | 1 + static/dashboard/package.json | 4 +- static/dashboard/routes.ts | 6 ++ static/dashboard/sockets/cx-proxy.test.ts | 121 ++++++++++++++++++++++ static/dashboard/sockets/cx-proxy.ts | 56 ++++++++++ 5 files changed, 186 insertions(+), 2 deletions(-) create mode 100644 static/dashboard/sockets/cx-proxy.test.ts create mode 100644 static/dashboard/sockets/cx-proxy.ts diff --git a/static/dashboard/CHANGELOG.md b/static/dashboard/CHANGELOG.md index f29fde428..a11d5f4f9 100644 --- a/static/dashboard/CHANGELOG.md +++ b/static/dashboard/CHANGELOG.md @@ -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.5.0** - 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.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) - **1.4.1** - Kolibri imports are verified, not trusted (K2GO-475). A missing file on Studio no longer aborts the import (`fail_on_error` off). After Kolibri reports COMPLETED, the runner counts the selected resources that Kolibri marks available in its db; none available is an error, some is a success with the counts in the new job field `result` (`{outcome: complete|partial, requested, available, notFound}`, also cleared on retry/resume). Only the engine writes the terminal phase. A restart adopts the import Kolibri is still running instead of queueing a second one. Pause now stops the Kolibri task, and resume queues it again (Kolibri skips the files it has). Any exit of the poll cancels and clears the Kolibri task. Thumbnails of every topic are no longer forced on a partial pick; the caller asks for them. (K2GO-475) diff --git a/static/dashboard/package.json b/static/dashboard/package.json index a8100c1fe..c487c41e3 100644 --- a/static/dashboard/package.json +++ b/static/dashboard/package.json @@ -1,10 +1,10 @@ { "name": "dashboard-console", - "version": "1.4.3", + "version": "1.5.0", "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", diff --git a/static/dashboard/routes.ts b/static/dashboard/routes.ts index 8392c7797..08e169bcc 100644 --- a/static/dashboard/routes.ts +++ b/static/dashboard/routes.ts @@ -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 @@ -71,6 +72,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. diff --git a/static/dashboard/sockets/cx-proxy.test.ts b/static/dashboard/sockets/cx-proxy.test.ts new file mode 100644 index 000000000..34c30a043 --- /dev/null +++ b/static/dashboard/sockets/cx-proxy.test.ts @@ -0,0 +1,121 @@ +/// +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 { + 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 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(); + } +}); diff --git a/static/dashboard/sockets/cx-proxy.ts b/static/dashboard/sockets/cx-proxy.ts new file mode 100644 index 000000000..28d4eb9c7 --- /dev/null +++ b/static/dashboard/sockets/cx-proxy.ts @@ -0,0 +1,56 @@ +// 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 = {}; + 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 the content type through; let Node frame the body (length or chunked) so a + // streamed export is relayed as-is. + const ct = up.headers['content-type']; + if (ct) res.setHeader('content-type', ct); + 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(); +} From bff19636341174e53df5c868d981af1a1ce2c54e Mon Sep 17 00:00:00 2001 From: "Luis Guzman (AppDevForAll)" Date: Thu, 22 Oct 2026 13:53:07 -0600 Subject: [PATCH 3/3] K2GO-427 fix(cx-core): deploy review fixes iiab-android installs cx-core via 'runrole cx_core', not a hand-install: the cx_core role is the single install source for both proot (PDSM) and systemd, and cx-core has no build step that would force the dash-node hand-install path. cx-proxy also forwards Content-Disposition and the upstream Content-Length (the export filename the app needs); the PDSM wrapper notes running() is liveness-approximate and health() is the gate. --- iiab-android | 67 +++++++---------------- static/dashboard/sockets/cx-proxy.test.ts | 20 +++++++ static/dashboard/sockets/cx-proxy.ts | 9 ++- static/pdsm/cx-core | 4 +- 4 files changed, 49 insertions(+), 51 deletions(-) diff --git a/iiab-android b/iiab-android index 6789d19f5..887614cb5 100644 --- a/iiab-android +++ b/iiab-android @@ -545,52 +545,6 @@ install_iiaboa_dashboard() { ok "IIAB-oA Dashboard installed and running!" } -#----------------------------- -# Install content-exchange core (K2GO-427) -#----------------------------- -# The core is Python 3 stdlib (no pip install, no build): "install" is a file copy plus -# registering the PDSM service. Same shape as install_iiaboa_dashboard, minus the Node -# build. On IIAB the cx_core Ansible role installs a systemd unit instead; this bootstrap -# is the K2Go (proot) driver. -install_iiaboa_cx_core() { - log "Installing the content-exchange core (cx-core)..." - local cx_src="${K2GO_OPT_DIR}/static/cx-core" - local cx_dest="/opt/cx-core" - - if [ ! -d "$cx_src" ]; then - warn "cx-core source not found at $cx_src; skipping." - return 0 - fi - - mkdir -p "$cx_dest" - cp -a "${cx_src}/." "$cx_dest/" - - # Export staging lives on the content volume, not /tmp (the core's CX_STAGING_DIR default). - mkdir -p /library/.cx-staging - - log "Configuring cx-core PDSM service..." - cp "${K2GO_OPT_DIR}/static/pdsm/cx-core" "/usr/local/pdsm/services-available/cx-core" - chmod +x "/usr/local/pdsm/services-available/cx-core" - /usr/local/bin/pdsm enable cx-core - /usr/local/bin/pdsm restart cx-core - - # Record the IIAB flags, the same contract the Code on the Go roles use: intent in - # local_vars.yml, completion in iiab_state.yml. The completion marker keeps the cx_core - # Ansible role idempotent (it gates install on 'cx_core_installed is undefined'), so a - # later runrole does not redo what this bootstrap already installed. - 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" - - local state_file="/etc/iiab/iiab_state.yml" - if [ -f "$state_file" ]; then - sed -i -E '/^[[:space:]]*cx_core_installed[[:space:]]*:/d' "$state_file" - echo "cx_core_installed: True" >> "$state_file" - fi - - ok "Content-exchange core installed and running!" -} - #----------------------------- # Update package db + deps #----------------------------- @@ -722,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 #----------------------------- @@ -889,8 +851,17 @@ install_welcome_zim # Install dashboard install_iiaboa_dashboard -# Install the content-exchange core (depends on nothing above; runs next to dash-node) -install_iiaboa_cx_core +#----------------------------- +# 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 diff --git a/static/dashboard/sockets/cx-proxy.test.ts b/static/dashboard/sockets/cx-proxy.test.ts index 34c30a043..338d625eb 100644 --- a/static/dashboard/sockets/cx-proxy.test.ts +++ b/static/dashboard/sockets/cx-proxy.test.ts @@ -105,6 +105,26 @@ test('cxProxy streams a chunked response intact (the export path)', async () => } }); +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(); diff --git a/static/dashboard/sockets/cx-proxy.ts b/static/dashboard/sockets/cx-proxy.ts index 28d4eb9c7..bb2771934 100644 --- a/static/dashboard/sockets/cx-proxy.ts +++ b/static/dashboard/sockets/cx-proxy.ts @@ -38,10 +38,15 @@ export function cxProxy(req: Request, res: Response): void { { host: CX_HOST, port: cxPort(), method: req.method, path: corePath, headers }, (up) => { res.status(up.statusCode || 502); - // Pass the content type through; let Node frame the body (length or chunked) so a - // streamed export is relayed as-is. + // 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); }, ); diff --git a/static/pdsm/cx-core b/static/pdsm/cx-core index ce1e4d64f..62c6ad968 100755 --- a/static/pdsm/cx-core +++ b/static/pdsm/cx-core @@ -18,7 +18,9 @@ LOGFILE="/var/log/cx-core.log" SUP_PIDFILE="/var/run/cx-core.sup.pid" running() { - # Match the actual server process, not the supervisor shell. + # 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 }