Cache channel listings for search
Rolling Release / build (push) Successful in 1m46s
Rolling Release / publish (push) Successful in 9s

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 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Opus 5.5 committed 2026-12-01 05:04:06 -08:00
1 parent 8f202290b9
commit 47a80fad04
9 files changed
+330 -55

No files matched your search

+2
View File
@@ -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 {
+35 -13
View File
@@ -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
+194
View File
@@ -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))
}
+19 -4
View File
@@ -41,7 +41,7 @@ let usage : String =
#| orbit list [-g] installed global packages
#| orbit info [channel::]<name> installed package details (local only)
#| orbit versions <name> 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 <dir>")
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`)")
}
+2
View File
@@ -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",
+12 -36
View File
@@ -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)
}
}
}
+44 -2
View File
@@ -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, [])