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,8 +3,8 @@
* Name : CatalogRepositoryImpl.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : Wires the bundled catalog and the live Studio tree behind the
* domain port (ADFA-4954).
* Description : Wires the bundled catalog and the topic tree (box-served first,
* Studio as fallback) behind the domain port (ADFA-4954, -5094).
* ============================================================================
*/
package org.iiab.controller.kolibri.data;
Expand Down Expand Up @@ -38,10 +38,13 @@ public final class CatalogRepositoryImpl implements CatalogRepository {
private static final String BASENAME = BundledCatalogSource.ASSET;

private final BundledCatalogSource bundled;
private final StudioTreeSource studio;
private final TreeSource tree;

public CatalogRepositoryImpl(Context context) {
this(new BundledCatalogSource(context), new StudioTreeSource());
// ADFA-5094: prefer the box-served topic tree (offline, whole tree once the channel's
// metadata is imported) and fall back to Studio when the box cannot answer.
this(new BundledCatalogSource(context),
new FallbackTreeSource(new LocalTreeSource(), new StudioTreeSource()));
// Keep the bundled catalog current: a weekly refresh plus an opportunistic (TTL-gated)
// check now. Only the Context constructor schedules — the test constructor below does not.
org.iiab.controller.catalog.data.CatalogRefreshScheduler.scheduleWeekly(
Expand All @@ -50,10 +53,10 @@ public CatalogRepositoryImpl(Context context) {
context, CATALOG, MANIFEST_URL, BASENAME);
}

/** For tests and for pointing the tree source at a mirror. */
public CatalogRepositoryImpl(BundledCatalogSource bundled, StudioTreeSource studio) {
/** For tests and for pointing the tree source elsewhere (e.g. a local-first composite). */
public CatalogRepositoryImpl(BundledCatalogSource bundled, TreeSource tree) {
this.bundled = bundled;
this.studio = studio;
this.tree = tree;
}

@Override
Expand All @@ -68,6 +71,6 @@ public String catalogGeneratedOn() {

@Override
public TopicNode fetchTree(String nodeId) {
return studio.fetchTree(nodeId);
return tree.fetchTree(nodeId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* ============================================================================
* Name : FallbackTreeSource.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : Tries one tree source, then another. Lets the repository prefer
* the box-served tree and fall back to Studio (ADFA-5094).
* ============================================================================
*/
package org.iiab.controller.kolibri.data;

import org.iiab.controller.kolibri.domain.TopicNode;

/**
* A {@link TreeSource} that asks {@code primary} first and {@code secondary}
* only when the first has nothing.
*
* <p>The one place the local-first policy lives: prefer the box (offline,
* instant, whole tree once imported), fall to Studio when the box cannot answer
* — box down, channel not imported, or PR3 not yet shipped, in which case the
* primary always misses and behaviour is exactly what it was before ADFA-5094.
*
* <p>Deliberately pure — no network, no Android — so this routing is unit-tested
* on a plain JVM while the sources it composes are integration concerns.
* {@code secondary} is not consulted when {@code primary} answers, so a hit
* costs no extra call.
*/
public final class FallbackTreeSource implements TreeSource {

private final TreeSource primary;
private final TreeSource secondary;

public FallbackTreeSource(TreeSource primary, TreeSource secondary) {
if (primary == null || secondary == null) {
throw new IllegalArgumentException("both sources are required");
}
this.primary = primary;
this.secondary = secondary;
}

@Override
public TopicNode fetchTree(String nodeId) {
TopicNode fromPrimary = primary.fetchTree(nodeId);
return fromPrimary != null ? fromPrimary : secondary.fetchTree(nodeId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* ============================================================================
* Name : LocalTreeSource.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : Reads a channel's topic tree from the box on localhost, when the
* channel's metadata has been imported there. Offline path for
* topic browsing (ADFA-5094).
* ============================================================================
*/
package org.iiab.controller.kolibri.data;

import android.util.Log;

import org.iiab.controller.config.BoxEndpoints;
import org.iiab.controller.kolibri.domain.ChannelId;
import org.iiab.controller.kolibri.domain.TopicNode;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
* Reads topic trees from the box's Kolibri REST core, not the internet.
*
* <p>The offline counterpart to {@link StudioTreeSource}. Once a channel has been
* metadata-imported on the box (its tree DB present, the content not necessarily
* downloaded — ADFA-5094 PR3), the box can answer the same shape Studio does, so
* the picker browses the whole tree with no connectivity. Until that import
* exists the endpoint returns 404 and this source returns {@code null}, which is
* the signal for {@link FallbackTreeSource} to try Studio instead.
*
* <p>The response is deliberately the <em>same</em> JSON as Studio's
* {@code contentnode_tree}, so {@link StudioCatalogMapper#tree(JSONObject)}
* parses both with no branching. The box owns that translation (PR3); the device
* side stays a thin read.
*
* <p>Talks to localhost, so timeouts are tight — a slow box is a bug, not the
* poor long-haul link {@link StudioTreeSource} plans for. Blocking by design;
* never throws, per the {@link TreeSource} contract.
*/
public final class LocalTreeSource implements TreeSource {

private static final String TAG = "K2Go-Kolibri";

/** Endpoint under the box API base: {@code /k2go-api/kolibri/tree/<nodeId>}. */
private static final String TREE_PATH = "/kolibri/tree/";

/** Box API base ({@code …:8085/k2go-api}); overridable so a test can point at a mock. */
private static final String DEFAULT_BASE = BoxEndpoints.API;

private static final int CONNECT_TIMEOUT_MS = 2000;
private static final int READ_TIMEOUT_MS = 10000;

/** Refuse absurd payloads rather than filling the heap on a phone. */
private static final int MAX_BYTES = 8 * 1024 * 1024;

/** The box API base, without a trailing slash. */
private final String baseUrl;

public LocalTreeSource() {
this(DEFAULT_BASE);
}

/**
* @param baseUrl the box API base (e.g. {@code http://localhost:8085/k2go-api}); a
* trailing slash is stripped so no URL this builds carries a double slash.
* Exists so a test can point at a {@code MockWebServer}, mirroring
* {@link StudioTreeSource}.
*/
public LocalTreeSource(String baseUrl) {
String b = baseUrl == null || baseUrl.trim().isEmpty() ? DEFAULT_BASE : baseUrl.trim();
this.baseUrl = b.endsWith("/") ? b.substring(0, b.length() - 1) : b;
}

@Override
public TopicNode fetchTree(String nodeId) {
// Validate before the id reaches a URL path, exactly as StudioTreeSource
// does: a value with a slash or a query string would address something
// else entirely on the box. Fail closed.
String id = ChannelId.normalise(nodeId);
if (id == null) {
return null;
}
try {
String body = httpGet(baseUrl + TREE_PATH + id);
if (body.isEmpty()) {
return null;
}
return StudioCatalogMapper.tree(new JSONObject(body));
} catch (Exception e) {
// A miss here is ordinary — the channel may simply not be imported
// yet — so this is debug, not a warning: the fallback covers it.
Log.d(TAG, "local tree " + nodeId + " unavailable: " + e.getMessage());
return null;
}
}

private static String httpGet(String urlStr) throws Exception {
HttpURLConnection c = (HttpURLConnection) new URL(urlStr).openConnection();
try {
c.setUseCaches(false);
c.setConnectTimeout(CONNECT_TIMEOUT_MS);
c.setReadTimeout(READ_TIMEOUT_MS);
c.setRequestProperty("Accept", "application/json");
int code = c.getResponseCode();
InputStream is = code >= 200 && code < 400 ? c.getInputStream() : c.getErrorStream();
String text = readAll(is);
if (code < 200 || code >= 400) {
throw new Exception("HTTP " + code);
}
return text;
} finally {
c.disconnect();
}
}

private static String readAll(InputStream is) throws Exception {
if (is == null) {
return "";
}
try (InputStream in = is) {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
byte[] chunk = new byte[8192];
int n;
int total = 0;
while ((n = in.read(chunk)) != -1) {
total += n;
if (total > MAX_BYTES) {
throw new Exception("response over " + (MAX_BYTES / (1024 * 1024)) + " MB");
}
buf.write(chunk, 0, n);
}
return buf.toString(StandardCharsets.UTF_8.name());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
* <p>Blocking by design, so the caller controls threading. Never throws: a
* failure is a {@code null} return, per the {@code CatalogRepository} contract.
*/
public final class StudioTreeSource {
public final class StudioTreeSource implements TreeSource {

private static final String TAG = "K2Go-Kolibri";

Expand Down Expand Up @@ -66,6 +66,7 @@ public StudioTreeSource(String baseUrl) {
* @return the subtree, or null when the request failed or the body was not
* a usable node
*/
@Override
public TopicNode fetchTree(String nodeId) {
// Validate before the id reaches a URL path, not after. Every caller
// today passes an already-normalised Channel.rootNodeId(), but this
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* ============================================================================
* Name : TreeSource.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : One seam for reading a channel's topic tree, so the repository
* can prefer a box-served tree and fall back to Studio without
* knowing which is which (ADFA-5094).
* ============================================================================
*/
package org.iiab.controller.kolibri.data;

import org.iiab.controller.kolibri.domain.TopicNode;

/**
* A source of one level of a channel's topic tree.
*
* <p>Introduced so the two implementations — {@link StudioTreeSource} over the
* internet and {@link LocalTreeSource} over the box on localhost — are
* interchangeable behind {@link FallbackTreeSource}. Before ADFA-5094 the
* repository held a {@code StudioTreeSource} directly; the tree was Studio's or
* nothing.
*
* <p>Same contract as {@code CatalogRepository.fetchTree}: <b>never throws</b>.
* A failure — no network, box not running, channel not imported, a malformed
* body — is a {@code null} return, so a fallback source can be tried in turn.
*/
public interface TreeSource {

/**
* One level of the tree rooted at {@code nodeId}, with its direct children.
*
* @return the subtree, or {@code null} when this source could not serve it
*/
TopicNode fetchTree(String nodeId);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* ============================================================================
* Name : FallbackTreeSourceTest.java
* Author : AppDevForAll
* Copyright : Copyright (c) 2026 AppDevForAll
* Description : Unit tests for the local-first tree routing. Pure JVM (ADFA-5094).
* ============================================================================
*/
package org.iiab.controller.kolibri.data;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;

import org.iiab.controller.kolibri.domain.TopicNode;
import org.junit.Test;

/**
* The routing that lets the box-served tree win and Studio cover the miss.
*
* <p>Three behaviours matter: a primary hit is returned without touching the
* secondary, a primary miss falls through with the same node id, and two misses
* are a miss — the null the {@code CatalogRepository} contract expects.
*/
public class FallbackTreeSourceTest {

private static final String ID = "c150ea1d69495d37b5b0ac6f017e9bfb";

/** Answers with whatever it was handed; records how it was used. */
private static final class FakeSource implements TreeSource {
final TopicNode answer;
int calls;
String asked;

FakeSource(TopicNode answer) {
this.answer = answer;
}

@Override
public TopicNode fetchTree(String nodeId) {
calls++;
asked = nodeId;
return answer;
}
}

private static TopicNode node(String title) {
return TopicNode.of(ID, title, "topic", false, 0L, 0, null);
}

@Test
public void primaryHit_returnsPrimary_andSkipsSecondary() {
TopicNode local = node("local");
FakeSource primary = new FakeSource(local);
FakeSource secondary = new FakeSource(node("studio"));

TopicNode got = new FallbackTreeSource(primary, secondary).fetchTree(ID);

assertSame("a primary hit must be returned as-is", local, got);
assertEquals(1, primary.calls);
assertEquals("secondary must not be consulted on a hit", 0, secondary.calls);
}

@Test
public void primaryMiss_fallsToSecondary_withSameId() {
FakeSource primary = new FakeSource(null);
TopicNode studio = node("studio");
FakeSource secondary = new FakeSource(studio);

TopicNode got = new FallbackTreeSource(primary, secondary).fetchTree(ID);

assertSame(studio, got);
assertEquals(1, primary.calls);
assertEquals(1, secondary.calls);
assertEquals("the fallback must ask for the same node", ID, secondary.asked);
}

@Test
public void bothMiss_returnsNull() {
FallbackTreeSource fb = new FallbackTreeSource(new FakeSource(null), new FakeSource(null));
assertNull(fb.fetchTree(ID));
}

@Test(expected = IllegalArgumentException.class)
public void nullPrimary_rejected() {
new FallbackTreeSource(null, new FakeSource(null));
}

@Test(expected = IllegalArgumentException.class)
public void nullSecondary_rejected() {
new FallbackTreeSource(new FakeSource(null), null);
}
}
Loading
Loading