Files
orbit/src/main/index.mbt
T
nandi a00c87bf04
Rolling Release / build (push) Successful in 1m49s
Rolling Release / publish (push) Successful in 8s
Show info for packages that aren't installed
- `orbit info` finds a package that isn't installed, or a `channel::` / `@constraint` build, in the cached channel listings used by search
- Channel indexes record each version's manifest digest, so a repeated info needs no network
- Versions without a digest, or indexes built before digests were added, are resolved in the registry
- Show the docs link, channel, digest, bins and dependencies for available builds
2026-12-01 14:39:13 -08:00

374 lines
11 KiB
MoonBit

// 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
digest : String // of the `version` manifest; "" in older indexes
}
///|
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] = []
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)
if e.digest != "" {
o["digest"] = Json::string(e.digest)
}
pkgs.push(Json::object(o))
}
let top : Map[String, Json] = Map([])
top["packages"] = Json::array(pkgs)
top
}
///|
fn index_json(entries : Array[IndexEntry]) -> String {
Json::object(index_object(entries)).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"),
digest: jstr(o, "digest", ""),
})
}
}
_ => ()
}
}
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] }
let raw = fetch_raw_manifest_bytes(ch, name, tag)
match orbit_info(utf8_decode(raw)) {
Some(info) =>
Some(IndexEntry::{
name,
version: info.version,
description: info.description,
versions: sorted_versions(tags),
digest: sha256_digest(raw),
})
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. Returns those found, and the names that couldn't
/// be read with the reason.
async fn read_entries(
ch : Channel,
names : Array[String],
) -> (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 => {
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] = []
let failed : Array[(String, String)] = []
for r in results {
match r {
(_, Ok(Some(e))) => out.push(e)
(_, Ok(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
}
///|
/// 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"],
digest: "sha256:ab",
}
}
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"])
assert_eq(parsed[0].digest, "sha256:ab")
// Indexes written before digests were recorded still parse.
let old = parse_index(
"{\"packages\":[{\"name\":\"a\",\"version\":\"1.0.0\",\"description\":\"d\",\"versions\":[\"1.0.0\"]}]}",
)
assert_eq(old[0].digest, "")
// 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,
)
}