From 47a80fad04f6827aad920dcb184d498a15d58f35 Mon Sep 17 00:00:00 2001 From: nandithebull Date: Tue, 1 Dec 2026 05:04:06 -0800 Subject: [PATCH] Cache channel listings for search Search keeps each channel's list for an hour, so a repeat needs no network, and uses the old copy with a warning if the registry fails. `--refresh` skips the cache; publish, index, login and logout drop it. A test command no longer writes to stdout, where it could corrupt the test runner's results. Planning: bnbr1 Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + ...1-cache-channel-indexes-for-fast-search.md | 20 ++ src/main/auth.mbt | 2 + src/main/index.mbt | 48 +++-- src/main/index_cache.mbt | 194 ++++++++++++++++++ src/main/main.mbt | 23 ++- src/main/moon.pkg | 2 + src/main/ops.mbt | 48 ++--- src/main/registry_wbtest.mbt | 46 ++++- 9 files changed, 330 insertions(+), 55 deletions(-) create mode 100644 planning/bnbr1-cache-channel-indexes-for-fast-search.md create mode 100644 src/main/index_cache.mbt diff --git a/README.md b/README.md index 7c22199..e4b986c 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,7 @@ The manifest has `artifactType` `application/vnd.latha.orbit.index.v1` and one J - `orbit publish` adds the package to the index, and creates the index from the catalog if there is none. `--no-index` skips this. - `orbit index [--channel ]` rebuilds it from the catalog. Use it after deleting a package, or if two publishes ran at once and one entry was lost. On a registry without a catalog, name the packages: `orbit index mytool othertool`. - Installs and version lookups never read the index, so a stale one can't change what is installed. +- Search keeps a copy of each channel's list in `~/.orbit/cache/indexes/` and uses it for an hour without touching the network. After that it fetches the list again, or uses the old copy with a warning if the registry can't be reached. `orbit search --refresh` fetches now. Your own `publish`, `index`, `login` and `logout` drop the copies they affect. A channel without an index is cached too, if it has at most 100 repositories. - The index is built with the publisher's login. On a registry where packages in one namespace can be private while others are public, a public index reveals the private names, descriptions and versions. Gitea sets visibility per owner, so this doesn't apply there. ## Usage @@ -248,6 +249,7 @@ src/main/ model.mbt orbit.json / state.json / config.json (+ tests) registry.mbt OCI registry ops: tags, resolve, cached manifests, fetch, publish, login index.mbt channel index: build, publish, read (+ tests) + index_cache.mbt local copies of channel listings for search (+ tests) solver.mbt lazy Resolvo-style CDCL SAT solver & UNSAT explainer (+ tests) ops.mbt SAT-backed global install/upgrade, remove/rollback/gc/search project.mbt orbit.toml, orbit.lock, .orbit/ environments, project CLI (+ tests) diff --git a/planning/bnbr1-cache-channel-indexes-for-fast-search.md b/planning/bnbr1-cache-channel-indexes-for-fast-search.md new file mode 100644 index 0000000..2899bdd --- /dev/null +++ b/planning/bnbr1-cache-channel-indexes-for-fast-search.md @@ -0,0 +1,20 @@ +--- +data: + priority: normal + status: done + tags: + - search + type: feature +id: bnbr1 +title: Cache channel indexes for fast search +--- +`orbit search` reads every channel over the network each time (about 8 s for two channels). + +Acceptance criteria: + +- A repeated search of the configured channels needs no network, for channels with an index and for small ones listed from the catalog. +- A copy older than an hour is fetched again; if that fails, it is used with a warning. +- `orbit search --refresh` skips the cache. Publishing, indexing, login and logout drop it. +- Installs and version lookups still never read it. + +Outcome: copies live in `/cache/indexes/` (`src/main/index_cache.mbt`). A repeated search takes 3 ms instead of about 12 s. Channels with over 100 repositories and no index are not cached. diff --git a/src/main/auth.mbt b/src/main/auth.mbt index 01cb1cf..704ac80 100644 --- a/src/main/auth.mbt +++ b/src/main/auth.mbt @@ -386,6 +386,7 @@ async fn cmd_login( verify_login(host, plain_http, creds) }) save_creds(orbit_root(), host, creds) + drop_cached_indexes(orbit_root()) println("Login succeeded for \{host}") } @@ -395,6 +396,7 @@ async fn cmd_logout(raw_host : String) -> Unit raise OrbitError { if host == "" { raise OrbitError("invalid registry host '\{raw_host}'") } + drop_cached_indexes(orbit_root()) if remove_creds(orbit_root(), host) { println("Removed credentials for \{host}") } else { diff --git a/src/main/index.mbt b/src/main/index.mbt index ad711f2..40ae6bf 100644 --- a/src/main/index.mbt +++ b/src/main/index.mbt @@ -23,7 +23,7 @@ struct IndexEntry { } ///| -fn index_json(entries : Array[IndexEntry]) -> String { +fn index_object(entries : Array[IndexEntry]) -> Map[String, Json] { let sorted = entries.copy() sorted.sort_by(fn(a, b) { a.name.lexical_compare(b.name) }) let pkgs : Array[Json] = [] @@ -37,7 +37,12 @@ fn index_json(entries : Array[IndexEntry]) -> String { } let top : Map[String, Json] = Map([]) top["packages"] = Json::array(pkgs) - Json::object(top).stringify() + "\n" + top +} + +///| +fn index_json(entries : Array[IndexEntry]) -> String { + Json::object(index_object(entries)).stringify() + "\n" } ///| @@ -204,12 +209,15 @@ fn find_entry(entries : Array[IndexEntry], name : String) -> IndexEntry? { } ///| -/// Read every named package. One that can't be read keeps its old entry. -async fn build_index( +/// Read every named package. Returns those found, and the names that couldn't +/// be read with the reason. +async fn read_entries( ch : Channel, names : Array[String], - old : Array[IndexEntry], -) -> Array[IndexEntry] raise OrbitError { +) -> (Array[IndexEntry], Array[(String, String)]) raise OrbitError { + if names.length() == 0 { + return ([], []) + } let results : Array[(String, Result[IndexEntry?, String])] = [] with_spinner("Reading \{names.length()} repositories in \{ch.name}", () => { @async.with_task_group(group => { @@ -229,17 +237,31 @@ async fn build_index( }) }) let out : Array[IndexEntry] = [] + let failed : Array[(String, String)] = [] for r in results { match r { (_, Ok(Some(e))) => out.push(e) (_, Ok(None)) => () - (n, Err(msg)) => { - println("warning: cannot read '\{n}': \{msg}") - match find_entry(old, n) { - Some(e) => out.push(e) - None => () - } - } + (n, Err(msg)) => failed.push((n, msg)) + } + } + (out, failed) +} + +///| +/// Read every named package. One that can't be read keeps its old entry. +async fn build_index( + ch : Channel, + names : Array[String], + old : Array[IndexEntry], +) -> Array[IndexEntry] raise OrbitError { + let (out, failed) = read_entries(ch, names) + for f in failed { + let (n, msg) = f + println("warning: cannot read '\{n}': \{msg}") + match find_entry(old, n) { + Some(e) => out.push(e) + None => () } } out diff --git a/src/main/index_cache.mbt b/src/main/index_cache.mbt new file mode 100644 index 0000000..9480827 --- /dev/null +++ b/src/main/index_cache.mbt @@ -0,0 +1,194 @@ +// Local copies of channel listings, so that a repeated search needs no network. +// Installs and version lookups never read them. + +///| +/// How long a copy is used before it is fetched again. +const INDEX_TTL_MS : UInt64 = 3_600_000 + +///| +/// A channel without an index is read whole, so that it can be cached, only up +/// to this many repositories. Beyond that just the matching names are read. +const MAX_LISTED_REPOS : Int32 = 100 + +///| +fn index_cache_dir(root : String) -> String { + root + "/cache/indexes" +} + +///| +/// Copies belong to a URL, not a channel name, which can be repointed. +fn index_cache_path(root : String, ch : Channel) -> String { + let key = channel_scheme(ch) + "://" + ch.url + index_cache_dir(root) + + "/" + + drop_chars(sha256_digest(utf8_encode(key)), 7) + + ".json" +} + +///| +struct CachedIndex { + entries : Array[IndexEntry] + fetched : UInt64 // milliseconds since the epoch +} + +///| +fn is_fresh(c : CachedIndex, now : UInt64) -> Bool { + c.fetched <= now && now - c.fetched < INDEX_TTL_MS +} + +///| +/// None if there is no usable copy. +async fn read_cached_index(root : String, ch : Channel) -> CachedIndex? noraise { + let text = match read_text(index_cache_path(root, ch)) { + Some(t) => t + None => return None + } + try { + let top = parse_object(text, "cached index") + let fetched = @string.parse_uint64(jstr(top, "fetched", "")) + Some(CachedIndex::{ entries: parse_index(text), fetched }) + } catch { + _ => None + } +} + +///| +/// Failing to write a copy only costs speed. It may name private packages, so +/// only the user can read it. +async fn write_cached_index( + root : String, + ch : Channel, + entries : Array[IndexEntry], + now : UInt64, +) -> Unit noraise { + try { + @fs.mkdir(index_cache_dir(root), recursive=true, allow_exist=true) + let top = index_object(entries) + top["fetched"] = Json::string(now.to_string()) + write_secret_atomic( + index_cache_path(root, ch), + Json::object(top).stringify() + "\n", + ) + } catch { + _ => () + } +} + +///| +/// Forget the copy of a channel that was just published to. +async fn drop_cached_index(root : String, ch : Channel) -> Unit noraise { + @fs.remove(index_cache_path(root, ch)) catch { + _ => () + } +} + +///| +/// Forget every copy, as a login or logout changes what may be listed. +async fn drop_cached_indexes(root : String) -> Unit noraise { + @fs.rmdir(index_cache_dir(root), recursive=true, allow_missing=true) catch { + _ => () + } +} + +///| +/// A channel's packages for search, which still has to match `term`: a fresh +/// copy, else its index, else the registry's catalog. If the registry fails, an +/// old copy is used. None means the channel couldn't be listed. +async fn channel_listing( + root : String, + ch : Channel, + term : String, + refresh : Bool, +) -> Array[IndexEntry]? noraise { + let now = @env.now() + let cached = read_cached_index(root, ch) + if !refresh && cached is Some(c) && is_fresh(c, now) { + return Some(c.entries) + } + let mut index_failed = false + try { + match load_index(ch) { + Some(entries) => { + write_cached_index(root, ch, entries, now) + return Some(entries) + } + None => () + } + } catch { + OrbitError(msg) => { + index_failed = true + if cached is Some(c) { + println( + "warning: cannot refresh channel '\{ch.name}', using its saved index: \{msg}", + ) + return Some(c.entries) + } + println("warning: cannot read index of channel '\{ch.name}': \{msg}") + } + } + try { + let (entries, complete) = list_catalog(ch, term) + if complete && !index_failed { + write_cached_index(root, ch, entries, now) + } + Some(entries) + } catch { + OrbitError(msg) => + match cached { + Some(c) => { + println( + "warning: cannot refresh channel '\{ch.name}', using its saved list: \{msg}", + ) + Some(c.entries) + } + None => { + println("warning: cannot list channel '\{ch.name}': \{msg}") + None + } + } + } +} + +///| +/// Read a channel from the registry's catalog, and whether the result is +/// complete: every package, all of them readable. +async fn list_catalog( + ch : Channel, + term : String, +) -> (Array[IndexEntry], Bool) raise OrbitError { + // A name with "/" is a nested channel namespace (e.g. example/greet under + // main), not a package name that `orbit install` could use. + let all = list_repos(ch).filter(fn(r) { valid_name(r) && r != INDEX_NAME }) + if all.length() <= MAX_LISTED_REPOS { + let (entries, failed) = read_entries(ch, all) + for f in failed { + println("warning: cannot read '\{f.0}': \{f.1}") + } + return (entries, failed.length() == 0) + } + let names = all.filter(fn(r) { contains_str(r, term) }) + let found = find_orbit_repos(ch, names) + let entries : Array[IndexEntry] = [] + for i, name in names { + match found[i] { + Some(info) => + entries.push(IndexEntry::{ + name, + version: info.version, + description: info.description, + versions: [], + }) + None => () + } + } + (entries, false) +} + +///| +test "a copy is fresh for an hour, and never from the future" { + let c = CachedIndex::{ entries: [], fetched: 1000 } + assert_true(is_fresh(c, 1000)) + assert_true(is_fresh(c, 1000 + INDEX_TTL_MS - 1)) + assert_false(is_fresh(c, 1000 + INDEX_TTL_MS)) + assert_false(is_fresh(c, 999)) +} diff --git a/src/main/main.mbt b/src/main/main.mbt index b08e8f6..de873c4 100644 --- a/src/main/main.mbt +++ b/src/main/main.mbt @@ -41,7 +41,7 @@ let usage : String = #| orbit list [-g] installed global packages #| orbit info [channel::] installed package details (local only) #| orbit versions published versions - #| orbit search [term] list packages (channel index or catalog API) + #| orbit search [--refresh] [term] list packages (cached for an hour) #| orbit gc delete unused builds from the store #| orbit env [-g] print the PATH line for your shell #| @@ -286,15 +286,22 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError { } "publish" => { need(pos, 1, "publish ") - let ch = find_channel(load_ctx(), publish_to) + let ctx = load_ctx() + let ch = find_channel(ctx, publish_to) publish( ch, pos[0], !flags.contains("--no-latest"), update_index=!flags.contains("--no-index"), ) + drop_cached_index(ctx.root, ch) + } + "index" => { + let ctx = load_ctx() + let ch = find_channel(ctx, publish_to) + cmd_index(ch, pos) + drop_cached_index(ctx.root, ch) } - "index" => cmd_index(find_channel(load_ctx(), publish_to), pos) "install" => match resolve_project_or_none(force_global, manifest_path) { Some(mf) => @@ -345,7 +352,15 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError { cmd_versions(load_ctx(), pos[0]) } "search" => - cmd_search(load_ctx(), if pos.length() > 0 { pos[0] } else { "" }) + cmd_search( + load_ctx(), + if pos.length() > 0 { + pos[0] + } else { + "" + }, + refresh=flags.contains("--refresh"), + ) "gc" => cmd_gc(load_ctx()) _ => raise OrbitError("unknown command '\{cmd}' (try `orbit help`)") } diff --git a/src/main/moon.pkg b/src/main/moon.pkg index e339af8..505103f 100644 --- a/src/main/moon.pkg +++ b/src/main/moon.pkg @@ -1,6 +1,8 @@ import { "latha/orbit/kernel", + "moonbitlang/core/env", "moonbitlang/core/json", + "moonbitlang/core/string", "moonbitlang/core/encoding/base64", "moonbitlang/core/encoding/hex", "moonbitlang/core/encoding/percent", diff --git a/src/main/ops.mbt b/src/main/ops.mbt index d4af5bc..cafedae 100644 --- a/src/main/ops.mbt +++ b/src/main/ops.mbt @@ -879,7 +879,11 @@ fn printable(s : String) -> String { } ///| -async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { +async fn cmd_search( + ctx : Ctx, + term : String, + refresh? : Bool = false, +) -> Unit raise OrbitError { let rows : Array[Array[String]] = [ ["PACKAGE", "CHANNEL", "VERSION", "DESCRIPTION"], ] @@ -894,43 +898,15 @@ async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { } let term_lower = ascii_lower(term) for ch in ctx.channels { - // Without a usable index, ask the registry's catalog. - let index = load_index(ch) catch { - OrbitError(msg) => { - println("warning: cannot read index of channel '\{ch.name}': \{msg}") - None - } - } - if index is Some(entries) { - listed = listed + 1 - for e in entries { - if contains_str(e.name, term_lower) || - contains_str(ascii_lower(e.description), term_lower) { - add(e.name, ch, e.version, e.description) - } - } - continue - } - let repos = list_repos(ch) catch { - OrbitError(msg) => { - println("warning: cannot list channel '\{ch.name}': \{msg}") - continue - } + let entries = match channel_listing(ctx.root, ch, term_lower, refresh) { + Some(es) => es + None => continue } listed = listed + 1 - let candidates : Array[String] = [] - for r in repos { - // A name with "/" is a nested channel namespace (e.g. example/greet under - // main), not a package name that `orbit install` could use. - if valid_name(r) && r != INDEX_NAME && contains_str(r, term_lower) { - candidates.push(r) - } - } - let found = find_orbit_repos(ch, candidates) - for i, r in candidates { - match found[i] { - Some(info) => add(r, ch, info.version, info.description) - None => () + for e in entries { + if contains_str(e.name, term_lower) || + contains_str(ascii_lower(e.description), term_lower) { + add(e.name, ch, e.version, e.description) } } } diff --git a/src/main/registry_wbtest.mbt b/src/main/registry_wbtest.mbt index fa0b80a..f37169a 100644 --- a/src/main/registry_wbtest.mbt +++ b/src/main/registry_wbtest.mbt @@ -749,7 +749,8 @@ async test "Pixi-style project workflow: new, add, sync --locked, run, update, r "1.0.0", Map([("lib", "^1.0")]), ["bin/app"], - script="#!/bin/sh\necho proj-app-1\n", + // Not stdout, where it would land in the test runner's results. + script="#!/bin/sh\necho proj-app-1 >&2\n", ) publish_mock_pkg( main_ch, @@ -758,7 +759,7 @@ async test "Pixi-style project workflow: new, add, sync --locked, run, update, r "2.0.0", Map([("lib", "^2.0")]), ["bin/app"], - script="#!/bin/sh\necho proj-app-2\n", + script="#!/bin/sh\necho proj-app-2 >&2\n", ) publish_mock_pkg( main_ch, @@ -940,6 +941,7 @@ async test "each channel has its own index, kept by publish and used by search" let st = new_mock_oci_state() let upload_seq = Ref(0) let catalog_gets = Ref(0) + let requests = Ref(0) let broken = Ref("") let server = @http.Server(@socket.Addr::parse("127.0.0.1:0")) @async.with_task_group(group => { @@ -948,6 +950,7 @@ async test "each channel has its own index, kept by publish and used by search" server.run_forever((req, body, conn) => { let req_bytes = body.read_all().binary() let (path, _) = strip_query(req.path) + requests.val = requests.val + 1 if path == "/v2/_catalog" { catalog_gets.val = catalog_gets.val + 1 } @@ -994,6 +997,45 @@ async test "each channel has its own index, kept by publish and used by search" ) assert_eq(catalog_gets.val, gets) + // A repeated search makes no requests; a refresh or an old copy does, and + // falls back to the copy if the registry fails. + let before_search = requests.val + let ctx = Ctx::{ root: work, channels: [a, nested], state: Map([]) } + cmd_search(ctx, "one") + assert_eq(requests.val, before_search) + cmd_search(ctx, "one", refresh=true) + assert_true(requests.val > before_search) + let saved = read_cached_index(work, a).unwrap().entries + write_cached_index(work, a, saved, 0) + broken.val = "/v2/a/" + let old = channel_listing(work, a, "", false).unwrap() + assert_eq(old.map(fn(e) { e.name }), ["one", "two"]) + assert_eq(read_cached_index(work, a).unwrap().fetched, 0) + broken.val = "" + ignore(channel_listing(work, a, "", false)) + assert_true(read_cached_index(work, a).unwrap().fetched > 0) + // A damaged copy is ignored, and copies follow the URL. + @fs.write_file( + index_cache_path(work, a), + "{", + create_mode=CreateOrTruncate, + ) + assert_true(read_cached_index(work, a) is None) + drop_cached_index(work, nested) + assert_true(read_cached_index(work, nested) is None) + + // Without an index, the catalog is cached unless a package was unreadable. + let plain = chan("plain") + publish_mock_pkg(plain, work, "five", "1.0.0", Map([]), [], update_index=false) + broken.val = "/v2/plain/five/" + assert_eq(channel_listing(work, plain, "", false).unwrap().length(), 0) + assert_true(read_cached_index(work, plain) is None) + broken.val = "" + assert_eq(channel_listing(work, plain, "x", false).unwrap()[0].name, "five") + let before_listing = requests.val + assert_eq(channel_listing(work, plain, "", false).unwrap()[0].name, "five") + assert_eq(requests.val, before_listing) + // A package that can't be read keeps its entry; a deleted one is dropped. broken.val = "/v2/a/one/" cmd_index(a, [])