diff --git a/controller/app/src/main/java/org/iiab/controller/catalog/data/CatalogRefreshScheduler.java b/controller/app/src/main/java/org/iiab/controller/catalog/data/CatalogRefreshScheduler.java index 81e1e4b7a..ca83296aa 100644 --- a/controller/app/src/main/java/org/iiab/controller/catalog/data/CatalogRefreshScheduler.java +++ b/controller/app/src/main/java/org/iiab/controller/catalog/data/CatalogRefreshScheduler.java @@ -38,17 +38,27 @@ private static Data input(String name, String manifestUrl, String basename) { .build(); } - private static Constraints connected() { + private static Constraints constraints(NetworkType netType) { return new Constraints.Builder() - .setRequiredNetworkType(NetworkType.CONNECTED) + .setRequiredNetworkType(netType) .build(); } - /** Weekly periodic refresh, enqueued once per catalog (KEEP). Safe to call on every launch. */ + /** Weekly periodic refresh over any connection. Safe to call on every launch. */ public static void scheduleWeekly(Context ctx, String name, String manifestUrl, String basename) { + scheduleWeekly(ctx, name, manifestUrl, basename, NetworkType.CONNECTED); + } + + /** + * Weekly periodic refresh, enqueued once per catalog (KEEP). Safe to call on every launch. + * {@code netType} lets a large asset ask for {@link NetworkType#UNMETERED} so it refreshes only + * on Wi-Fi and never spends the user's mobile data (ADFA-5094: the tree bundle is ~16 MB). + */ + public static void scheduleWeekly(Context ctx, String name, String manifestUrl, String basename, + NetworkType netType) { PeriodicWorkRequest req = new PeriodicWorkRequest.Builder( CatalogRefreshWorker.class, 7, TimeUnit.DAYS) - .setConstraints(connected()) + .setConstraints(constraints(netType)) .setInputData(input(name, manifestUrl, basename)) .build(); WorkManager.getInstance(ctx.getApplicationContext()) @@ -56,10 +66,20 @@ public static void scheduleWeekly(Context ctx, String name, String manifestUrl, ExistingPeriodicWorkPolicy.KEEP, req); } - /** Opportunistic one-shot; the worker's TTL gate no-ops it when still fresh. */ + /** Opportunistic one-shot over any connection; the worker's TTL gate no-ops it when fresh. */ public static void refreshNow(Context ctx, String name, String manifestUrl, String basename) { + refreshNow(ctx, name, manifestUrl, basename, NetworkType.CONNECTED); + } + + /** + * Opportunistic one-shot; the worker's TTL gate no-ops it when still fresh. {@code netType} + * constrains which connection may trigger it — {@link NetworkType#UNMETERED} keeps a large + * asset off mobile data (ADFA-5094). + */ + public static void refreshNow(Context ctx, String name, String manifestUrl, String basename, + NetworkType netType) { OneTimeWorkRequest req = new OneTimeWorkRequest.Builder(CatalogRefreshWorker.class) - .setConstraints(connected()) + .setConstraints(constraints(netType)) .setInputData(input(name, manifestUrl, basename)) .build(); WorkManager.getInstance(ctx.getApplicationContext()) diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/data/BundledTreeIndex.java b/controller/app/src/main/java/org/iiab/controller/kolibri/data/BundledTreeIndex.java new file mode 100644 index 000000000..1fbcc5a7c --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/data/BundledTreeIndex.java @@ -0,0 +1,170 @@ +/* + * ============================================================================ + * Name : BundledTreeIndex.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : Pure, in-memory index over the flat offline topic-tree bundle + * (kolibri_tree.jsonl, "topics" variant). Serves one level at a + * time, the shape TreeSource wants, without Android or I/O so it + * is unit-testable on a plain JVM (ADFA-5094). + * ============================================================================ + */ +package org.iiab.controller.kolibri.data; + +import org.iiab.controller.kolibri.domain.ChannelId; +import org.iiab.controller.kolibri.domain.TopicNode; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * The offline topic tree, flattened. + * + *

The bundle is one JSON object per line, no header — each a folder with the + * aggregates the generator measured over the whole published content DB: {@code count} + * (subtree resource count), {@code bytes} (subtree bytes), and {@code dcount}/{@code dbytes} + * (the folder's direct loose-resource leaves, folded so the bundle need not carry them). A + * row names its {@code parent}; the channel roots carry an empty parent. + * + *

Built once via {@link Builder} (fed line by line, so the ~MB file never lands in a + * single list) and then queried by node id. {@link #fetchOneLevel} returns that node with + * its direct child folders — one level, matching {@link TreeSource#fetchTree} — each child + * carrying its own aggregates so the picker shows sizes before drilling. Individual leaf + * resources are not in the bundle; the live source fills them when online. + * + *

Never throws: a malformed, duplicate, or unidentifiable line is skipped, and an + * unknown node id is a {@code null} return. + */ +public final class BundledTreeIndex { + + /** A folder row, ids already normalised. */ + private static final class Row { + final String id; + final String title; + final String kind; + final int count; + final long bytes; + final int dcount; + final long dbytes; + + Row(String id, String title, String kind, int count, long bytes, int dcount, long dbytes) { + this.id = id; + this.title = title; + this.kind = kind; + this.count = count; + this.bytes = bytes; + this.dcount = dcount; + this.dbytes = dbytes; + } + } + + private final Map byId; + private final Map> childrenByParent; + + private BundledTreeIndex(Map byId, Map> childrenByParent) { + this.byId = byId; + this.childrenByParent = childrenByParent; + } + + /** How many folders the index holds. */ + public int size() { + return byId.size(); + } + + /** + * The node at {@code nodeId} with its direct child folders, or {@code null} when the + * bundle does not carry that node. Children are one level deep (no grandchildren). + */ + public TopicNode fetchOneLevel(String nodeId) { + String id = ChannelId.normalise(nodeId); + if (id == null) { + return null; + } + Row self = byId.get(id); + if (self == null) { + return null; + } + List childRows = childrenByParent.get(id); + List kids = new ArrayList<>(); + if (childRows != null) { + for (Row c : childRows) { + TopicNode child = TopicNode.fromBundle( + c.id, c.title, c.kind, c.bytes, c.count, c.dcount, c.dbytes, null); + if (child != null) { + kids.add(child); + } + } + } + return TopicNode.fromBundle( + self.id, self.title, self.kind, self.bytes, self.count, self.dcount, self.dbytes, kids); + } + + public static Builder builder() { + return new Builder(); + } + + /** Accumulates rows line by line; see {@link #add}. */ + public static final class Builder { + private final Map byId = new HashMap<>(); + private final Map> childrenByParent = new LinkedHashMap<>(); + private int skipped; + + /** + * Feeds one JSONL line. Blank lines are ignored; a line that will not parse, carries + * no usable id, or repeats an id already seen is counted in {@link #skipped()} and + * dropped. Returns {@code this} for chaining. + */ + public Builder add(String line) { + if (line == null) { + return this; + } + String t = line.trim(); + if (t.isEmpty()) { + return this; + } + try { + JSONObject o = new JSONObject(t); + String id = ChannelId.normalise(o.optString("id", "")); + if (id == null || byId.containsKey(id)) { + skipped++; + return this; + } + String parent = ChannelId.normalise(o.optString("parent", "")); + String parentKey = parent == null ? "" : parent; // roots have no parent + Row r = new Row(id, + o.optString("title", ""), + o.optString("kind", ""), + Math.max(0, o.optInt("count", 0)), + Math.max(0L, o.optLong("bytes", 0L)), + Math.max(0, o.optInt("dcount", 0)), + Math.max(0L, o.optLong("dbytes", 0L))); + byId.put(id, r); + List siblings = childrenByParent.get(parentKey); + if (siblings == null) { + siblings = new ArrayList<>(); + childrenByParent.put(parentKey, siblings); + } + siblings.add(r); + } catch (Exception badLine) { + skipped++; + } + return this; + } + + /** Lines dropped so far. */ + public int skipped() { + return skipped; + } + + public BundledTreeIndex build() { + return new BundledTreeIndex( + Collections.unmodifiableMap(byId), + Collections.unmodifiableMap(childrenByParent)); + } + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/data/BundledTreeSource.java b/controller/app/src/main/java/org/iiab/controller/kolibri/data/BundledTreeSource.java new file mode 100644 index 000000000..4832e1339 --- /dev/null +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/data/BundledTreeSource.java @@ -0,0 +1,127 @@ +/* + * ============================================================================ + * Name : BundledTreeSource.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : Serves the Kolibri topic tree from the flat bundle shipped in + * the APK (kolibri_tree.jsonl), preferring a newer copy pulled + * from Cloudflare. The offline floor for tree browsing: it answers + * when neither the box nor Studio can (ADFA-5094). + * ============================================================================ + */ +package org.iiab.controller.kolibri.data; + +import android.content.Context; +import android.util.Log; + +import org.iiab.controller.catalog.data.CatalogOverlay; +import org.iiab.controller.kolibri.domain.TopicNode; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +/** + * The topic tree bundled with the app, as a {@link TreeSource}. + * + *

Mirrors {@link BundledCatalogSource}: JSON Lines, one folder per line (no header), + * parsed once into a {@link BundledTreeIndex} and cached for the process — the file does + * not change while the app runs, and a pulled Cloudflare overlay is preferred over the APK + * asset, picked up by the same mtime check. + * + *

Unlike the box- and Studio-backed sources, this one is offline and holds the whole + * (topics-only) tree, so it is the last fallback: when the box has not imported a + * channel and there is no internet, this still lets the user browse what a channel contains. + * Individual leaf resources are not in the bundle — a mixed level shows the folder's loose + * aggregate, and the live source fills the leaves when online. + * + *

Blocking; call from an IO thread. Never throws (the {@link TreeSource} contract): a + * missing asset or unknown node id is a {@code null} return, so a caller can move on. + */ +public final class BundledTreeSource implements TreeSource { + + private static final String TAG = "K2Go-Kolibri"; + // ADFA-5094: also the overlay basename — CatalogRepositoryImpl points the tree refresh worker + // at this same name, so the worker writes the overlay exactly where this source looks for it. + static final String ASSET = "kolibri_tree.jsonl"; + + private static volatile BundledTreeIndex cachedIndex; + // -1 = not loaded, 0 = APK asset, >0 = the pulled overlay's lastModified. + private static volatile long cachedOverlayMtime = -1L; + + private final Context appContext; + + public BundledTreeSource(Context context) { + this.appContext = context.getApplicationContext(); + } + + @Override + public TopicNode fetchTree(String nodeId) { + reloadIfOverlayChanged(); + BundledTreeIndex idx = load(); + return idx == null ? null : idx.fetchOneLevel(nodeId); + } + + /** Drops the cache. For tests and for the in-place tree refresh (ADFA-5094). */ + public static void invalidate() { + cachedIndex = null; + cachedOverlayMtime = -1L; + } + + /** + * Pick up a freshly pulled overlay (or its removal) without an explicit callback: if the + * overlay file's mtime differs from what the cache was loaded from, drop the cache so the + * next {@link #load()} reads the current source. + */ + private void reloadIfOverlayChanged() { + if (cachedIndex == null) { + return; // not loaded yet; load() picks the source + } + File overlay = CatalogOverlay.file(appContext, ASSET); + long mtime = overlay.exists() ? overlay.lastModified() : 0L; + if (mtime != cachedOverlayMtime) { + invalidate(); + } + } + + private BundledTreeIndex load() { + if (cachedIndex != null) { + return cachedIndex; + } + synchronized (BundledTreeSource.class) { + if (cachedIndex != null) { + return cachedIndex; + } + BundledTreeIndex.Builder builder = BundledTreeIndex.builder(); + + // Prefer the pulled overlay over the APK asset when it is present. + File overlay = CatalogOverlay.file(appContext, ASSET); + boolean useOverlay = overlay.exists(); + long mtime = useOverlay ? overlay.lastModified() : 0L; + + try (InputStream is = useOverlay + ? new FileInputStream(overlay) : appContext.getAssets().open(ASSET); + BufferedReader r = new BufferedReader( + new InputStreamReader(is, StandardCharsets.UTF_8))) { + String line; + while ((line = r.readLine()) != null) { + builder.add(line); + } + } catch (Exception e) { + // A missing asset is a build problem, not a runtime one, but it must not take + // the app down: log and serve an empty tree, so the caller falls through. + Log.w(TAG, "bundled tree unavailable: " + e.getMessage()); + } + + if (builder.skipped() > 0) { + Log.w(TAG, "bundled tree: skipped " + builder.skipped() + " unusable line(s)"); + } + cachedIndex = builder.build(); + cachedOverlayMtime = mtime; + return cachedIndex; + } + } +} diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/data/CatalogRepositoryImpl.java b/controller/app/src/main/java/org/iiab/controller/kolibri/data/CatalogRepositoryImpl.java index 6f4d1403d..3174a9b79 100644 --- a/controller/app/src/main/java/org/iiab/controller/kolibri/data/CatalogRepositoryImpl.java +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/data/CatalogRepositoryImpl.java @@ -37,20 +37,39 @@ public final class CatalogRepositoryImpl implements CatalogRepository { // from, so the worker writes it exactly where the source looks (they must never drift). private static final String BASENAME = BundledCatalogSource.ASSET; + // ADFA-5094: the offline topic-tree bundle is refreshed the same way, from its own manifest, + // overlaying its own APK asset. A separate name so the two refreshes never collide. + private static final String TREE_CATALOG = "kolibri-tree"; + private static final String TREE_MANIFEST_URL = + "https://k2go-download.appdevforall.org/catalogs/kolibri-tree.manifest.json"; + private static final String TREE_BASENAME = BundledTreeSource.ASSET; + private final BundledCatalogSource bundled; private final TreeSource tree; public CatalogRepositoryImpl(Context context) { // 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. + // metadata is imported), then Studio when online, and finally the bundled tree — the + // offline floor that lets the user browse a channel even with the box unimported and no + // internet. Live sources win when they can answer, so the bundle is consulted last. this(new BundledCatalogSource(context), - new FallbackTreeSource(new LocalTreeSource(), new StudioTreeSource())); + new FallbackTreeSource(new LocalTreeSource(), + new FallbackTreeSource(new StudioTreeSource(), new BundledTreeSource(context)))); // 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( context, CATALOG, MANIFEST_URL, BASENAME); org.iiab.controller.catalog.data.CatalogRefreshScheduler.refreshNow( context, CATALOG, MANIFEST_URL, BASENAME); + // The tree bundle refreshes on the same cadence, but only on Wi-Fi (UNMETERED): it is ~16 MB + // against the catalog's ~83 KB, and the APK asset is a working floor, so a metered pull is + // not worth the user's mobile data. + org.iiab.controller.catalog.data.CatalogRefreshScheduler.scheduleWeekly( + context, TREE_CATALOG, TREE_MANIFEST_URL, TREE_BASENAME, + androidx.work.NetworkType.UNMETERED); + org.iiab.controller.catalog.data.CatalogRefreshScheduler.refreshNow( + context, TREE_CATALOG, TREE_MANIFEST_URL, TREE_BASENAME, + androidx.work.NetworkType.UNMETERED); } /** For tests and for pointing the tree source elsewhere (e.g. a local-first composite). */ diff --git a/controller/app/src/main/java/org/iiab/controller/kolibri/domain/TopicNode.java b/controller/app/src/main/java/org/iiab/controller/kolibri/domain/TopicNode.java index ad24a8db9..eb9bc48fd 100644 --- a/controller/app/src/main/java/org/iiab/controller/kolibri/domain/TopicNode.java +++ b/controller/app/src/main/java/org/iiab/controller/kolibri/domain/TopicNode.java @@ -49,11 +49,14 @@ public final class TopicNode { private final long subtreeBytes; private final boolean subtreeSizeKnown; private final int descendantCount; + private final int looseResourceCount; + private final long looseResourceBytes; private final List children; private TopicNode(String id, String title, String kind, boolean leaf, long ownBytes, long subtreeBytes, boolean subtreeSizeKnown, - int descendantCount, List children) { + int descendantCount, int looseResourceCount, long looseResourceBytes, + List children) { this.id = id; this.title = title; this.kind = kind; @@ -62,6 +65,8 @@ private TopicNode(String id, String title, String kind, boolean leaf, this.subtreeBytes = subtreeBytes; this.subtreeSizeKnown = subtreeSizeKnown; this.descendantCount = descendantCount; + this.looseResourceCount = looseResourceCount; + this.looseResourceBytes = looseResourceBytes; this.children = children; } @@ -132,6 +137,52 @@ public static TopicNode of(String rawId, String title, String kind, boolean leaf kind == null ? "" : kind.trim(), leaf, own, total, known, Math.max(0, descendantCount), + 0, 0L, + Collections.unmodifiableList(kids)); + } + + /** + * Builds a topic (folder) from a precomputed bundle row (ADFA-5094). + * + *

Unlike {@link #of}, the subtree size and count are given, not summed + * from children: the offline bundle is flat and served one level at a time, and the + * aggregates were computed by the generator over the whole published content DB, so + * a folder can report its true size before any child is fetched. {@code subtreeBytes} + * is therefore always {@link #hasSubtreeSize() known}. + * + *

The bundle keeps only folders; a folder's direct loose leaf resources + * are folded into {@code looseResourceCount}/{@code looseResourceBytes}, so a mixed + * level can show "N resources here" without carrying leaves the bundle omits. The live + * source (Studio / box) fills those individual leaves when online. + * + * @param descendantCount the subtree resource count the generator measured + * @return the node, or {@code null} when {@code rawId} is not a valid node id + */ + public static TopicNode fromBundle(String rawId, String title, String kind, + long subtreeBytes, int descendantCount, + int looseResourceCount, long looseResourceBytes, + List children) { + String id = ChannelId.normalise(rawId); + if (id == null) { + return null; + } + List kids = new ArrayList<>(); + if (children != null) { + for (TopicNode c : children) { + if (c != null) { + kids.add(c); + } + } + } + return new TopicNode(id, + title == null ? "" : title.trim(), + kind == null ? "" : kind.trim(), + false, // a bundle row is always a folder + 0L, // topics carry no own files beyond artwork + Math.max(0L, subtreeBytes), true, // known: the generator measured it over the DB + Math.max(0, descendantCount), + Math.max(0, looseResourceCount), + Math.max(0L, looseResourceBytes), Collections.unmodifiableList(kids)); } @@ -179,6 +230,19 @@ public int descendantCount() { return descendantCount; } + /** + * Count of loose leaf resources directly under this folder — the bundle's per-level + * aggregate (ADFA-5094). 0 for nodes not built from the bundle, or a folder with none. + */ + public int looseResourceCount() { + return looseResourceCount; + } + + /** Bytes of those loose leaf resources. 0 when none or not from the bundle. */ + public long looseResourceBytes() { + return looseResourceBytes; + } + /** Direct children, in source order. Unmodifiable, never null. */ public List children() { return children; diff --git a/controller/app/src/test/java/org/iiab/controller/kolibri/data/BundledTreeIndexTest.java b/controller/app/src/test/java/org/iiab/controller/kolibri/data/BundledTreeIndexTest.java new file mode 100644 index 000000000..3e8f5a4ab --- /dev/null +++ b/controller/app/src/test/java/org/iiab/controller/kolibri/data/BundledTreeIndexTest.java @@ -0,0 +1,86 @@ +package org.iiab.controller.kolibri.data; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.iiab.controller.kolibri.domain.TopicNode; +import org.junit.Test; + +/** + * Unit tests for {@link BundledTreeIndex} — the flat offline tree served one level at a + * time. Pure JVM (real org.json on the test classpath), no Android. (ADFA-5094) + */ +public class BundledTreeIndexTest { + + private static final String ROOT = "c150ea1d69495d37b5b0ac6f017e9bfb"; + private static final String A = "23a7dc9c73635cd2abbd3e8aab13c3ca"; + private static final String B = "a3eac3983b085e1594eeb18d1f173260"; + private static final String D = "0123456789abcdef0123456789abcdef"; + private static final String ABSENT = "ffffffffffffffffffffffffffffffff"; + + private static String row(String id, String parent, String title, int count, long bytes, + int dcount, long dbytes) { + return "{\"id\":\"" + id + "\",\"parent\":\"" + parent + "\",\"title\":\"" + title + + "\",\"kind\":\"topic\",\"count\":" + count + ",\"bytes\":" + bytes + + ",\"dcount\":" + dcount + ",\"dbytes\":" + dbytes + "}"; + } + + private static BundledTreeIndex sample() { + return BundledTreeIndex.builder() + .add(row(ROOT, "", "Root", 15, 1500L, 0, 0L)) + .add(row(A, ROOT, "Alpha", 10, 1000L, 2, 50L)) + .add(row(B, ROOT, "Beta", 5, 500L, 1, 20L)) + .add(row(D, A, "Delta", 0, 0L, 0, 0L)) + .build(); + } + + @Test + public void servesOneLevelWithChildAggregates() { + BundledTreeIndex idx = sample(); + assertEquals(4, idx.size()); + + TopicNode root = idx.fetchOneLevel(ROOT); + assertNotNull(root); + assertEquals(2, root.children().size()); // A and B, in file order + assertEquals(1500L, root.subtreeBytes()); + assertTrue(root.hasSubtreeSize()); + + TopicNode alpha = root.children().get(0); + assertEquals(A, alpha.id()); + assertEquals(1000L, alpha.subtreeBytes()); + assertEquals(10, alpha.descendantCount()); + assertEquals(2, alpha.looseResourceCount()); + assertEquals(50L, alpha.looseResourceBytes()); + assertTrue("children come one level at a time", alpha.children().isEmpty()); + } + + @Test + public void drillsIntoAChild() { + TopicNode alpha = sample().fetchOneLevel(A); + assertNotNull(alpha); + assertEquals(1, alpha.children().size()); + assertEquals(D, alpha.children().get(0).id()); + } + + @Test + public void unknownNodeIsNull() { + assertNull(sample().fetchOneLevel(ABSENT)); + assertNull(sample().fetchOneLevel("not-a-node-id")); + assertNull(sample().fetchOneLevel(null)); + } + + @Test + public void skipsBlankMalformedAndDuplicateLines() { + BundledTreeIndex.Builder b = BundledTreeIndex.builder() + .add(row(ROOT, "", "Root", 1, 1L, 0, 0L)) + .add("") // blank: ignored, not counted + .add("{not json") // malformed: skipped + .add(row(ROOT, "", "Dup", 9, 9L, 0, 0L)); // duplicate id: skipped + BundledTreeIndex idx = b.build(); + assertEquals(1, idx.size()); + assertEquals(2, b.skipped()); // malformed + duplicate + assertEquals(1L, idx.fetchOneLevel(ROOT).subtreeBytes()); // first row won + } +} diff --git a/controller/app/src/test/java/org/iiab/controller/kolibri/domain/TopicNodeTest.java b/controller/app/src/test/java/org/iiab/controller/kolibri/domain/TopicNodeTest.java index ccbe73d5d..986c0f5e8 100644 --- a/controller/app/src/test/java/org/iiab/controller/kolibri/domain/TopicNodeTest.java +++ b/controller/app/src/test/java/org/iiab/controller/kolibri/domain/TopicNodeTest.java @@ -146,4 +146,32 @@ public void descendantCountIsCarriedAndClamped() { assertEquals(0, TopicNode.of(ROOT, "x", "topic", false, 0L, -3, null) .descendantCount()); } + + // ADFA-5094: the offline bundle is flat, so a folder must report the size the + // generator measured over the whole DB — not a sum of the one level it carries. + @Test + public void fromBundleTrustsGivenAggregatesNotChildren() { + TopicNode child = TopicNode.fromBundle(A, "Sub", "topic", 0L, 0, 0, 0L, null); + TopicNode t = TopicNode.fromBundle(ROOT, "Folder", "topic", + 5_000_000L, 42, 3, 120L, Collections.singletonList(child)); + assertTrue(t.isTopic()); + assertFalse(t.isLeaf()); + assertTrue(t.hasSubtreeSize()); + assertEquals(5_000_000L, t.subtreeBytes()); + assertEquals(42, t.descendantCount()); + assertEquals(3, t.looseResourceCount()); + assertEquals(120L, t.looseResourceBytes()); + assertEquals(1, t.children().size()); + } + + @Test + public void fromBundleClampsNegativesAndRejectsBadId() { + TopicNode t = TopicNode.fromBundle(ROOT, "x", "topic", -1L, -5, -2, -9L, null); + assertEquals(0L, t.subtreeBytes()); + assertTrue(t.hasSubtreeSize()); + assertEquals(0, t.descendantCount()); + assertEquals(0, t.looseResourceCount()); + assertEquals(0L, t.looseResourceBytes()); + assertNull(TopicNode.fromBundle("not-an-id", "x", "topic", 0L, 0, 0, 0L, null)); + } }