From 4271a084b648951939728717b83478baf231666c Mon Sep 17 00:00:00 2001 From: nandithebull Date: Mon, 30 Nov 2026 20:48:31 -0800 Subject: [PATCH] Give each channel a package index orbit-index:latest in a channel lists its packages. Search reads it and falls back to the catalog; publish keeps it current and 'orbit index' rebuilds it. Installs never use it. Co-Authored-By: Claude Opus 5.5 --- README.md | 18 +- src/main/index.mbt | 332 +++++++++++++++++++++++++++++++++++ src/main/main.mbt | 18 +- src/main/oci.mbt | 5 +- src/main/ops.mbt | 55 ++++-- src/main/registry.mbt | 7 + src/main/registry_wbtest.mbt | 88 +++++++++- 7 files changed, 498 insertions(+), 25 deletions(-) create mode 100644 src/main/index.mbt diff --git a/README.md b/README.md index 27e1dd8..b7af1dc 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,21 @@ ship one under `files/share/doc//README.md`, as the `greet` example does. Because these are ordinary OCI artifacts, you can sign them with `cosign` or `notation` and attach SBOMs using the registry's own tooling. +### Channel index + +A channel can hold an index of its packages at `/orbit-index:latest` (the name is reserved), so `orbit search` takes two requests per channel, matches descriptions too, and needs no catalog API. Each namespace (a Gitea user or organisation) has its own index, written by whoever can publish there. A nested channel such as `nandi/example` is separate from `nandi`. Without an index, search asks the registry's catalog. + +The manifest has `artifactType` `application/vnd.latha.orbit.index.v1` and one JSON layer (`application/vnd.latha.orbit.index.v1+json`): + +```json +{"packages":[{"name":"mytool","version":"1.4.0","description":"...","versions":["1.4.0"]}]} +``` + +- `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. +- 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 ### Global environment @@ -230,6 +245,7 @@ src/main/ semver.mbt versions, relational/compound constraints, parsing over src/kernel (+ tests) 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) 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) @@ -252,4 +268,4 @@ Fixes needed for current MoonBit, kept here in case you build with an older comp - There's no lock file for concurrent runs, and no install hooks, by design. - `orbit gc` only preserves global current and rollback builds (run `orbit install` / `orbit sync` in a project to re-populate missing store entries from its `orbit.lock`). - `orbit info ` reads globally installed package details without contacting the registry. Use `orbit versions ` to check published versions. -- `search` needs the registry's catalog API (Gitea has it, also without a login). If a registry doesn't offer it, use `orbit versions `. +- `search` needs a channel index or the registry's catalog API (Gitea has it, also without a login). Otherwise use `orbit versions `. diff --git a/src/main/index.mbt b/src/main/index.mbt new file mode 100644 index 0000000..ad711f2 --- /dev/null +++ b/src/main/index.mbt @@ -0,0 +1,332 @@ +// The channel index: one OCI artifact per channel that lists its packages, so +// search needs no catalog API. Installs never use it. + +///| +/// Repository name of the index inside a channel. Not usable as a package name. +const INDEX_NAME : String = "orbit-index" + +///| +const INDEX_ARTIFACT_TYPE : String = "application/vnd.latha.orbit.index.v1" + +///| +const INDEX_MEDIA_TYPE : String = "application/vnd.latha.orbit.index.v1+json" + +///| +const EMPTY_MEDIA_TYPE : String = "application/vnd.oci.empty.v1+json" + +///| +struct IndexEntry { + name : String + version : String + description : String + versions : Array[String] // newest first +} + +///| +fn index_json(entries : Array[IndexEntry]) -> String { + let sorted = entries.copy() + sorted.sort_by(fn(a, b) { a.name.lexical_compare(b.name) }) + let pkgs : Array[Json] = [] + for e in sorted { + let o : Map[String, Json] = Map([]) + o["name"] = Json::string(e.name) + o["version"] = Json::string(e.version) + o["description"] = Json::string(e.description) + o["versions"] = strs_json(e.versions) + pkgs.push(Json::object(o)) + } + let top : Map[String, Json] = Map([]) + top["packages"] = Json::array(pkgs) + Json::object(top).stringify() + "\n" +} + +///| +fn parse_index(text : String) -> Array[IndexEntry] raise OrbitError { + let top = parse_object(text, "channel index") + let pkgs = match top.get("packages") { + Some(Json::Array(xs)) => xs + _ => raise OrbitError("channel index: expected 'packages' to be an array") + } + let out : Array[IndexEntry] = [] + for p in pkgs { + match p { + Json::Object(o) => { + let name = jstr(o, "name", "") + // Skip names that `orbit install` couldn't use. + if valid_name(name) && name != INDEX_NAME { + out.push(IndexEntry::{ + name, + version: jstr(o, "version", ""), + description: jstr(o, "description", ""), + versions: jstrs(o, "versions"), + }) + } + } + _ => () + } + } + out +} + +///| +/// The digest of the index layer, or None if the manifest isn't an index. +fn index_layer_digest(text : String) -> String? raise OrbitError { + let o = parse_object(text, "index manifest") + if jstr(o, "artifactType", "") != INDEX_ARTIFACT_TYPE { + return None + } + match o.get("layers") { + Some(Json::Array([Json::Object(l), ..])) => { + let d = jstr(l, "digest", "") + if has_prefix(d, "sha256:") { + return Some(d) + } + } + _ => () + } + raise OrbitError("index manifest has no sha256 layer") +} + +///| +/// The channel's index, or None if it has none. A 404 here only means "no +/// index", even after a rejected login, so that check is skipped. +async fn load_index(ch : Channel) -> Array[IndexEntry]? raise OrbitError { + with_spinner("Reading index of \{ch.name}", () => { + let repo = channel_repo_path(ch, INDEX_NAME) + let base = channel_base_url(ch) + "/v2/" + repo + let get = async fn(path : String, accept : String) { + oci_request( + Get, + base + path, + Map([("Accept", accept)]), + b"", + repo + ":pull", + check_login=false, + ) + } + let (resp, body) = get("/manifests/latest", MANIFEST_ACCEPT) + if is_missing_status(resp.code) { + return None + } + if resp.code < 200 || resp.code >= 300 { + raise OrbitError(format_oci_error(resp.code, resp.reason, body)) + } + let digest = match index_layer_digest(utf8_decode(body)) { + Some(d) => d + None => return None + } + let (blob_resp, blob) = get("/blobs/" + digest, "application/json") + if blob_resp.code < 200 || blob_resp.code >= 300 { + raise OrbitError( + format_oci_error(blob_resp.code, blob_resp.reason, blob), + ) + } + let actual = sha256_digest(blob) + if actual != digest { + raise OrbitError("index digest mismatch: expected \{digest}, got \{actual}") + } + Some(parse_index(utf8_decode(blob))) + }) +} + +///| +async fn push_index( + ch : Channel, + entries : Array[IndexEntry], +) -> Unit raise OrbitError { + let base = channel_base_url(ch) + let repo = channel_repo_path(ch, INDEX_NAME) + let config = b"{}" + let data = utf8_encode(index_json(entries)) + let descriptor = fn(media_type : String, bytes : Bytes) { + let o : Map[String, Json] = Map([]) + o["mediaType"] = Json::string(media_type) + o["digest"] = Json::string(sha256_digest(bytes)) + o["size"] = json_int64(bytes.length().to_int64()) + Json::object(o) + } + let ann : Map[String, Json] = Map([]) + ann["org.opencontainers.image.created"] = Json::string(utc_now()) + let manifest : Map[String, Json] = Map([]) + manifest["schemaVersion"] = json_int64(2L) + manifest["mediaType"] = Json::string(OCI_MANIFEST_MEDIA_TYPE) + manifest["artifactType"] = Json::string(INDEX_ARTIFACT_TYPE) + manifest["config"] = descriptor(EMPTY_MEDIA_TYPE, config) + manifest["layers"] = Json::array([descriptor(INDEX_MEDIA_TYPE, data)]) + manifest["annotations"] = Json::object(ann) + with_spinner("Publishing index of \{ch.name}", () => { + upload_blob_bytes(base, repo, sha256_digest(config), config) + upload_blob_bytes(base, repo, sha256_digest(data), data) + put_manifest( + base, + repo, + "latest", + utf8_encode(Json::object(manifest).stringify() + "\n"), + ) + }) +} + +///| +/// Read one package from the registry. None means it doesn't exist or isn't an +/// Orbit package; failures are errors so that they can't drop a package. +async fn read_index_entry( + ch : Channel, + name : String, +) -> IndexEntry? raise OrbitError { + let tags = match list_tags_quiet(ch, name) { + Some(ts) => ts + None => return None + } + if tags.length() == 0 { + return None + } + let tag = if tags.contains("latest") { "latest" } else { tags[0] } + match orbit_info(fetch_raw_manifest(ch, name, tag)) { + Some(info) => + Some(IndexEntry::{ + name, + version: info.version, + description: info.description, + versions: sorted_versions(tags), + }) + None => None + } +} + +///| +fn find_entry(entries : Array[IndexEntry], name : String) -> IndexEntry? { + for e in entries { + if e.name == name { + return Some(e) + } + } + None +} + +///| +/// 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 results : Array[(String, Result[IndexEntry?, String])] = [] + with_spinner("Reading \{names.length()} repositories in \{ch.name}", () => { + @async.with_task_group(group => { + let tasks : Array[@async.Task[Result[IndexEntry?, String]]] = [] + for n in names { + tasks.push( + group.spawn(() => { + try Ok(read_index_entry(ch, n)) catch { + OrbitError(msg) => Err(msg) + } + }), + ) + } + for i, t in tasks { + results.push((names[i], t.wait())) + } + }) + }) + let out : Array[IndexEntry] = [] + 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 => () + } + } + } + } + out +} + +///| +/// Rebuild a channel's index. Without names, the packages come from the +/// registry's catalog; with names, from those names and the existing index. +async fn cmd_index( + ch : Channel, + names : Array[String], +) -> Unit raise OrbitError { + let old = load_index(ch) + rebuild_index(ch, names, old) +} + +///| +async fn rebuild_index( + ch : Channel, + names : Array[String], + old : Array[IndexEntry]?, +) -> Unit raise OrbitError { + let old = old.unwrap_or([]) + let all : Array[String] = [] + let found = if names.length() == 0 { list_repos(ch) } else { names } + for n in found { + if valid_name(n) && n != INDEX_NAME && !all.contains(n) { + all.push(n) + } + } + if names.length() > 0 { + for e in old { + if !all.contains(e.name) { + all.push(e.name) + } + } + } + let entries = build_index(ch, all, old) + push_index(ch, entries) + println("indexed \{entries.length()} package(s) in \{repo_of(ch, INDEX_NAME)}") +} + +///| +/// Record a just-published package. A channel without an index gets a full one, +/// because an index with one package would hide the others from search. +/// The package is already published, so failures here are only warnings. +async fn index_published(ch : Channel, name : String) -> Unit noraise { + try { + match load_index(ch) { + None => rebuild_index(ch, [], None) + Some(old) => { + let entries = old.filter(fn(e) { e.name != name }) + match read_index_entry(ch, name) { + Some(e) => entries.push(e) + None => () + } + push_index(ch, entries) + } + } + } catch { + e => { + let msg = match e { + OrbitError(m) => m + } + println("warning: index of channel '\{ch.name}' not updated: \{msg}") + } + } +} + +///| +test "index round-trips, sorted, without unusable names" { + let entry = fn(name : String) { + IndexEntry::{ name, version: "1.0.0", description: "d", versions: ["1.0.0"] } + } + let parsed = parse_index( + index_json([ + entry("zed"), + entry("a"), + entry("example/greet"), + entry(INDEX_NAME), + ]), + ) + assert_eq(parsed.map(fn(e) { e.name }), ["a", "zed"]) + assert_eq(parsed[0].versions, ["1.0.0"]) + // Only an index artifact is used, and it is not an Orbit package. + assert_true(index_layer_digest("{\"artifactType\":\"x\"}") is None) + assert_true( + orbit_info("{\"artifactType\":\"\{INDEX_ARTIFACT_TYPE}\"}") is None, + ) +} diff --git a/src/main/main.mbt b/src/main/main.mbt index 3e6efc3..4b7c311 100644 --- a/src/main/main.mbt +++ b/src/main/main.mbt @@ -25,8 +25,10 @@ let usage : String = #| orbit logout remove stored registry credentials #| orbit channel list channels, highest priority first #| orbit channel add [--plain-http] - #| orbit publish [--channel ] [--no-latest] + #| orbit publish [--channel ] [--no-latest] [--no-index] #| push /orbit.json + /files/ + #| orbit index [--channel ] [name...] + #| rebuild the channel's package index #| orbit install [-g] [channel::][@constraint]... #| install globally with SAT dependency solving #| orbit remove [-g] ... [--force] remove, then drop unused dependencies @@ -35,7 +37,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 repositories (needs catalog API) + #| orbit search [term] list packages (channel index or catalog API) #| orbit gc delete unused builds from the store #| orbit env [-g] print the PATH line for your shell #| @@ -147,8 +149,8 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError { } else if has_prefix(a, "--manifest-path=") { manifest_path = Some(drop_chars(a, 16)) } else if a == "--channel" { - if cmd != "publish" || i + 1 >= args.length() { - raise OrbitError("usage: orbit publish --channel ") + if (cmd != "publish" && cmd != "index") || i + 1 >= args.length() { + raise OrbitError("usage: orbit publish | index --channel ") } publish_to = args[i + 1] i = i + 1 @@ -279,8 +281,14 @@ async fn dispatch(args : Array[String]) -> Unit raise OrbitError { "publish" => { need(pos, 1, "publish ") let ch = find_channel(load_ctx(), publish_to) - publish(ch, pos[0], !flags.contains("--no-latest")) + publish( + ch, + pos[0], + !flags.contains("--no-latest"), + update_index=!flags.contains("--no-index"), + ) } + "index" => cmd_index(find_channel(load_ctx(), publish_to), pos) "install" => match resolve_project_or_none(force_global, manifest_path) { Some(mf) => diff --git a/src/main/oci.mbt b/src/main/oci.mbt index 0324708..ee2b8ff 100644 --- a/src/main/oci.mbt +++ b/src/main/oci.mbt @@ -624,6 +624,7 @@ async fn oci_request( body : Bytes, scope_key : String, creds_override? : Creds, + check_login? : Bool = true, ) -> (@http.Response, Bytes) raise OrbitError { let initial_url = parse_url(url_str) let (initial_auth, used_cached) = if creds_override is None && scope_key != "" { @@ -638,7 +639,7 @@ async fn oci_request( meth, url_str, headers, initial_auth, body, ) if resp.code != 401 { - if creds_override is None { + if creds_override is None && check_login { check_rejected_login(final_url.host, resp.code) } return (resp, resp_body) @@ -666,7 +667,7 @@ async fn oci_request( Some(retry_auth), body, ) - if creds_override is None { + if creds_override is None && check_login { check_rejected_login(final_url.host, retry_resp.code) } (retry_resp, retry_body) diff --git a/src/main/ops.mbt b/src/main/ops.mbt index eb40292..d4af5bc 100644 --- a/src/main/ops.mbt +++ b/src/main/ops.mbt @@ -867,13 +867,50 @@ fn print_table(rows : Array[Array[String]]) -> Unit { } } +///| +/// Registry text for the terminal: control characters become spaces. +fn printable(s : String) -> String { + let sb = StringBuilder() + for c in s { + let n = c.to_int() + sb.write_char(if n < 32 || (n >= 127 && n < 160) { ' ' } else { c }) + } + sb.to_string() +} + ///| async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { let rows : Array[Array[String]] = [ ["PACKAGE", "CHANNEL", "VERSION", "DESCRIPTION"], ] let mut listed = 0 + let add = fn(name : String, ch : Channel, version : String, desc : String) { + rows.push([ + name, + ch.name, + if version == "" { "-" } else { printable(version) }, + if desc == "" { "-" } else { printable(desc) }, + ]) + } + 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}") @@ -885,28 +922,14 @@ async fn cmd_search(ctx : Ctx, term : String) -> Unit raise OrbitError { 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) && contains_str(r, term) { + 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) => - rows.push([ - r, - ch.name, - if info.version == "" { - "-" - } else { - info.version - }, - if info.description == "" { - "-" - } else { - info.description - }, - ]) + Some(info) => add(r, ch, info.version, info.description) None => () } } diff --git a/src/main/registry.mbt b/src/main/registry.mbt index f7d05a7..5010c53 100644 --- a/src/main/registry.mbt +++ b/src/main/registry.mbt @@ -715,12 +715,16 @@ async fn publish( ch : Channel, dir : String, also_latest : Bool, + update_index? : Bool = true, ) -> Unit raise OrbitError { let text = match read_text(dir + "/orbit.json") { Some(t) => t None => raise OrbitError("\{dir}/orbit.json not found") } let m = parse_manifest(text) + if m.name == INDEX_NAME { + raise OrbitError("'\{INDEX_NAME}' is reserved for the channel index") + } let config = package_config(text, m) let files = dir + "/files" if !exists(files) { @@ -755,4 +759,7 @@ async fn publish( } }) println("published \{m.name} \{m.version} to \{repo_of(ch, m.name)}") + if update_index { + index_published(ch, m.name) + } } diff --git a/src/main/registry_wbtest.mbt b/src/main/registry_wbtest.mbt index 3fc8b08..aa30907 100644 --- a/src/main/registry_wbtest.mbt +++ b/src/main/registry_wbtest.mbt @@ -590,6 +590,7 @@ async fn publish_mock_pkg( depends : Map[String, String], bins : Array[String], script? : String = "#!/bin/sh\necho ok\n", + update_index? : Bool = true, ) -> Unit raise Error { let pkg_dir = work + "/stage-" + name + "-" + version @fs.mkdir(pkg_dir + "/files/bin", recursive=true) @@ -609,7 +610,7 @@ async fn publish_mock_pkg( @fs.mkdir(path_dirname(p), recursive=true, allow_exist=true) @fs.write_file(p, script, create_mode=CreateOrTruncate, permission=0o755) } - publish(ch, pkg_dir, true) + publish(ch, pkg_dir, true, update_index~) } ///| @@ -930,3 +931,88 @@ async test "a rejected login falls back to anonymous for reads only" { }) rejected_logins.clear() } + +///| +async test "each channel has its own index, kept by publish and used by search" { + token_cache.clear() + let work = @fs.tmpdir(prefix="orbit-wb-index-") + defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () }) + let st = new_mock_oci_state() + let upload_seq = Ref(0) + let catalog_gets = Ref(0) + let broken = Ref("") + let server = @http.Server(@socket.Addr::parse("127.0.0.1:0")) + @async.with_task_group(group => { + defer server.close() + group.spawn_bg(no_wait=true, () => { + server.run_forever((req, body, conn) => { + let req_bytes = body.read_all().binary() + let (path, _) = strip_query(req.path) + if path == "/v2/_catalog" { + catalog_gets.val = catalog_gets.val + 1 + } + if broken.val != "" && has_prefix(path, broken.val) { + conn.send_response(500, "Broken") + conn.end_response() + return + } + handle_mock_oci(st, upload_seq, req, req_bytes, conn) + }) + }) + let addr = "127.0.0.1:" + server.addr.port().to_string() + let chan = fn(name : String) { + Channel::{ name, url: addr + "/" + name, plain_http: true } + } + let a = chan("a") + let nested = chan("a/b") + let names = async fn(ch : Channel) { + load_index(ch).unwrap().map(fn(e) { e.name }) + } + assert_true(load_index(a) is None) + + // Without an index, the first publish indexes the whole channel. + publish_mock_pkg(a, work, "one", "1.0.0", Map([]), [], update_index=false) + assert_true(load_index(a) is None) + publish_mock_pkg(a, work, "two", "1.0.0", Map([]), []) + assert_eq(names(a), ["one", "two"]) + publish_mock_pkg(a, work, "two", "1.1.0", Map([]), []) + let two = find_entry(load_index(a).unwrap(), "two").unwrap() + assert_eq(two.version, "1.1.0") + assert_eq(two.versions, ["1.1.0", "1.0.0"]) + assert_eq(two.description, "Mock two 1.1.0") + + // A nested channel is separate. + publish_mock_pkg(nested, work, "three", "1.0.0", Map([]), []) + assert_eq(names(a), ["one", "two"]) + assert_eq(names(nested), ["three"]) + + // Search doesn't touch the catalog once there is an index. + let gets = catalog_gets.val + cmd_search( + Ctx::{ root: work, channels: [a, nested], state: Map([]) }, + "MOCK", + ) + assert_eq(catalog_gets.val, gets) + + // A package that can't be read keeps its entry; a deleted one is dropped. + broken.val = "/v2/a/one/" + cmd_index(a, []) + assert_eq(names(a), ["one", "two"]) + broken.val = "" + st.tags.remove("a/two") + cmd_index(a, []) + assert_eq(names(a), ["one"]) + + // An unreadable index is never overwritten by publish. + let before = st.manifests["a/" + INDEX_NAME]["latest"].0 + broken.val = "/v2/a/" + INDEX_NAME + "/manifests/" + publish_mock_pkg(a, work, "four", "1.0.0", Map([]), []) + broken.val = "" + assert_eq(st.manifests["a/" + INDEX_NAME]["latest"].0, before) + + // Without a catalog, packages are named. + broken.val = "/v2/_catalog" + cmd_index(a, ["four"]) + assert_eq(names(a), ["four", "one"]) + }) +}