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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
* Name : CxCoreDataSource.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : K2GO-427. App-side client of the content-exchange core (cx-core)
* Description : K2GO-427 / K2GO-507. App-side client of the content-exchange core (cx-core)
* through dash-node's relay (/k2go-api/v1/*). Read side (list + storage)
* plus the export calls (plan + streaming item). Same HttpURLConnection
* shape as content/RestContentClient. The one place this feature touches
* HttpURLConnection.
* plus the export long operation (prepare / status / fetch / abort) and the
* import calls. Same HttpURLConnection shape as content/RestContentClient. The
* one place this feature touches HttpURLConnection.
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.data;
Expand Down Expand Up @@ -40,6 +40,12 @@ public final class CxCoreDataSource {
/** Delete blocks on the box's own delete (Kolibri deletechannel, Kiwix reindex), which can run
* well past the read-side timeout, so it waits longer than a plain read. */
private static final int DELETE_READ_TIMEOUT_MS = 120000;
/** K2GO-507: the export fetch read timeout is a per-read (inactivity) gap, NOT a total wall
* clock. {@link HttpURLConnection#setReadTimeout} fires only when a single read blocks this
* long with no bytes, and it resets on every read, so a multi-GB staged tar can stream for
* minutes as long as bytes keep flowing; only a genuine stall trips it. The op is already
* staged when we fetch, so the response head returns fast. */
private static final int FETCH_STALL_TIMEOUT_MS = 60000;

/** {@code GET /v1/apps} -> {@code {"apps": [...]}}. */
public JSONObject getApps() throws Exception {
Expand Down Expand Up @@ -81,24 +87,43 @@ public JSONObject deleteContent(String app, String localRef) throws Exception {
}

/**
* {@code GET /v1/export/item/{app}/{localRef}} -> the item's streaming archive. The core sends a
* chunked response with no Content-Length; the caller streams the body and closes the returned
* handle to release the connection. Path segments are percent-encoded (the core decodes them).
* {@code POST /v1/export/prepare} with {@code {app, localRef}} -> {@code {opId, state, totalBytes}}.
* Starts (or finds nothing to stage for) the export operation; returns fast. K2GO-507.
*/
public Stream openExportItem(String app, String localRef) throws Exception {
String url = V1 + "/export/item/" + encodeSegment(app) + "/" + encodeSegment(localRef);
public JSONObject postExportPrepare(String app, String localRef) throws Exception {
JSONObject body = new JSONObject().put("app", app).put("localRef", localRef);
return postJson(V1 + "/export/prepare", body);
}

/**
* {@code GET /v1/export/status/{opId}} -> {@code {state, stagedBytes, totalBytes, error?}}. A 404
* means the op was swept; it surfaces as {@link CxHttpException} with {@code code() == 404} so the
* caller can re-prepare rather than keep polling a dead id. K2GO-507.
*/
public JSONObject getExportStatus(String opId) throws Exception {
return getJson(V1 + "/export/status/" + encodeSegment(opId));
}

/**
* {@code GET /v1/export/fetch/{opId}} -> the staged archive as a chunked stream. The op is already
* staged, so the response head returns fast; the body uses a per-read STALL timeout (see
* {@link #FETCH_STALL_TIMEOUT_MS}), not a wall clock. The caller streams the body and closes the
* returned handle to release the connection (the core clears the op on close). K2GO-507.
*/
public Stream openExportFetch(String opId) throws Exception {
String url = V1 + "/export/fetch/" + encodeSegment(opId);
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
try {
c.setUseCaches(false);
c.setConnectTimeout(CONNECT_TIMEOUT_MS);
c.setReadTimeout(READ_TIMEOUT_MS);
c.setReadTimeout(FETCH_STALL_TIMEOUT_MS);
c.setRequestMethod("GET");
c.setRequestProperty("Accept", "application/octet-stream");
int code = c.getResponseCode();
if (code < 200 || code >= 400) {
String text = readAll(c.getErrorStream());
c.disconnect();
throw new Exception("HTTP " + code + ": " + text);
throw new CxHttpException(code, text);
}
String filename = parseContentDispositionFilename(c.getHeaderField("Content-Disposition"));
return new Stream(c, c.getInputStream(), filename);
Expand All @@ -108,6 +133,11 @@ public Stream openExportItem(String app, String localRef) throws Exception {
}
}

/** {@code DELETE /v1/export/{opId}} -> {@code {ok}}. Client abort of an in-flight op. K2GO-507. */
public JSONObject deleteExportOp(String opId) throws Exception {
return deleteJson(V1 + "/export/" + encodeSegment(opId));
}

private static JSONObject postJson(String urlStr, JSONObject body) throws Exception {
HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection();
try {
Expand All @@ -126,7 +156,7 @@ private static JSONObject postJson(String urlStr, JSONObject body) throws Except
boolean ok = code >= 200 && code < 400;
String text = readAll(ok ? c.getInputStream() : c.getErrorStream());
if (!ok) {
throw new Exception("HTTP " + code + ": " + text);
throw new CxHttpException(code, text);
}
return new JSONObject(text.isEmpty() ? "{}" : text);
} finally {
Expand All @@ -146,7 +176,7 @@ private static JSONObject deleteJson(String urlStr) throws Exception {
boolean ok = code >= 200 && code < 400;
String text = readAll(ok ? c.getInputStream() : c.getErrorStream());
if (!ok) {
throw new Exception("HTTP " + code + ": " + text);
throw new CxHttpException(code, text);
}
return new JSONObject(text.isEmpty() ? "{}" : text);
} finally {
Expand All @@ -166,7 +196,7 @@ private static JSONObject getJson(String urlStr) throws Exception {
boolean ok = code >= 200 && code < 400;
String text = readAll(ok ? c.getInputStream() : c.getErrorStream());
if (!ok) {
throw new Exception("HTTP " + code + ": " + text);
throw new CxHttpException(code, text);
}
return new JSONObject(text.isEmpty() ? "{}" : text);
} finally {
Expand Down Expand Up @@ -215,6 +245,24 @@ private static String parseContentDispositionFilename(String header) {
return semi >= 0 ? value.substring(0, semi).trim() : value;
}

/**
* A non-2xx/3xx HTTP response, carrying the status code so a caller can branch on it: the export
* status poll treats {@code code() == 404} as "operation swept" and re-prepares. Extends
* {@link Exception}, so callers that only {@code catch (Exception)} keep working. K2GO-507.
*/
public static final class CxHttpException extends Exception {
private final int code;

CxHttpException(int code, String message) {
super("HTTP " + code + ": " + message);
this.code = code;
}

public int code() {
return code;
}
}

/** A live streaming response: the body plus the server-suggested name. Close to release the socket. */
public static final class Stream implements Closeable {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@
* Name : CxCoreExportSource.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : K2GO-427. Data-layer implementation of the export source port against
* cx-core (through dash-node's /v1 relay): POST /v1/export/plan, the
* streaming GET /v1/export/item, and the collection-manifest assembly.
* Description : K2GO-427 / K2GO-507. Data-layer implementation of the export source port against
* cx-core (through dash-node's /v1 relay): POST /v1/export/plan, the export long
* operation (prepare / status / fetch / abort), and the collection-manifest assembly.
* ============================================================================
*/
package org.appdevforall.k2go.contentexchange.data;

import org.appdevforall.k2go.contentexchange.domain.ContentExportSource;
import org.appdevforall.k2go.contentexchange.domain.ExportItem;
import org.appdevforall.k2go.contentexchange.domain.ExportPlan;
import org.appdevforall.k2go.contentexchange.domain.ExportPrep;
import org.appdevforall.k2go.contentexchange.domain.ExportStatus;
import org.appdevforall.k2go.contentexchange.domain.ItemRef;
import org.json.JSONArray;
import org.json.JSONObject;
Expand Down Expand Up @@ -93,11 +95,61 @@ public ExportPlan plan(List<ItemRef> refs) throws Exception {
}

@Override
public ItemPayload open(ItemRef ref) throws Exception {
CxCoreDataSource.Stream stream = dataSource.openExportItem(ref.app(), ref.localRef());
public ExportPrep prepare(ItemRef ref) throws Exception {
JSONObject r = dataSource.postExportPrepare(ref.app(), ref.localRef());
String opId = r.optString("opId", "");
if (opId.isEmpty()) {
throw new Exception("export prepare returned no opId");
}
boolean ready = "ready".equals(r.optString("state", ""));
return new ExportPrep(opId, ready, r.optLong("totalBytes", 0L));
}

@Override
public ExportStatus status(String opId) throws Exception {
JSONObject r;
try {
r = dataSource.getExportStatus(opId);
} catch (CxCoreDataSource.CxHttpException e) {
if (e.code() == 404) {
return ExportStatus.gone(); // the op was swept: the caller re-prepares
}
throw e;
}
ExportStatus.State state;
switch (r.optString("state", "")) {
case "ready":
state = ExportStatus.State.READY;
break;
case "error":
state = ExportStatus.State.ERROR;
break;
default:
state = ExportStatus.State.STAGING;
break;
}
String error = r.isNull("error") ? null : r.optString("error", null);
return new ExportStatus(state, r.optLong("stagedBytes", 0L), r.optLong("totalBytes", 0L), error);
}

@Override
public ItemPayload fetch(String opId) throws Exception {
CxCoreDataSource.Stream stream = dataSource.openExportFetch(opId);
return new ItemPayload(stream.body(), stream.filename(), stream);
}

@Override
public void abort(String opId) {
if (opId == null || opId.isEmpty()) {
return;
}
try {
dataSource.deleteExportOp(opId);
} catch (Exception ignored) {
// Best-effort: a swept or already-dropped op 404s; the box's TTL sweep is the backstop.
}
}

@Override
public byte[] buildManifest(List<ItemRef> order, Map<ItemRef, String> payloadNames) throws Exception {
return CollectionManifest.build(entries, order, payloadNames);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,17 @@
import java.util.Map;

/**
* Domain port for the BOX side of an export: plan the items, stream one item's archive, and
* build the collection manifest. The Data layer implements it against the core REST API
* (through dash-node's {@code /v1/*} relay); the domain never learns the transport or the
* JSON shape.
* Domain port for the BOX side of an export: plan the items, run the per-item staging long
* operation (prepare, poll, fetch), and build the collection manifest. The Data layer implements
* it against the core REST API (through dash-node's {@code /v1/*} relay); the domain never learns
* the transport or the JSON shape.
*
* <p>K2GO-507: a large item (a multi-GB Kolibri channel) is staged on the box before any byte
* streams, so a single blocking request times out. The export is therefore a long operation: the
* caller {@link #prepare}s an item, {@link #status}-polls while the box stages it (the poll is the
* liveness signal, so there is no wall-clock timeout), then {@link #fetch}es the staged stream.
* {@link #abort} drops an operation the caller gives up on. The box owns the operation state; the
* caller only mirrors it, so there is no competing "where is this export" on the app side.
*
* <p>The manifest is built here rather than in the carrier because the source holds the
* authoritative per-item entries the plan returned (identity, dedup, integrity); the carrier
Expand All @@ -24,8 +31,17 @@ public interface ContentExportSource {
/** Plan the given items: exact sizes + skip list, moving no payload. */
ExportPlan plan(List<ItemRef> refs) throws Exception;

/** Open the streaming archive for one item. The caller copies the stream, then closes it. */
ItemPayload open(ItemRef ref) throws Exception;
/** Start staging one item on the box: returns the operation id and whether it is already ready. */
ExportPrep prepare(ItemRef ref) throws Exception;

/** One status reading of a staging operation. A swept operation reports {@code GONE}. */
ExportStatus status(String opId) throws Exception;

/** Open the staged stream for a ready operation. The caller copies the stream, then closes it. */
ItemPayload fetch(String opId) throws Exception;

/** Best-effort drop of an operation the caller abandons (cancel or error). Never throws. */
void abort(String opId);

/**
* Build the top-level {@code manifest.json} over the items that were written, in the given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,19 @@ public final class ExportJob {
public static final int DONE = 2;
public static final int FAILED = 3;

/** K2GO-507: the two phases of an active item's progress bar. The box stages the item
* ({@link #PHASE_PREPARE}, fed by stagedBytes) before it streams ({@link #PHASE_WRITE}, fed by
* copiedBytes). The bar maps prepare to 0..50 percent and write to 50..100 percent. */
public static final int PHASE_PREPARE = 0;
public static final int PHASE_WRITE = 1;

private int[] status = new int[0];
private long[] planned = new long[0];
private long[] copied = new long[0];
/** K2GO-507: per-item phase and bytes staged so far. These mirror the box's op status (the single
* source of truth); the job never stores a competing "where is this export", it projects the poll. */
private int[] phase = new int[0];
private long[] staged = new long[0];
private int index = -1;

/**
Expand All @@ -30,6 +40,8 @@ public void begin(long[] plannedBytes) {
status = new int[n];
planned = new long[n];
copied = new long[n];
phase = new int[n];
staged = new long[n];
index = -1;
for (int i = 0; i < n; i++) {
if (plannedBytes[i] < 0) {
Expand Down Expand Up @@ -75,10 +87,35 @@ public void setActive(int i) {
if (i >= 0 && i < status.length) {
status[i] = ACTIVE;
copied[i] = 0L;
// An item starts in the prepare phase: the box stages it before it streams (K2GO-507).
phase[i] = PHASE_PREPARE;
staged[i] = 0L;
index = i;
}
}

public int phase(int i) {
return i >= 0 && i < phase.length ? phase[i] : PHASE_WRITE;
}

/** Move the active item from staging to streaming (prepare -> write). */
public void setPhase(int i, int newPhase) {
if (i >= 0 && i < phase.length) {
phase[i] = newPhase;
}
}

public long staged(int i) {
return i >= 0 && i < staged.length ? staged[i] : 0L;
}

/** Record the absolute bytes staged so far on the box for item {@code i} (prepare-phase progress). */
public void setStaged(int i, long bytes) {
if (i >= 0 && i < staged.length) {
staged[i] = Math.max(0L, bytes);
}
}

/** Record the absolute bytes written so far for item {@code i}. */
public void setCopied(int i, long bytes) {
if (i >= 0 && i < copied.length) {
Expand Down Expand Up @@ -199,12 +236,28 @@ public int overallPercent() {
return (int) Math.min(100L, (long) settled * 100L / n);
}

/** Percent of the active item written so far (0 when its size is unknown). */
/**
* The active item's two-phase bar value (K2GO-507): the prepare phase fills 0..50 from stagedBytes,
* the write phase fills 50..100 from copiedBytes, both against the item's planned size. Returns 0
* when no item is active; when the size is unknown the prepare phase reads 0 and the write phase
* reads 50 (the bar still advances by phase, it just cannot show a within-phase fraction).
*/
public int currentItemPercent() {
int i = index;
if (i < 0 || i >= planned.length || planned[i] <= 0) {
if (i < 0 || i >= planned.length) {
return 0;
}
if (phase[i] == PHASE_PREPARE) {
return half(staged[i], planned[i]); // 0..50
}
return 50 + half(copied[i], planned[i]); // 50..100
}

/** {@code done/total} scaled into 0..50, or 0 when the total is unknown. */
private static int half(long done, long total) {
if (total <= 0) {
return 0;
}
return (int) Math.min(100L, copied[i] * 100L / planned[i]);
return (int) Math.min(50L, done * 50L / total);
}
}
Loading
Loading