Author SHA1 Message Date
nandiandClaude Opus 5.5 83e694c6c4 Prove the semver and solver kernel instead of testing it
Rolling Release / build (push) Successful in 1m39s
Rolling Release / publish (push) Successful in 8s
Move number parsing, version ordering and constraints, version sorting and
solver literals into src/kernel, with contracts checked by moon prove under
overflow-checked integers. Replace the semver behaviour tests with those
proofs, keep tests for string parsing, and run the proofs in CI.

Version numbers are now 64-bit: the old parser silently wrapped at 2^31.
Drop pick_tag, which only tests called.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:56:21 -08:00
nandiandClaude Opus 5.5 2d815bbb75 Add rolling release built with Zig's musl toolchain
Rolling Release / build (push) Successful in 1m40s
Rolling Release / publish (push) Successful in 8s
Build a static Linux x86_64 binary with zig cc, linking OpenSSL in and
serving it to moonbitlang/async through a dlopen shim. CI publishes it to
the rolling release on every push to main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 16:50:10 -08:00
nandi 3ca9e8ed1d Add example project with locked dependencies and tasks
- Add examples/project with orbit.toml declaring hello and greet (example channel)
- Pin resolved versions and digests in orbit.lock
- Add demo.sh and a demo task that calls hello and greet from .orbit/bin
- Ignore the generated .orbit/ directory and document usage in its README
- Link the example from the main README
2026-11-28 12:13:00 -08:00
nandi 13aa7d7f77 Add Pixi-style project environments and SAT dependency solver
- Add orbit.toml project manifests, deterministic orbit.lock files, [tasks], and `orbit run`
- Add per-project .orbit/bin environments; `-g`/`--global` targets the global environment
- Replace greedy global resolution with a lazy CDCL SAT solver that explains conflicts
- Support channel::pkg dependency pins and comma-separated, comparison, and wildcard constraints
- Cache immutable sha256 manifests under ~/.orbit/cache/manifests
- Validate dependency keys and constraints in orbit.json
2026-11-28 01:43:04 -08:00
nandi 0919ce105c Replace oras with native OCI registry client and add login
- Talk to OCI Distribution v2 registries directly over HTTP/TLS; oras is no longer required on PATH
- Add `orbit login <host>` and `orbit logout <host>`; credentials go to $ORBIT_ROOT/auth.json (mode 0600)
- Fall back to Docker config (credHelpers and credsStore) when no Orbit credentials exist
- Verify layer downloads with streaming SHA-256
- Fall back to the next channel only on HTTP 404 instead of matching oras error text
- Update README and moon.mod to drop oras references
2026-11-27 15:46:41 -08:00
nandi f8c9b99ee3 Add orbit SVG favicon
- Add a 64x64 favicon.svg with the orbit logo mark
- Use a dark slate background with violet orbit rings
2026-11-27 13:14:25 -08:00
nandi e9e51459dc Merge pull request 'Show package before channel in orbit search' (#7) from search-columns into main 2026-11-27 21:11:23 +00:00
nandiandClaude Haiku 5.5 ec64fb07cf Show package before channel in orbit search
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-27 00:11:46 -08:00
nandi 44d7ac2346 Merge pull request 'Search as a table, Orbit-only results, and spinner fix' (#6) from orbit-search-filter into main 2026-11-27 08:09:43 +00:00
nandiandClaude Haiku 5.5 984494f556 Skip nested channel namespaces in orbit search
A repo such as example/greet under main is another channel's package, and
its name is not a valid package name, so search no longer lists it under main.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-26 23:59:10 -08:00
nandiandClaude Haiku 5.5 8eadda5815 Show orbit search results as a table
Search prints CHANNEL, PACKAGE, VERSION and DESCRIPTION columns. Version and
description come from the manifest annotations, so no extra requests are made.
Empty results say which term matched nothing.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-26 23:27:49 -08:00
nandiandClaude Haiku 5.5 6a369dfa5e Mark Orbit packages with artifactType and filter search by it
orbit publish sets the manifest artifactType to application/vnd.latha.orbit.v1.
orbit search checks each matching repository's latest manifest in parallel and
lists only Orbit packages, so Helm charts and other OCI artifacts no longer
appear. Packages published earlier are recognised by their config media type.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-26 23:19:43 -08:00
nandiandClaude Haiku 5.5 a999db54a8 Fix spinner hang and use braille frames
The spinner ran as a background task that outlived the command, so a
terminal run of orbit search never returned. It is now a child task that
is cancelled once the command finishes, and it starts immediately with
braille frames. upgrade skips the metadata fetch for an unchanged build
whose description is already saved.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-26 22:59:16 -08:00
nandi 83a1784fca Merge pull request 'Use moonbitlang/async for process and file IO' (#5) from orbit-async-io into main 2026-11-27 06:42:34 +00:00
nandiandClaude Haiku 5.5 ec21287549 Use moonbitlang/async for process and file IO
Process execution and file access go through @process and @fs. The spinner
is a background task in a task group, and the C stub keeps only getenv,
exit, isatty, symlink and stderr output. orbit info reads installed state
only, and it records and restores package descriptions. just install adds
Orbit's bin directory to ~/.bashrc once.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-26 22:40:18 -08:00
nandi 65e5dc966f Merge pull request 'Add README to the greet example directory' (#4) from greet-example-readme into main 2026-11-27 04:43:11 +00:00
nandi 2eff722311 Add README to the greet example directory 2026-11-26 20:43:02 -08:00
nandi 6069a261db Merge pull request 'Add documentation metadata for Orbit packages' (#3) from greet-package-docs into main 2026-11-27 04:38:38 +00:00
42 changed files with 8744 additions and 681 deletions

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
name: Rolling Release
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
# Never cancelled, so a newer push can't interrupt a release half way.
concurrency:
group: rolling-${{ github.ref }}
cancel-in-progress: false
permissions:
contents: read
env:
MOONBIT_VERSION: 0.10.20+65efd5b93
Z3_VERSION: 5.3.3
Z3_SHA256: d56f60b06f432f33de5810f7f1a384a339131f361e2d54d08ea83eea14326880
ZIG_VERSION: 0.17.1
ZIG_SHA256: 3581863e3cbcfd0fce0efc682ce7e9e93da96668a977791d356a26d2a7e9b17a
jobs:
build:
runs-on: depot-ubuntu-24.04-4
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Install build tools
run: |
missing=
for tool in gcc make perl readelf curl xz; do
command -v "$tool" >/dev/null || missing=1
done
if [ -n "$missing" ]; then
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends build-essential perl curl xz-utils >/dev/null
fi
- name: Install MoonBit
run: |
curl -fsSL --retry 5 https://cli.moonbitlang.com/install/unix.sh | bash -s -- "$MOONBIT_VERSION"
echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
"$HOME/.moon/bin/moon" update
"$HOME/.moon/bin/moon" version --all
- name: Install Zig
run: |
curl -fsSL --retry 5 -o "$RUNNER_TEMP/zig.tar.xz" \
"https://ziglang.org/download/$ZIG_VERSION/zig-x86_64-linux-$ZIG_VERSION.tar.xz"
echo "$ZIG_SHA256 $RUNNER_TEMP/zig.tar.xz" | sha256sum -c -
tar -xJf "$RUNNER_TEMP/zig.tar.xz" -C "$RUNNER_TEMP"
echo "$RUNNER_TEMP/zig-x86_64-linux-$ZIG_VERSION" >> "$GITHUB_PATH"
- name: Test
run: moon test --target native
# Proofs replace tests of src/kernel. The override checks for overflow;
# `just prove` runs the same command.
- name: Prove
run: |
z3="z3-$Z3_VERSION-x64-glibc-2.39"
curl -fsSL --retry 5 -o "$RUNNER_TEMP/z3.zip" \
"https://github.com/Z3Prover/z3/releases/download/z3-$Z3_VERSION/$z3.zip"
echo "$Z3_SHA256 $RUNNER_TEMP/z3.zip" | sha256sum -c -
python3 -m zipfile -e "$RUNNER_TEMP/z3.zip" "$RUNNER_TEMP"
chmod +x "$RUNNER_TEMP/$z3/bin/z3"
export Z3PATH="$RUNNER_TEMP/$z3/bin/z3"
export MOON_PROVE_PRELUDE_OVERRIDE="$HOME/.moon/lib/prelude_proof_machine_int"
moon prove src/kernel
- name: Build static binary
run: scripts/build-musl.sh
# A real HTTPS install: proves the linked-in OpenSSL and CA lookup work.
- name: Smoke test
run: |
export ORBIT_ROOT="$RUNNER_TEMP/orbit-smoke"
dist/orbit-linux-x86_64 install hello
"$ORBIT_ROOT/bin/hello"
- uses: actions/upload-artifact@v3
with:
name: orbit-linux-x86_64
path: dist/
if-no-files-found: error
publish:
needs: build
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
runs-on: depot-ubuntu-24.04
timeout-minutes: 10
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v3
with:
name: orbit-linux-x86_64
path: dist/
- name: Publish rolling release
env:
GITEA_TOKEN: ${{ github.token }}
run: |
(cd dist && sha256sum -c SHA256SUMS)
python3 scripts/publish-rolling.py
+1
View File
@@ -1,3 +1,4 @@
target/
.mooncakes/
_build/
dist/
+101 -22
View File
@@ -1,19 +1,20 @@
# orbit
A small package manager written in MoonBit that uses any OCI registry (Gitea, GHCR, Harbor, `registry:2`, ...) as its repository, with [ORAS](https://github.com/oras-project/oras) as the transport.
A small package manager written in MoonBit that uses any OCI registry (Gitea, GHCR, Harbor, `registry:2`, ...) as its repository, speaking the OCI Distribution v2 protocol directly over HTTP/TLS.
> **Status:** builds cleanly (no warnings) with MoonBit `moonc v1.0.0-rc1` / `moon 0.1.20261126`, and the unit tests pass. publish, install (with dependencies), upgrade, rollback, remove and gc have been exercised end to end against a local `registry:2` with ORAS 1.2.3.
> **Status:** builds cleanly (no warnings) with MoonBit `moonc v1.0.0-rc1` / `moon 0.1.20261126`, and the unit tests pass. publish, install (with dependencies), upgrade, rollback, remove and gc have been exercised end to end against a local `registry:2` and Gitea.
## What it does
- **Publish:** `orbit publish <dir>` packs `<dir>/files/` into `pkg.tar.gz` and pushes it with `<dir>/orbit.json` as the OCI config blob.
- **Install with dependencies:** it reads only the small config blob (`oras manifest fetch-config`) to plan, then pulls the layers by digest.
- **Version constraints:** `1.2.3`, `1.2`, `^1.2.0`, `~1.2.0`, `>=1.2`, `*`. Prereleases match only when the constraint asks for one.
- **Content-addressed store:** packages unpack into `~/.orbit/store/<name>/<digest>/`, and their binaries are symlinked into `~/.orbit/bin/`.
- **Lazy CDCL SAT solver:** resolves global and project dependency graphs with backtracking, conflict explanations, and `channel::pkg` dependency pins, reading only needed config blobs and caching immutable `sha256` manifests under `~/.orbit/cache/manifests/`.
- **Pixi-style project environments:** `orbit new`, `orbit.toml` manifests, deterministic `orbit.lock` lockfiles, `[tasks]`, `orbit run`, and isolated `.orbit/bin/` environments symlinked from the shared store (`-g` / `--global` targets the global environment inside a project).
- **Version constraints:** `1.2.3`, `=1.2.3`, `==1.2.3`, `1.2`, `1.2.*`, `^1.2.0`, `~1.2.0`, `>=1.2`, `<=2.0`, `>1.0`, `<2.0`, `!=1.3.0`, `*`, and comma-separated ranges (`>=1.2.0, <2.0.0`). Prereleases match only when the constraint mentions a `-`.
- **Content-addressed store:** packages unpack into `~/.orbit/store/<name>/<digest>/`, and their binaries are symlinked into `~/.orbit/bin/` (global) or `<project>/.orbit/bin/` (project).
- **File ownership:** two packages can't provide the same binary.
- **Upgrade and rollback:** the previous two builds are kept, and `orbit rollback <name>` switches back instantly with no network.
- **Remove:** `orbit remove` refuses to delete what other packages need, then autoremoves orphaned dependencies.
- **gc** deletes builds that are neither current nor kept for rollback.
- **Upgrade and rollback:** global installs keep the previous two builds, and `orbit rollback <name>` switches back instantly with no network.
- **Remove:** `orbit remove` refuses to delete what other global packages need and autoremoves orphaned dependencies; in projects it updates `orbit.toml` and `orbit.lock`.
- **gc** deletes store builds that are neither globally current nor kept for rollback.
## Package format
@@ -36,7 +37,7 @@ mypkg/
}
```
In a channel this becomes `<channel url>/mytool:1.4.0`, plus the `latest` tag:
In a channel this becomes `<channel url>/mytool:1.4.0`, plus the `latest` tag. The manifest sets `artifactType` to `application/vnd.latha.orbit.v1`, which is how `orbit search` tells Orbit packages apart from other OCI artifacts such as Helm charts. Packages published before this have no `artifactType`, so search also recognises the Orbit config media type:
| Part | Media type |
|---|---|
@@ -52,8 +53,10 @@ Because these are ordinary OCI artifacts, you can sign them with `cosign` or `no
## Usage
### Global environment
```sh
oras login git.site.latha.org # once, with a Gitea token (needed to publish)
orbit login git.site.latha.org # once, with a Gitea token (needed to publish)
eval "$(orbit env)"
orbit publish examples/hello
@@ -64,6 +67,44 @@ orbit rollback hello
orbit remove hello
```
### Project workflow (Pixi-style)
Inside a directory with `orbit.toml` (or pass `--manifest-path <path>`), commands target the project unless you pass `-g` / `--global`:
```sh
orbit new myapp && cd myapp
orbit add hello example::greet
orbit run greet
orbit lock --update
orbit install --locked
orbit update
orbit remove hello
```
An `orbit.toml` looks like:
```toml
[project]
name = "myapp"
version = "0.1.0"
channels = ["example", "main"]
[[channels]]
name = "example"
url = "git.site.latha.org/nandi/example"
[dependencies]
hello = "^1.0.0"
greet = { version = ">=1.0.0, <2.0.0", channel = "example" }
[tasks]
hi = "greet"
```
See [examples/project](examples/project/README.md) for a working example project using `hello` and `example::greet`.
Credentials are stored in `~/.orbit/auth.json` (`$ORBIT_ROOT/auth.json`, mode `0600`). Orbit also falls back to `~/.docker/config.json` (`$DOCKER_CONFIG/config.json`) including `credHelpers` and `credsStore`. Use `orbit logout <host>` to remove stored credentials from Orbit.
## Channels
Packages come from **channels**, which work like channels in pixi. A channel is a name for a registry namespace. The built-in `main` channel is `git.site.latha.org/nandi`, so no setup is needed.
@@ -105,17 +146,44 @@ docker run -d -p 5000:5000 registry:2
orbit channel add local localhost:5000/pkgs --plain-http
```
## Rolling release
Every push to `main` that passes the tests replaces the
[`rolling` release](https://git.site.latha.org/nandi/orbit/releases/tag/rolling)
with a static Linux x86_64 binary. It doesn't need glibc or OpenSSL, only `tar`,
`/bin/sh`, and the system's CA certificates (`ca-certificates` on most distros;
set `SSL_CERT_FILE` if they live somewhere unusual).
```sh
base=https://git.site.latha.org/nandi/orbit/releases/download/rolling
curl -fLO "$base/orbit-linux-x86_64" -fLO "$base/SHA256SUMS" &&
sha256sum -c SHA256SUMS &&
install -Dm755 orbit-linux-x86_64 ~/.local/bin/orbit
```
`just build-musl` makes the same binary locally in `dist/`. It needs `zig`,
`perl`, `make`, and `curl`. [scripts/build-musl.sh](scripts/build-musl.sh) compiles
MoonBit's C output and a pinned OpenSSL with `zig cc -target x86_64-linux-musl`.
`moonbitlang/async` normally loads OpenSSL with `dlopen`, which static binaries
can't do, so [openssl_static.c](scripts/musl/openssl_static.c) supplies the
linked-in functions instead.
## Building
```sh
moon build --target native --release
moon test --target native # semver / manifest unit tests
moon test --target native # unit and mock-registry tests
just prove # proofs of src/kernel (needs an SMT solver: z3, cvc5 or alt-ergo)
# the binary is _build/native/release/build/main/main.exe
```
Or run `just install` to build and copy the binary to `~/.local/bin/orbit`.
It also adds Orbit's package bin directory to `~/.bashrc` if the setup line
isn't already there. Open a new Bash shell or run `source ~/.bashrc` to pick
up the change in your current shell. `~/.local/bin` must already be on `PATH`
to run `orbit` itself by name.
Linux only for now: arguments come from `/proc/self/cmdline`. It needs `oras`, `tar` and `/bin/sh` on `PATH`.
Linux only for now: arguments come from `/proc/self/cmdline`. It needs `tar` and `/bin/sh` on `PATH`.
### Package Orbit with Orbit
@@ -127,10 +195,10 @@ package_dir=$(sh scripts/package-orbit.sh) &&
_build/native/release/build/main/main.exe publish "$package_dir"
```
This publishes to the `main` channel (use `--channel <name>` for another), so log in with `oras login <host>` first if needed. The
This publishes to the `main` channel (use `--channel <name>` for another), so log in with `orbit login <host>` first if needed. The
package contains a native Linux binary for the build machine's architecture.
Use the same architecture on the install machine. `oras` and `tar` are still
system prerequisites; the package does not bundle them.
Use the same architecture on the install machine. `tar` is still a
system prerequisite; the package does not bundle it.
To bootstrap from source, install the published package with the binary you just
built. After adding Orbit's bin directory to `PATH`, use the installed binary
@@ -146,16 +214,26 @@ orbit upgrade orbit
## Layout
`src/kernel/` holds the code whose behaviour is proved rather than tested: number
parsing, version ordering and constraints, sorting, and solver literals. See its
[README](src/kernel/README.md).
```
src/main/
stub.c C glue: system(), popen(), file read/write, getenv, exit
sys.mbt FFI bindings, UTF-8, string helpers, shell quoting
semver.mbt versions, constraints, tag selection (+ tests)
stub.c C glue: time, termios echo toggle, getenv, symlink, stderr, exit
sys.mbt FFI bindings, UTF-8, string helpers, spinner, atomic writes
sha256.mbt streaming FIPS 180-4 SHA-256 (+ tests)
auth.mbt credentials store (~/.orbit/auth.json + Docker config fallback)
oci.mbt OCI Distribution v2 HTTP transport, Bearer/Basic auth, redirects
semver.mbt versions, relational/compound constraints, parsing over src/kernel (+ tests)
model.mbt orbit.json / state.json / config.json (+ tests)
registry.mbt oras wrappers: tags, resolve, fetch-config, pull, push
ops.mbt dependency planner, install/remove/upgrade/rollback/gc
registry.mbt OCI registry ops: tags, resolve, cached manifests, fetch, publish, login
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)
channels.mbt config.toml, channel priority and lookup (+ tests)
main.mbt CLI
registry_wbtest.mbt mock-OCI registry, SAT global, and project workflow tests
```
## Toolchain notes
@@ -169,6 +247,7 @@ Fixes needed for current MoonBit, kept here in case you build with an older comp
## Known limits
- Dependency resolution is greedy (highest satisfying version, first come), not a SAT solver.
- There's no lock file for concurrent runs, and no install hooks, by design.
- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit info <name>` there.
- `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 <name>` reads globally installed package details without contacting the registry. Use `orbit versions <name>` to check published versions.
- `search` needs the registry's catalog API, which Gitea doesn't expose. Use `orbit versions <name>` if you already know the package name.
+11
View File
@@ -0,0 +1,11 @@
# greet
`greet` is an example Orbit package from the `example` channel. It installs a
small greeting command and depends on `hello` from the built-in `main`
channel.
- [Installation and usage](files/share/doc/greet/README.md)
- [Package on Gitea](https://git.site.latha.org/nandi/-/packages/container/example%2Fgreet/latest)
This directory contains the package manifest (`orbit.json`) and the files Orbit
installs (`files/`).
+1
View File
@@ -0,0 +1 @@
.orbit/
+26
View File
@@ -0,0 +1,26 @@
# orbit-demo
An example project whose dependencies (`hello` from `main` and `greet` from `example`) are declared in [orbit.toml](orbit.toml) and pinned in [orbit.lock](orbit.lock).
## Files
- `orbit.toml` — declares the `example` channel, dependencies (`greet` and `hello`), and `[tasks]`.
- `orbit.lock` — deterministic lockfile generated by `orbit lock`.
- `demo.sh` — script invoked by the `demo` task that calls `hello` and `greet` from `.orbit/bin/`.
- `.gitignore` — ignores the generated `.orbit/` environment directory.
## Usage
From this directory:
```sh
orbit install --locked # sync .orbit/ from orbit.lock
orbit list # show locked project packages
orbit run --locked demo # run demo.sh with .orbit/bin on PATH
orbit run --locked greet # run the greet task
orbit run --locked hello # run the hello task
orbit update # resolve newer versions allowed by orbit.toml
eval "$(orbit env)" # put .orbit/bin on PATH in your current shell
```
Or from the repository root with `--manifest-path examples/project`.
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
echo "Project: ${ORBIT_PROJECT:-$(pwd)}"
echo " hello -> $(hello)"
echo " greet -> $(greet)"
+30
View File
@@ -0,0 +1,30 @@
# Generated by orbit. Do not edit by hand.
version = 1
[[channels]]
name = "main"
url = "git.site.latha.org/nandi"
[[channels]]
name = "example"
url = "git.site.latha.org/nandi/example"
[[package]]
name = "greet"
version = "1.0.1"
channel = "example"
url = "git.site.latha.org/nandi/example"
digest = "sha256:72f32cfa2800376cf49813e86b5ee99a853c972842e2df72e82447bd825abdb9"
description = "Example package for the example channel"
bin = ["bin/greet"]
depends = { hello = "^1.0.0" }
[[package]]
name = "hello"
version = "1.0.0"
channel = "main"
url = "git.site.latha.org/nandi"
digest = "sha256:30e13217f0e0475a4526a141b76c78e7f19f6c66754795dbb6636e6d251ee043"
description = "Example orbit package"
bin = ["bin/hello"]
+18
View File
@@ -0,0 +1,18 @@
[project]
name = "orbit-demo"
version = "0.1.0"
description = "Example project with dependencies managed by orbit"
channels = ["main", "example"]
[[channels]]
name = "example"
url = "git.site.latha.org/nandi/example"
[dependencies]
greet = { version = ">=1.0.0, <2.0.0", channel = "example" }
hello = "^1.0.0"
[tasks]
demo = "sh \"$ORBIT_PROJECT/demo.sh\""
greet = "greet"
hello = ["hello"]
+15
View File
@@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
<title>orbit</title>
<rect width="64" height="64" fill="#0f172a"/>
<circle cx="32" cy="32" r="21" fill="none" stroke="#a78bfa" stroke-opacity="0.4" stroke-width="2.5"/>
<g transform="rotate(-32 32 32)" fill="none">
<path d="M7 32 A25 10.5 0 0 1 57 32" stroke="#a78bfa" stroke-opacity="0.55" stroke-width="3.2"/>
</g>
<polygon points="32,20.5 42,26.25 42,37.75 32,43.5 22,37.75 22,26.25" fill="#f8fafc"/>
<g transform="rotate(-32 32 32)" fill="none">
<path d="M44.5 41.1 A25 10.5 0 0 1 19.5 41.1" stroke="#0f172a" stroke-width="7.2"/>
<path d="M57 32 A25 10.5 0 0 1 7 32" stroke="#a78bfa" stroke-width="3.2"/>
</g>
<circle cx="18.5" cy="15.9" r="7.5" fill="#0f172a"/>
<circle cx="18.5" cy="15.9" r="4.8" fill="#a78bfa"/>
</svg>

After

Width:  |  Height:  |  Size: 843 B

+13 -1
View File
@@ -6,10 +6,22 @@ default:
build:
moon build --target native --release
# Build a static binary with Zig's musl toolchain (dist/orbit-linux-x86_64).
build-musl:
scripts/build-musl.sh
# Run the unit tests.
test:
moon test --target native
# Build orbit and install it to ~/.local/bin.
# Prove src/kernel with overflow-checked integers (needs z3, cvc5 or alt-ergo).
prove:
MOON_PROVE_PRELUDE_OVERRIDE="${MOON_HOME:-$HOME/.moon}/lib/prelude_proof_machine_int" moon prove src/kernel
# Install Orbit to ~/.local/bin and set up its package PATH for Bash.
install: build
install -Dm755 _build/native/release/build/main/main.exe "$HOME/.local/bin/orbit"
@line='export PATH="${ORBIT_ROOT:-$HOME/.orbit}/bin:$PATH"'; rc="$HOME/.bashrc"; \
if [ ! -f "$rc" ] || ! grep -Fqx -- "$line" "$rc"; then \
printf '\n%s\n' "$line" >> "$rc"; \
fi
+3 -2
View File
@@ -6,12 +6,13 @@ readme = "README.md"
license = "Apache-2.0"
keywords = [ "package-manager", "oras", "oci" ]
keywords = [ "package-manager", "oci" ]
description = "A small package manager that stores packages as OCI artifacts via ORAS"
description = "A small package manager that stores packages as OCI artifacts"
source = "src"
import {
"moonbit-community/toml@0.5.1",
"moonbitlang/async@0.22.9",
}
+76
View File
@@ -0,0 +1,76 @@
#!/bin/sh
# Build a fully static Orbit with Zig's musl toolchain:
# dist/orbit-linux-x86_64 and dist/SHA256SUMS
#
# Needs moon, zig, perl, make, and curl. OpenSSL is built once, with zig, into
# _build/musl-deps (set ORBIT_MUSL_DEPS to keep it elsewhere).
set -eu
openssl_version=3.5.9
openssl_sha256=603f5602e2eef00d77fbd429d34dcd5822bb301757a1bc9cdb24c670f1eb859a
cd "$(dirname "$0")/.."
root=$PWD
# Only x86_64: the libbacktrace.a that moon links is prebuilt for the host.
if [ "$(uname -sm)" != "Linux x86_64" ]; then
echo "build-musl.sh only supports Linux x86_64" >&2
exit 1
fi
export ORBIT_MUSL_TARGET=x86_64-linux-musl
deps=${ORBIT_MUSL_DEPS:-$root/_build/musl-deps}
prefix=$deps/openssl-$openssl_version-zig-$(zig version)
if [ ! -f "$prefix/lib/libssl.a" ]; then
echo "Building OpenSSL $openssl_version with zig $(zig version)" >&2
mkdir -p "$deps"
work=$(mktemp -d "$deps/build.XXXXXX")
trap 'rm -rf "$work"' EXIT
curl -fsSL --retry 5 -o "$work/openssl.tar.gz" \
"https://github.com/openssl/openssl/releases/download/openssl-$openssl_version/openssl-$openssl_version.tar.gz"
printf '%s %s\n' "$openssl_sha256" "$work/openssl.tar.gz" | sha256sum -c - >&2
tar -xzf "$work/openssl.tar.gz" -C "$work"
(
cd "$work/openssl-$openssl_version"
# no-autoload-config: the host's openssl.cnf may name modules we can't load.
CC="$root/scripts/musl/cc" AR="$root/scripts/musl/ar" RANLIB="zig ranlib" \
./Configure linux-x86_64 --prefix="$work/out" --libdir=lib --openssldir=/etc/ssl \
no-shared no-module no-dso no-apps no-tests no-docs no-legacy no-autoload-config \
no-ssl3 no-tls1 no-tls1_1 no-dtls no-comp no-afalgeng
make -s -j"$(nproc)" build_libs
make -s install_dev
) > "$work/log" 2>&1 || { tail -n 60 "$work/log" >&2; exit 1; }
rm -rf "$prefix"
mv "$work/out" "$prefix"
fi
if [ ! -d .mooncakes/moonbitlang/async ]; then moon install >&2; fi
obj=$root/_build/musl-shim
mkdir -p "$obj"
sed -nE 's/^ *IMPORT_FUNC(_WITH_ALT_NAMES)?\([^,]+, *([A-Za-z0-9_]+) *,.*/ORBIT_SYMBOL(\2)/p' \
.mooncakes/moonbitlang/async/src/tls/openssl.c > "$obj/openssl_symbols.h"
if [ "$(wc -l < "$obj/openssl_symbols.h")" -lt 20 ]; then
echo "Could not read the OpenSSL imports from moonbitlang/async" >&2
exit 1
fi
scripts/musl/cc -c -O2 -I"$prefix/include" -I"$obj" \
scripts/musl/openssl_static.c -o "$obj/openssl_static.o"
# A separate target directory keeps these objects apart from the usual glibc ones.
# moon doesn't track ORBIT_MUSL_LINK, so relink every time.
rm -f _build/musl/native/release/build/main/main.exe
# async's dir.c uses NAME_MAX without limits.h, which only glibc's dirent.h pulls in.
MOON_CC=$root/scripts/musl/cc MOON_AR=$root/scripts/musl/ar \
ORBIT_MUSL_CFLAGS="-include limits.h" \
ORBIT_MUSL_LINK="$obj/openssl_static.o $prefix/lib/libssl.a $prefix/lib/libcrypto.a" \
moon build --target native --release --target-dir _build/musl >&2
mkdir -p dist
install -m 755 _build/musl/native/release/build/main/main.exe dist/orbit-linux-x86_64
if readelf -lW dist/orbit-linux-x86_64 | grep -q INTERP; then
echo "dist/orbit-linux-x86_64 is not static" >&2
exit 1
fi
(cd dist && sha256sum orbit-linux-x86_64 > SHA256SUMS)
ls -l dist >&2
+2
View File
@@ -0,0 +1,2 @@
#!/bin/sh
exec zig ar "$@"
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# MOON_CC for static musl builds: `zig cc`, plus the static OpenSSL objects when linking.
set -eu
# shellcheck disable=SC2086 # ORBIT_MUSL_* are space-separated lists
for arg in "$@"; do
case $arg in
-c) exec zig cc -target "$ORBIT_MUSL_TARGET" -ffunction-sections -fdata-sections ${ORBIT_MUSL_CFLAGS-} "$@" ;;
esac
done
exec zig cc -target "$ORBIT_MUSL_TARGET" -static -s -Wl,--gc-sections "$@" ${ORBIT_MUSL_LINK-}
+66
View File
@@ -0,0 +1,66 @@
// moonbitlang/async loads OpenSSL with dlopen/dlsym, which a static musl binary
// can't do. These definitions replace musl's stubs (nothing else in Orbit uses
// them) and hand out the statically linked OpenSSL functions instead.
//
// openssl_symbols.h is generated by scripts/build-musl.sh from async's own
// import list, so a function OpenSSL lacks fails the link, not the first request.
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
// SSL_CTX_set_default_verify_paths only checks the OPENSSLDIR chosen at build
// time (/etc/ssl). Also load the CA bundle from where other distros keep it,
// unless the user picked their own with SSL_CERT_FILE or SSL_CERT_DIR.
static int set_default_verify_paths(SSL_CTX *ctx) {
static const char *const bundles[] = {
"/etc/ssl/certs/ca-certificates.crt", // Debian, Arch, Alpine, Nix
"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem", // Fedora, RHEL
"/etc/pki/tls/certs/ca-bundle.crt", // older Fedora, RHEL
"/etc/ssl/ca-bundle.pem", // openSUSE
"/etc/ssl/cert.pem", // Alpine, Void
};
if (!SSL_CTX_set_default_verify_paths(ctx)) return 0;
if (getenv("SSL_CERT_FILE") || getenv("SSL_CERT_DIR")) return 1;
for (size_t i = 0; i < sizeof(bundles) / sizeof(bundles[0]); ++i) {
if (access(bundles[i], R_OK) == 0 &&
SSL_CTX_load_verify_file(ctx, bundles[i])) {
break;
}
}
return 1;
}
static const struct {
const char *name;
void *address;
} symbols[] = {
{ "OpenSSL_version_num", (void *)OpenSSL_version_num },
#define ORBIT_SYMBOL(name) { #name, (void *)name },
#include "openssl_symbols.h"
#undef ORBIT_SYMBOL
};
void *dlopen(const char *file, int mode) {
(void)mode;
return file && strncmp(file, "libssl.so", 9) == 0 ? (void *)symbols : NULL;
}
void *dlsym(void *handle, const char *name) {
if (handle != (void *)symbols) return NULL;
if (strcmp(name, "SSL_CTX_set_default_verify_paths") == 0) {
return (void *)set_default_verify_paths;
}
for (size_t i = 0; i < sizeof(symbols) / sizeof(symbols[0]); ++i) {
if (strcmp(name, symbols[i].name) == 0) return symbols[i].address;
}
return NULL;
}
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Publish dist/ as the rolling Gitea release. Run by .gitea/workflows/rolling-release.yml."""
import json
import os
from pathlib import Path
import subprocess
import urllib.error
import urllib.parse
import urllib.request
TAG = "rolling"
STAGED = "new-"
ASSETS = ["orbit-linux-x86_64", "SHA256SUMS"]
ROOT = Path(__file__).resolve().parent.parent
DIST = ROOT / "dist"
SERVER = os.environ["GITHUB_SERVER_URL"].rstrip("/")
REPO = os.environ["GITHUB_REPOSITORY"]
COMMIT = os.environ["GITHUB_SHA"]
TOKEN = os.environ["GITEA_TOKEN"]
RELEASES = f"{SERVER}/api/v1/repos/{REPO}/releases"
def call(method, url, data=None, content_type="application/json"):
"""Make a Gitea API call. Returns None when a GET finds nothing."""
if isinstance(data, dict):
data = json.dumps(data).encode()
request = urllib.request.Request(url, data=data, method=method)
request.add_header("Authorization", f"token {TOKEN}")
if data is not None:
request.add_header("Content-Type", content_type)
try:
with urllib.request.urlopen(request, timeout=300) as response:
body = response.read()
except urllib.error.HTTPError as error:
if method == "GET" and error.code == 404:
return None
detail = error.read().decode(errors="replace")
raise SystemExit(f"{method} {url}: HTTP {error.code}: {detail}")
return json.loads(body) if body else None
def replace_assets(release_id):
"""Upload under staging names, then swap, so downloads are only missing for a moment."""
assets_url = f"{RELEASES}/{release_id}/assets"
for asset in call("GET", assets_url):
if asset["name"].startswith(STAGED):
call("DELETE", f"{assets_url}/{asset['id']}")
for name in ASSETS:
query = urllib.parse.urlencode({"name": STAGED + name})
call("POST", f"{assets_url}?{query}", (DIST / name).read_bytes(), "application/octet-stream")
ids = {asset["name"]: asset["id"] for asset in call("GET", assets_url)}
for name in ASSETS:
if name in ids:
call("DELETE", f"{assets_url}/{ids[name]}")
call("PATCH", f"{assets_url}/{ids[STAGED + name]}", {"name": name})
def main():
missing = [name for name in ASSETS if not (DIST / name).is_file()]
if missing:
raise SystemExit(f"missing from dist/: {', '.join(missing)}")
sums = (DIST / "SHA256SUMS").read_text().strip()
download = f"{SERVER}/{REPO}/releases/download/{TAG}"
release = {
"tag_name": TAG,
"target_commitish": COMMIT,
"name": f"Rolling build ({COMMIT[:7]})",
"prerelease": True,
"body": (
f"Automated build of `main` at [`{COMMIT[:7]}`]({SERVER}/{REPO}/commit/{COMMIT}). "
"A static Linux x86_64 binary built with Zig's musl toolchain, with OpenSSL included.\n\n"
f"```sh\ncurl -fLo orbit {download}/orbit-linux-x86_64\nchmod +x orbit\n```\n\n"
f"```\n{sums}\n```\n"
),
}
existing = call("GET", f"{RELEASES}/tags/{TAG}")
if existing is None:
existing = call("POST", RELEASES, {**release, "draft": False})
replace_assets(existing["id"])
subprocess.run(
["git", "push", "--force", "origin", f"{COMMIT}:refs/tags/{TAG}"], cwd=ROOT, check=True
)
call("PATCH", f"{RELEASES}/{existing['id']}", {**release, "draft": False})
print(f"Published {SERVER}/{REPO}/releases/tag/{TAG}")
if __name__ == "__main__":
main()
+24
View File
@@ -0,0 +1,24 @@
# kernel
The proved part of Orbit. `src/main` runs this code, so the proofs replace tests
of it. There are no axioms. Contracts are in `.mbt`, specifications in `.mbtp`.
| File | Proved |
|---|---|
| `nat` | The result is the decimal value, or -1 for an empty string, a non-digit, or 10^18 and up. Nothing overflows. |
| `version` | `compare` is a total order, and each constraint operator accepts exactly its interval. |
| `sort` | `sort_desc` terminates and lists every index once, highest version first and stable. |
| `lit` | Literals round trip to their variable and sign, and a literal and its complement never agree. |
Run `just prove`. It selects the machine-integer prelude. Plain `moon prove`
models integers as unbounded, so it would miss overflow.
Not proved, and still tested in `src/main`: splitting strings, ranking
prereleases (`Key.pre`), and anything that does I/O. The prover treats strings
as opaque. `src/main` is not proof-enabled, so its calls must meet the
`proof_require` clauses by themselves.
**Writing specifications:** `moonc-prove` 0.10.20 drops the parentheses around an
implication, so `(a → b) && (c → d)` is read as `((a → b) && c) → d`. Never put
`→` or a quantifier under `&&` or `||`. Give it its own predicate, or use `==`.
After changing a proof, break the code on purpose and check that it fails.
+80
View File
@@ -0,0 +1,80 @@
///|
#derive(Eq)
pub(all) enum Val {
Unassigned
True
False
}
///|
pub extend Val with Eq::{equal, not_equal}
///|
pub fn pos_lit(
v : Int32,
) -> Int32 where {
proof_require: var_ok(v),
proof_ensure: r => 0 <= r && r / 2 == v && r % 2 == 0,
} {
v * 2
}
///|
pub fn neg_lit(
v : Int32,
) -> Int32 where {
proof_require: var_ok(v),
proof_ensure: r => 0 <= r && r / 2 == v && r % 2 == 1,
} {
v * 2 + 1
}
///|
pub fn lit_var(
l : Int32,
) -> Int32 where {
proof_require: 0 <= l,
proof_ensure: r => 0 <= r && (l == r * 2 || l == r * 2 + 1),
} {
l / 2
}
///|
pub fn lit_is_neg(
l : Int32,
) -> Bool where {
proof_require: 0 <= l,
proof_ensure: r => r == (l % 2 == 1),
} {
l % 2 != 0
}
///|
/// The complement: same variable, opposite sign.
pub fn lit_neg(
l : Int32,
) -> Int32 where {
proof_require: 0 <= l,
proof_ensure: r => 0 <= r && r != l && r / 2 == l / 2 && r % 2 != l % 2,
} {
if l % 2 == 0 {
l + 1
} else {
l - 1
}
}
///|
pub fn lit_val(
v : Val,
l : Int32,
) -> Val where {
proof_require: 0 <= l,
proof_ensure: r => truth_ok(v, l, r),
} {
match v {
Unassigned => Unassigned
True => if lit_is_neg(l) { False } else { True }
False => if lit_is_neg(l) { True } else { False }
}
}
+56
View File
@@ -0,0 +1,56 @@
// Specification of solver literals: variable `v` has the positive literal `2v`
// and the negative literal `2v + 1`.
///|
predicate var_ok(v : Int32) {
0 <= v && v < 1073741823
}
///|
predicate is_true(v : Val) {
match v {
True => true
_ => false
}
}
///|
predicate is_false(v : Val) {
match v {
False => true
_ => false
}
}
///|
predicate lit_true(v : Val, l : Int32) {
(is_true(v) && l % 2 == 0) || (is_false(v) && l % 2 == 1)
}
///|
predicate lit_false(v : Val, l : Int32) {
(is_false(v) && l % 2 == 0) || (is_true(v) && l % 2 == 1)
}
///|
/// `r` is the truth of literal `l` when its variable holds `v`.
predicate truth_ok(v : Val, l : Int32, r : Val) {
is_true(r) == lit_true(v, l) && is_false(r) == lit_false(v, l)
}
///|
predicate opposite(a : Val, b : Val) {
is_true(a) == is_false(b) && is_false(a) == is_true(b)
}
///|
/// Complementary literals never agree.
lemma truth_complement(v : Val, l : Int32, m : Int32, a : Val, b : Val) where {
proof_require: 0 <= l,
proof_require: 0 <= m,
proof_require: l % 2 != m % 2,
proof_require: truth_ok(v, l, a),
proof_require: truth_ok(v, m, b),
proof_ensure: opposite(a, b),
} {
}
+1
View File
@@ -0,0 +1 @@
proof_enabled = true
+33
View File
@@ -0,0 +1,33 @@
///|
/// Value of the decimal code points `s`, or -1 if `s` is empty, has a
/// non-digit, or is 10^18 or more.
pub fn parse_nat(
s : FixedArray[Int64],
) -> Int64 where {
proof_require: s.length() < 2147483647,
proof_ensure: r => parse_post(s, r),
proof_ensure: r => valid_or_rejected(r),
} {
let t = FixedArray::make(s.length() + 1, 0L)
for i in 0..<s.length() {
let n = t[i]
let c = s[i]
t[i + 1] = if n < 0L || n > 99999999999999999L || c < 48L || c > 57L {
-1L
} else {
n * 10L + (c - 48L)
}
} where {
proof_invariant: 0 <= i && i <= s.length(),
proof_invariant: trace(s, t, i, t[i]),
proof_invariant: valid_or_rejected(t[i]),
}
let r = t[s.length()]
proof_assert trace(s, t, s.length(), r)
proof_assert decimal(s, r)
if s.length() == 0 {
-1L
} else {
r
}
}
+52
View File
@@ -0,0 +1,52 @@
// Specification of `parse_nat`.
///|
predicate nat_ok(n : Int64) {
0L <= n && n <= 999999999999999999L
}
///|
/// `p` followed by the digit `c`, or -1 if `p` was already rejected, `c` is not
/// a digit, or the result is 10^18 or more.
fn append(p : Int64, c : Int64) -> Int64 {
if 0L <= p && p <= 99999999999999999L && 48L <= c && c <= 57L {
p * 10L + (c - 48L)
} else {
0L - 1L
}
}
///|
/// `t[i]` is the decimal value of the first `i` code points, for all `i <= n`.
predicate trace_ok(s : FixedArray[Int64], t : FixedArray[Int64], n : Int32) {
∀ i : Int32, (0 <= i && i < n) → t[i + 1] == append(t[i], s[i])
}
///|
predicate trace(
s : FixedArray[Int64],
t : FixedArray[Int64],
n : Int32,
r : Int64,
) {
t.length() == s.length() + 1 &&
t[0] == 0L &&
trace_ok(s, t, n) &&
t[n] == r
}
///|
/// `r` is the decimal value of `s`, or -1 as for `append`.
predicate decimal(s : FixedArray[Int64], r : Int64) {
∃ t : FixedArray[Int64], trace(s, t, s.length(), r)
}
///|
predicate parse_post(s : FixedArray[Int64], r : Int64) {
(s.length() == 0 && r == 0L - 1L) || (s.length() > 0 && decimal(s, r))
}
///|
predicate valid_or_rejected(r : Int64) {
r == 0L - 1L || nat_ok(r)
}
+40
View File
@@ -0,0 +1,40 @@
///|
/// Indices of `keys`, highest version first; equal versions keep their order.
pub fn sort_desc(
keys : FixedArray[Key],
) -> FixedArray[Int32] where {
proof_ensure: r => sort_post(keys, r),
} {
let idx = FixedArray::make(keys.length(), 0)
for i in 0..<keys.length() {
idx[i] = i
sink(keys, idx, i, i)
} where {
proof_invariant: 0 <= i && i <= keys.length(),
proof_invariant: sorted_prefix(keys, idx, i),
}
idx
}
///|
/// Move the entry at `j` left until the first `n + 1` entries are ordered.
fn sink(
keys : FixedArray[Key],
idx : FixedArray[Int32],
j : Int32,
n : Int32,
) -> Unit where {
proof_decrease: j,
proof_require: 0 <= j && j <= n && n < keys.length(),
proof_require: sinking(keys, idx, j, n),
proof_ensure: sorted_prefix(keys, idx, n + 1),
} {
if j > 0 && compare(keys[idx[j]], keys[idx[j - 1]]) > 0 {
let t = idx[j]
idx[j] = idx[j - 1]
idx[j - 1] = t
sink(keys, idx, j - 1, n)
} else {
()
}
}
+87
View File
@@ -0,0 +1,87 @@
// Specification of `sort_desc`: the result lists every index of `keys` once,
// highest version first, ties in their original order.
///|
predicate same_length(keys : FixedArray[Key], idx : FixedArray[Int32]) {
idx.length() == keys.length()
}
///|
/// The first `n` entries are all below `n`.
predicate below(idx : FixedArray[Int32], n : Int32) {
∀ p : Int32, (0 <= p && p < n) → (0 <= idx[p] && idx[p] < n)
}
///|
predicate distinct(idx : FixedArray[Int32], n : Int32) {
∀ p : Int32, ∀ q : Int32, (0 <= p && p < q && q < n) → idx[p] != idx[q]
}
///|
/// Index `i` comes before index `j` in the result.
predicate before(keys : FixedArray[Key], i : Int32, j : Int32) {
key_lt(keys[j], keys[i]) || (key_eq(keys[j], keys[i]) && i < j)
}
///|
predicate ordered(keys : FixedArray[Key], idx : FixedArray[Int32], n : Int32) {
∀ p : Int32, ∀ q : Int32, (0 <= p && p < q && q < n) →
before(keys, idx[p], idx[q])
}
///|
/// Everything in `(j, n]` comes after the entry being inserted at `j`.
predicate after_hole(
keys : FixedArray[Key],
idx : FixedArray[Int32],
j : Int32,
n : Int32,
) {
∀ q : Int32, (j < q && q <= n) → before(keys, idx[j], idx[q])
}
///|
/// The first `n + 1` entries are ordered, ignoring the one at `j`.
predicate ordered_except(
keys : FixedArray[Key],
idx : FixedArray[Int32],
j : Int32,
n : Int32,
) {
∀ p : Int32, ∀ q : Int32, (0 <= p && p < q && q <= n && p != j && q != j) →
before(keys, idx[p], idx[q])
}
///|
predicate sort_post(keys : FixedArray[Key], idx : FixedArray[Int32]) {
sorted_prefix(keys, idx, keys.length())
}
///|
/// The first `n` entries are `0..<n`, reordered.
predicate sorted_prefix(
keys : FixedArray[Key],
idx : FixedArray[Int32],
n : Int32,
) {
same_length(keys, idx) &&
below(idx, n) &&
distinct(idx, n) &&
ordered(keys, idx, n)
}
///|
/// Entry `n` is being inserted and has reached position `j`.
predicate sinking(
keys : FixedArray[Key],
idx : FixedArray[Int32],
j : Int32,
n : Int32,
) {
same_length(keys, idx) &&
below(idx, n + 1) &&
distinct(idx, n + 1) &&
idx[j] == n &&
after_hole(keys, idx, j, n) &&
ordered_except(keys, idx, j, n)
}
+115
View File
@@ -0,0 +1,115 @@
///|
/// A version reduced to integers. `pre` ranks the prerelease: callers must give
/// equal prereleases equal ranks and order the others as they compare.
pub(all) struct Key {
major : Int64
minor : Int64
patch : Int64
pre : Int32
}
///|
#derive(Eq, Debug)
pub(all) enum Op {
Any
Ge
Le
Gt
Lt
Eq
Ne
Caret
Tilde
Prefix
NotPrefix
}
///|
pub extend Op with Eq::{equal, not_equal}
///|
pub extend Op with Debug::{to_repr}
///|
/// -1, 0 or 1 as `a` is below, equal to or above `b`.
pub fn compare(
a : Key,
b : Key,
) -> Int32 where {
proof_ensure: r => compare_post(a, b, r),
} {
if a.major < b.major {
-1
} else if a.major > b.major {
1
} else if a.minor < b.minor {
-1
} else if a.minor > b.minor {
1
} else if a.patch < b.patch {
-1
} else if a.patch > b.patch {
1
} else if a.pre < b.pre {
-1
} else if a.pre > b.pre {
1
} else {
0
}
}
///|
/// Whether `v` satisfies the clause `op b`, where `b` was written with `parts`
/// components.
pub fn matches(
op : Op,
v : Key,
b : Key,
parts : Int32,
) -> Bool where {
proof_require: key_inv(v),
proof_require: key_inv(b),
proof_require: 1 <= parts && parts <= 3,
proof_ensure: r => r == allowed(op, v, b, parts),
} {
match op {
Any => true
Ge => compare(v, b) >= 0
Le => compare(v, b) <= 0
Gt => compare(v, b) > 0
Lt => compare(v, b) < 0
Eq => compare(v, b) == 0
Ne => compare(v, b) != 0
Caret =>
compare(v, b) >= 0 &&
v.major == b.major &&
(b.major != 0L || v.minor == b.minor)
Tilde =>
compare(v, b) >= 0 &&
v.major == b.major &&
(parts == 1 || v.minor == b.minor)
Prefix => same_prefix(v, b, parts)
NotPrefix => !same_prefix(v, b, parts)
}
}
///|
fn same_prefix(
v : Key,
b : Key,
parts : Int32,
) -> Bool where {
proof_require: key_inv(v),
proof_require: key_inv(b),
proof_require: 1 <= parts && parts <= 3,
proof_ensure: r => r == in_prefix(v, b, parts),
} {
if parts == 1 {
v.major == b.major
} else if parts == 2 {
v.major == b.major && v.minor == b.minor
} else {
true
}
}
+140
View File
@@ -0,0 +1,140 @@
// Specification of versions: a key is ordered lexicographically, and every
// constraint operator is an interval of that order.
///|
predicate key_inv(k : Key) {
nat_ok(k.major) && nat_ok(k.minor) && nat_ok(k.patch)
}
///|
predicate core_lt(a : Key, b : Key) {
a.major < b.major ||
(a.major == b.major && a.minor < b.minor) ||
(a.major == b.major && a.minor == b.minor && a.patch < b.patch)
}
///|
predicate core_eq(a : Key, b : Key) {
a.major == b.major && a.minor == b.minor && a.patch == b.patch
}
///|
predicate key_lt(a : Key, b : Key) {
core_lt(a, b) || (core_eq(a, b) && a.pre < b.pre)
}
///|
predicate key_eq(a : Key, b : Key) {
core_eq(a, b) && a.pre == b.pre
}
///|
predicate key_le(a : Key, b : Key) {
key_lt(a, b) || key_eq(a, b)
}
///|
predicate not_lt(a : Key, b : Key) {
!key_lt(a, b)
}
///|
predicate compare_post(a : Key, b : Key, r : Int32) {
(r == 0 || r == 1 || r == -1) &&
((r == -1) == key_lt(a, b)) &&
((r == 0) == key_eq(a, b)) &&
((r == 1) == key_lt(b, a))
}
// Laws of the order: these say `compare` is a total order.
///|
lemma key_lt_irreflexive(a : Key) where {
proof_ensure: not_lt(a, a),
} {
}
///|
lemma key_lt_asymmetric(a : Key, b : Key) where {
proof_require: key_lt(a, b),
proof_ensure: not_lt(b, a),
} {
}
///|
lemma key_lt_transitive(a : Key, b : Key, c : Key) where {
proof_require: key_lt(a, b),
proof_require: key_lt(b, c),
proof_ensure: key_lt(a, c),
} {
}
///|
predicate comparable(a : Key, b : Key) {
key_lt(a, b) || key_eq(a, b) || key_lt(b, a)
}
///|
lemma key_lt_total(a : Key, b : Key) where {
proof_ensure: comparable(a, b),
} {
}
///|
/// `v`'s core is below the first version of the next major.
predicate below_next_major(v : Key, b : Key) {
v.major < b.major + 1L
}
///|
/// `v`'s core is below the first version of the next minor.
predicate below_next_minor(v : Key, b : Key) {
v.major < b.major || (v.major == b.major && v.minor < b.minor + 1L)
}
///|
predicate from_major(v : Key, b : Key) {
b.major <= v.major
}
///|
predicate from_minor(v : Key, b : Key) {
b.major < v.major || (b.major == v.major && b.minor <= v.minor)
}
///|
/// Half-open core interval covered by a one- or two-part prefix.
predicate in_prefix(v : Key, b : Key, parts : Int32) {
(parts == 1 && from_major(v, b) && below_next_major(v, b)) ||
(parts == 2 && from_minor(v, b) && below_next_minor(v, b)) ||
parts == 3
}
///|
predicate in_caret(v : Key, b : Key) {
(b.major != 0L && key_le(b, v) && below_next_major(v, b)) ||
(b.major == 0L && key_le(b, v) && below_next_minor(v, b))
}
///|
predicate in_tilde(v : Key, b : Key, parts : Int32) {
(parts == 1 && key_le(b, v) && below_next_major(v, b)) ||
(parts != 1 && key_le(b, v) && below_next_minor(v, b))
}
///|
predicate allowed(op : Op, v : Key, b : Key, parts : Int32) {
match op {
Any => true
Ge => key_le(b, v)
Le => key_le(v, b)
Gt => key_lt(b, v)
Lt => key_lt(v, b)
Eq => key_eq(v, b)
Ne => !key_eq(v, b)
Caret => in_caret(v, b)
Tilde => in_tilde(v, b, parts)
Prefix => in_prefix(v, b, parts)
NotPrefix => !in_prefix(v, b, parts)
}
}
+442
View File
@@ -0,0 +1,442 @@
// Registry credentials stored in $ORBIT_ROOT/auth.json, with read fallback
// to $DOCKER_CONFIG/config.json (or ~/.docker/config.json).
///|
struct Creds {
username : String
password : String
}
///|
fn strip_url_scheme(s : String) -> String {
if has_prefix(s, "https://") {
drop_chars(s, 8)
} else if has_prefix(s, "http://") {
drop_chars(s, 7)
} else {
s
}
}
///|
fn ascii_lower(s : String) -> String {
let sb = StringBuilder()
for c in s {
if c >= 'A' && c <= 'Z' {
sb.write_char(Int32::unsafe_to_char(c.to_int() + 32))
} else {
sb.write_char(c)
}
}
sb.to_string()
}
///|
fn normalize_host(raw : String) -> String {
let t = trim(raw)
let no_scheme = if has_prefix(ascii_lower(t), "https://") {
drop_chars(t, 8)
} else if has_prefix(ascii_lower(t), "http://") {
drop_chars(t, 7)
} else {
t
}
let (host, _) = split_first(no_scheme, '/')
ascii_lower(trim(host))
}
///|
fn is_docker_hub_host(h : String) -> Bool {
h == "docker.io" || h == "registry-1.docker.io" || h == "index.docker.io"
}
///|
fn host_matches(stored_key : String, host : String) -> Bool {
let a = normalize_host(stored_key)
let b = normalize_host(host)
if a == "" || b == "" {
return false
}
if a == b {
return true
}
is_docker_hub_host(a) && is_docker_hub_host(b)
}
///|
fn auth_file_path(root : String) -> String {
root + "/auth.json"
}
///|
fn docker_config_path() -> String {
let dir = getenv("DOCKER_CONFIG")
if dir != "" {
dir + "/config.json"
} else {
getenv("HOME") + "/.docker/config.json"
}
}
///|
fn encode_basic_auth(creds : Creds) -> String {
let raw = utf8_encode(creds.username + ":" + creds.password)
@base64.encode(raw[:])
}
///|
fn decode_basic_auth(b64 : String) -> Creds? {
let raw = @base64.decode(trim(b64), ignore_whitespace=true) catch {
_ => return None
}
let decoded = utf8_decode(raw)
if !has_char(decoded, ':') {
return None
}
let (username, password) = split_first(decoded, ':')
if username == "" && password == "" {
return None
}
Some(Creds::{ username, password })
}
///|
async fn creds_from_helper(
helper : String,
server_url : String,
) -> Creds? noraise {
if helper == "" || has_char(helper, '/') || has_char(helper, ' ') {
return None
}
let bin = "docker-credential-" + helper
let (code, stdout) = run_with_stdin(bin, ["get"], server_url + "\n") catch {
_ => return None
}
if code != 0 {
return None
}
let obj = parse_object(stdout, "credential helper") catch { _ => return None }
let username = jstr(obj, "Username", "")
let password = jstr(obj, "Secret", "")
if username == "" && password == "" {
None
} else {
Some(Creds::{ username, password })
}
}
///|
async fn load_creds_from_file(path : String, host : String) -> Creds? noraise {
let text = match read_text(path) {
Some(t) => t
None => return None
}
let top = parse_object(text, path) catch { _ => return None }
match top.get("credHelpers") {
Some(Json::Object(helpers)) =>
for k, v in helpers {
if host_matches(k, host) {
match v {
Json::String(helper) =>
if helper != "" {
match creds_from_helper(helper, k) {
Some(c) => return Some(c)
None =>
if k != host {
match creds_from_helper(helper, host) {
Some(c) => return Some(c)
None => ()
}
}
}
}
_ => ()
}
}
}
_ => ()
}
match top.get("auths") {
Some(Json::Object(auths)) =>
for k, v in auths {
if host_matches(k, host) {
match v {
Json::Object(entry) => {
let b64 = jstr(entry, "auth", "")
if b64 != "" {
match decode_basic_auth(b64) {
Some(c) => return Some(c)
None => ()
}
}
let u = jstr(entry, "username", "")
let p = jstr(entry, "password", "")
if u != "" || p != "" {
return Some(Creds::{ username: u, password: p })
}
}
_ => ()
}
}
}
_ => ()
}
let store = jstr(top, "credsStore", "")
if store != "" {
match creds_from_helper(store, host) {
Some(c) => return Some(c)
None =>
if is_docker_hub_host(normalize_host(host)) {
return creds_from_helper(store, "https://index.docker.io/v1/")
}
}
}
None
}
///|
async fn load_creds(host : String) -> Creds? noraise {
let nhost = normalize_host(host)
if nhost == "" {
return None
}
match load_creds_from_file(auth_file_path(orbit_root()), nhost) {
Some(c) => Some(c)
None => load_creds_from_file(docker_config_path(), nhost)
}
}
///|
async fn save_creds(
root : String,
host : String,
creds : Creds,
) -> Unit raise OrbitError {
let nhost = normalize_host(host)
let path = auth_file_path(root)
let top = match read_text(path) {
Some(t) => parse_object(t, "auth.json")
None => Map([])
}
let auths : Map[String, Json] = match top.get("auths") {
Some(Json::Object(m)) => m
None => Map([])
_ => raise OrbitError("auth.json: expected 'auths' to be an object")
}
let stale : Array[String] = []
for k, _ in auths {
if host_matches(k, nhost) {
stale.push(k)
}
}
for k in stale {
auths.remove(k)
}
let entry : Map[String, Json] = Map([])
entry["auth"] = Json::string(encode_basic_auth(creds))
auths[nhost] = Json::object(entry)
top["auths"] = Json::object(auths)
@fs.mkdir(root, recursive=true, allow_exist=true) catch {
e => raise OrbitError("cannot create \{root}: \{e}")
}
write_secret_atomic(path, Json::object(top).stringify(indent=2) + "\n")
}
///|
async fn remove_creds(root : String, host : String) -> Bool raise OrbitError {
let nhost = normalize_host(host)
let path = auth_file_path(root)
let text = match read_text(path) {
Some(t) => t
None => return false
}
let top = parse_object(text, "auth.json")
let auths : Map[String, Json] = match top.get("auths") {
Some(Json::Object(m)) => m
None => return false
_ => raise OrbitError("auth.json: expected 'auths' to be an object")
}
let matching : Array[String] = []
for k, _ in auths {
if host_matches(k, nhost) {
matching.push(k)
}
}
if matching.length() == 0 {
return false
}
for k in matching {
auths.remove(k)
}
top["auths"] = Json::object(auths)
write_secret_atomic(path, Json::object(top).stringify(indent=2) + "\n")
true
}
///|
fn strip_trailing_cr(s : String) -> String {
let a = chars(s)
let mut end = a.length()
if end > 0 && a[end - 1] == '\r' {
end = end - 1
}
slice(a, 0, end)
}
///|
fn strip_trailing_newlines(s : String) -> String {
let a = chars(s)
let mut end = a.length()
while end > 0 && (a[end - 1] == '\n' || a[end - 1] == '\r') {
end = end - 1
}
slice(a, 0, end)
}
///|
async fn read_stdin_line() -> String raise OrbitError {
let line = @stdio.stdin.read_until("\n") catch {
e => raise OrbitError("cannot read stdin: \{e}")
}
match line {
Some(s) => strip_trailing_cr(s)
None => ""
}
}
///|
async fn read_password_prompt() -> String raise OrbitError {
c_print_err(utf8_encode("Password: "))
let echo_disabled = c_set_echo(0) == 0
defer {
if echo_disabled {
ignore(c_set_echo(1))
c_print_err(utf8_encode("\n"))
}
}
read_stdin_line()
}
///|
async fn resolve_login_plain_http(
raw_host : String,
host : String,
plain_http_flag : Bool,
) -> Bool raise OrbitError {
let lower = ascii_lower(trim(raw_host))
if plain_http_flag || has_prefix(lower, "http://") {
return true
}
if has_prefix(lower, "https://") {
return false
}
let ctx = load_ctx()
for ch in ctx.channels {
let (ch_host, _) = split_first(ch.url, '/')
if host_matches(ch_host, host) && ch.plain_http {
return true
}
}
false
}
///|
async fn cmd_login(
raw_host : String,
username_opt : String?,
password_opt : String?,
password_stdin : Bool,
plain_http_flag : Bool,
) -> Unit raise OrbitError {
if password_opt is Some(_) && password_stdin {
raise OrbitError("use either --password or --password-stdin, not both")
}
let host = normalize_host(raw_host)
if host == "" || has_char(host, ' ') || has_char(host, '\t') {
raise OrbitError("invalid registry host '\{raw_host}'")
}
let plain_http = resolve_login_plain_http(raw_host, host, plain_http_flag)
let username = match username_opt {
Some(u) => u
None => {
c_print_err(utf8_encode("Username: "))
trim(read_stdin_line())
}
}
let password = if password_stdin {
let raw = @stdio.stdin.read_all().text() catch {
e => raise OrbitError("cannot read password from stdin: \{e}")
}
strip_trailing_newlines(raw)
} else {
match password_opt {
Some(p) => p
None => read_password_prompt()
}
}
if username == "" && password == "" {
raise OrbitError("username or password is required")
}
let creds = Creds::{ username, password }
with_spinner("Logging in to \{host}", () => {
verify_login(host, plain_http, creds)
})
save_creds(orbit_root(), host, creds)
println("Login succeeded for \{host}")
}
///|
async fn cmd_logout(raw_host : String) -> Unit raise OrbitError {
let host = normalize_host(raw_host)
if host == "" {
raise OrbitError("invalid registry host '\{raw_host}'")
}
if remove_creds(orbit_root(), host) {
println("Removed credentials for \{host}")
} else {
println("No stored credentials for \{host}")
}
let docker_path = docker_config_path()
match load_creds_from_file(docker_path, host) {
Some(_) =>
println("note: credentials for \{host} still exist in \{docker_path}")
None => ()
}
}
///|
test "host normalization and matching" {
assert_eq(normalize_host("https://git.site.latha.org/nandi"), "git.site.latha.org")
assert_eq(normalize_host("http://localhost:5000/"), "localhost:5000")
assert_true(host_matches("https://index.docker.io/v1/", "registry-1.docker.io"))
assert_true(host_matches("docker.io", "index.docker.io"))
assert_false(host_matches("ghcr.io", "git.site.latha.org"))
}
///|
test "basic auth encode and decode roundtrip" {
let c = Creds::{ username: "nandi", password: "s:e:c/r+e=t" }
let b64 = encode_basic_auth(c)
let decoded = decode_basic_auth(b64).unwrap()
assert_eq(decoded.username, "nandi")
assert_eq(decoded.password, "s:e:c/r+e=t")
assert_true(decode_basic_auth("not-valid-b64!!!") is None)
assert_true(decode_basic_auth(@base64.encode(b"nocolon"[:])) is None)
}
///|
async test "save and remove credentials in auth.json" {
let root = @fs.tmpdir(prefix="orbit-auth-test-")
defer (@fs.rmdir(root, recursive=true, allow_missing=true) catch { _ => () })
let c = Creds::{ username: "alice", password: "secret" }
save_creds(root, "https://git.site.latha.org", c)
let loaded = load_creds_from_file(auth_file_path(root), "git.site.latha.org")
guard loaded is Some(got) else { fail("expected saved credentials") }
assert_eq(got.username, "alice")
assert_eq(got.password, "secret")
assert_true(remove_creds(root, "git.site.latha.org"))
assert_true(
load_creds_from_file(auth_file_path(root), "git.site.latha.org") is None,
)
assert_false(remove_creds(root, "git.site.latha.org"))
}
+8 -8
View File
@@ -162,7 +162,7 @@ fn parse_legacy_config(text : String) -> Array[Channel] raise OrbitError {
}
///|
fn load_listed_channels(root : String) -> Array[Channel] raise OrbitError {
async fn load_listed_channels(root : String) -> Array[Channel] raise OrbitError {
match read_text(root + "/config.toml") {
Some(t) => parse_config(t)
None =>
@@ -186,7 +186,7 @@ fn channel_toml(c : Channel) -> String {
///|
/// Append a channel at the lowest priority, keeping the file's comments.
fn cmd_channel_add(
async fn cmd_channel_add(
root : String,
name : String,
url : String,
@@ -264,7 +264,7 @@ fn split_channel(spec : String) -> (String?, String) {
/// The channel to get `name` from, with its tags there. A pinned channel is
/// used as is. Otherwise the first channel that has the package wins, even if
/// a lower one has a newer version.
fn locate(
async fn locate(
ctx : Ctx,
name : String,
pin : String?,
@@ -349,9 +349,9 @@ test "channel spec" {
///|
test "only a missing repository falls through to the next channel" {
assert_true(is_missing_repo("Error response from registry: name unknown"))
assert_true(is_missing_repo("GET \"u\": response status code 404: Not Found"))
assert_false(is_missing_repo("dial tcp: lookup x: no such host"))
assert_false(is_missing_repo("connect: connection refused"))
assert_false(is_missing_repo("response status code 401: Unauthorized"))
assert_true(is_missing_status(404))
assert_false(is_missing_status(401))
assert_false(is_missing_status(403))
assert_false(is_missing_status(500))
assert_false(is_missing_status(502))
}
+231 -37
View File
@@ -1,36 +1,55 @@
// orbit: a package manager whose repository is any OCI registry, via ORAS.
// orbit: a package manager whose repository is any OCI registry.
///|
let usage : String =
#|orbit - packages as OCI artifacts (via oras)
#|orbit - packages as OCI artifacts
#|
#|usage:
#| orbit init create folders and config.toml
#|usage (project workflow, when orbit.toml is present):
#| orbit new [dir] create a project orbit.toml
#| orbit add [channel::]<name>[@constraint]...
#| solve, pin in orbit.toml, lock & sync
#| orbit install [--locked | --frozen] sync .orbit/ from orbit.toml / orbit.lock
#| orbit sync [--locked | --frozen] same as `orbit install` in a project
#| orbit lock [--update] resolve and write orbit.lock
#| orbit update [name...] upgrade locked packages within constraints
#| orbit remove <name>... remove from orbit.toml, re-lock & sync
#| orbit run [--locked | --frozen] <cmd|task> [args...]
#| run a command or [tasks] entry in .orbit
#| orbit list show locked project packages
#| orbit env print PATH for .orbit/bin + global bin
#|
#|usage (global & registry commands; add -g/--global inside a project):
#| orbit init [--project] create ~/.orbit (or --project for orbit.toml)
#| orbit login <host> [-u <user>] [-p <pass> | --password-stdin] [--plain-http]
#| log in to an OCI registry
#| orbit logout <host> remove stored registry credentials
#| orbit channel list channels, highest priority first
#| orbit channel add <name> <url> [--plain-http]
#| orbit publish <dir> [--channel <name>] [--no-latest]
#| push <dir>/orbit.json + <dir>/files/
#| orbit install [channel::]<name>[@constraint]...
#| install with dependencies
#| orbit remove <name>... [--force] remove, then drop unused dependencies
#| orbit upgrade [name...] upgrade within constraints
#| orbit rollback <name> switch to the previous build
#| orbit list installed packages
#| orbit info <name> local and remote details
#| orbit install [-g] [channel::]<name>[@constraint]...
#| install globally with SAT dependency solving
#| orbit remove [-g] <name>... [--force] remove, then drop unused dependencies
#| orbit upgrade [-g] [name...] jointly upgrade within constraints
#| orbit rollback <name> switch to the previous global build
#| orbit list [-g] installed global packages
#| orbit info [channel::]<name> installed package details (local only)
#| orbit versions <name> published versions
#| orbit search [term] list repositories (needs catalog API)
#| orbit gc delete unused builds from the store
#| orbit env print the PATH line for your shell
#| orbit env [-g] print the PATH line for your shell
#|
#|constraints: 1.2.3 =1.2.3 1.2 ^1.2.0 ~1.2.0 >=1.2 *
#|flags: -g, --global --manifest-path <path> --locked --frozen
#|constraints: 1.2.3 =1.2.3 ==1.2.3 1.2.* ^1.2.0 ~1.2.0 >=1.2 <2.0 !=1.3.0 *
#| (comma-separated clauses are ANDed, e.g. ">=1.2.0, <2.0.0")
#|config: <orbit root>/config.toml
#|credentials: <orbit root>/auth.json (falls back to ~/.docker/config.json)
#|environment: ORBIT_ROOT (default ~/.orbit); ORBIT_REGISTRY and
#| ORBIT_PLAIN_HTTP=1 override the built-in main channel
#|authentication: run `oras login <registry-host>` once.
///|
/// Create the directories, and a config.toml if there is no config yet.
fn cmd_init() -> Unit raise OrbitError {
async fn cmd_init() -> Unit raise OrbitError {
let root = orbit_root()
sh_ok(
"mkdir -p " +
@@ -60,7 +79,35 @@ fn need(pos : Array[String], n : Int32, what : String) -> Unit raise OrbitError
}
///|
fn dispatch(args : Array[String]) -> Unit raise OrbitError {
async fn resolve_project_or_none(
force_global : Bool,
manifest_path : String?,
) -> String? raise OrbitError {
if force_global {
if manifest_path is Some(_) {
raise OrbitError("--global cannot be used with --manifest-path")
}
None
} else {
find_project_manifest(manifest_path)
}
}
///|
async fn require_project_manifest(
manifest_path : String?,
) -> String raise OrbitError {
match find_project_manifest(manifest_path) {
Some(mf) => mf
None =>
raise OrbitError(
"no orbit.toml found in current or parent directories (run `orbit new` to create one)",
)
}
}
///|
async fn dispatch(args : Array[String]) -> Unit raise OrbitError {
if args.length() == 0 {
println(usage)
return
@@ -69,30 +116,111 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError {
let pos : Array[String] = []
let flags : Array[String] = []
let mut publish_to = MAIN_CHANNEL
let mut username : String? = None
let mut password : String? = None
let mut force_global = false
let mut manifest_path : String? = None
let mut i = 1
while i < args.length() {
if args[i] == "--channel" {
if cmd == "run" && pos.length() > 0 {
// Forward all flags/args after the command/task name verbatim.
pos.push(args[i])
i = i + 1
continue
}
let a = args[i]
if a == "--" {
i = i + 1
while i < args.length() {
pos.push(args[i])
i = i + 1
}
break
} else if a == "-g" || a == "--global" {
force_global = true
} else if a == "--manifest-path" {
if i + 1 >= args.length() {
raise OrbitError("usage: --manifest-path <path>")
}
manifest_path = Some(args[i + 1])
i = i + 1
} 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 <dir> --channel <name>")
}
publish_to = args[i + 1]
i = i + 1
} else if has_prefix(args[i], "--") {
flags.push(args[i])
} else if a == "-u" || a == "--username" {
if cmd != "login" || i + 1 >= args.length() {
raise OrbitError(
"usage: orbit login <host> [-u <user>] [-p <pass> | --password-stdin] [--plain-http]",
)
}
username = Some(args[i + 1])
i = i + 1
} else if has_prefix(a, "--username=") {
if cmd != "login" {
raise OrbitError("unknown flag '\{a}'")
}
username = Some(drop_chars(a, 11))
} else if a == "-p" || a == "--password" {
if cmd != "login" || i + 1 >= args.length() {
raise OrbitError(
"usage: orbit login <host> [-u <user>] [-p <pass> | --password-stdin] [--plain-http]",
)
}
password = Some(args[i + 1])
i = i + 1
} else if has_prefix(a, "--password=") {
if cmd != "login" {
raise OrbitError("unknown flag '\{a}'")
}
password = Some(drop_chars(a, 11))
} else if has_prefix(a, "--") {
flags.push(a)
} else {
pos.push(args[i])
pos.push(a)
}
i = i + 1
}
match cmd {
"help" | "-h" | "--help" => println(usage)
"init" => {
if pos.length() > 0 {
raise OrbitError(
"init takes no arguments; use `orbit channel add <name> <url>`",
)
"new" => {
if force_global {
raise OrbitError("--global cannot be used with `orbit new`")
}
cmd_init()
cmd_project_init(if pos.length() > 0 { Some(pos[0]) } else { None })
}
"init" =>
if flags.contains("--project") {
cmd_project_init(if pos.length() > 0 { Some(pos[0]) } else { None })
} else {
if pos.length() > 0 {
raise OrbitError(
"init takes no arguments; use `orbit channel add <name> <url>` or `orbit new <dir>`",
)
}
cmd_init()
}
"login" => {
need(
pos,
1,
"login <host> [-u <user>] [-p <pass> | --password-stdin] [--plain-http]",
)
cmd_login(
pos[0],
username,
password,
flags.contains("--password-stdin"),
flags.contains("--plain-http"),
)
}
"logout" => {
need(pos, 1, "logout <host>")
cmd_logout(pos[0])
}
"channel" => {
need(pos, 1, "channel list|add")
@@ -110,22 +238,92 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError {
other => raise OrbitError("unknown channel command '\{other}'")
}
}
"env" => println("export PATH=\"\{orbit_root()}/bin:$PATH\"")
"lock" => {
if force_global {
raise OrbitError("--global cannot be used with `orbit lock`")
}
let mf = require_project_manifest(manifest_path)
cmd_project_lock(load_ctx(), mf, flags.contains("--update"))
}
"sync" => {
if force_global {
raise OrbitError("--global cannot be used with `orbit sync`")
}
let mf = require_project_manifest(manifest_path)
cmd_project_sync(
load_ctx(),
mf,
flags.contains("--locked"),
flags.contains("--frozen"),
)
}
"run" => {
if force_global {
raise OrbitError("--global cannot be used with `orbit run`")
}
let mf = require_project_manifest(manifest_path)
need(pos, 1, "run [--locked|--frozen] <command|task> [args...]")
cmd_project_run(
load_ctx(),
mf,
pos,
flags.contains("--locked"),
flags.contains("--frozen"),
)
}
"env" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_env(load_ctx(), mf)
None => println("export PATH=\"\{orbit_root()}/bin:$PATH\"")
}
"publish" => {
need(pos, 1, "publish <dir>")
let ch = find_channel(load_ctx(), publish_to)
publish(ch, pos[0], !flags.contains("--no-latest"))
}
"install" | "add" => cmd_install(load_ctx(), pos)
"remove" | "rm" => cmd_remove(load_ctx(), pos, flags.contains("--force"))
"upgrade" | "up" => cmd_upgrade(load_ctx(), pos)
"install" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) =>
if pos.length() == 0 {
cmd_project_sync(
load_ctx(),
mf,
flags.contains("--locked"),
flags.contains("--frozen"),
)
} else {
raise OrbitError(
"in a project (found \{mf}), use `orbit add <pkg>...` to add dependencies or `orbit install -g <pkg>...` to install globally",
)
}
None => cmd_install(load_ctx(), pos)
}
"add" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_add(load_ctx(), mf, pos)
None => cmd_install(load_ctx(), pos)
}
"remove" | "rm" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_remove(load_ctx(), mf, pos)
None => cmd_remove(load_ctx(), pos, flags.contains("--force"))
}
"upgrade" | "up" | "update" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_update(load_ctx(), mf, pos)
None => cmd_upgrade(load_ctx(), pos)
}
"rollback" => {
need(pos, 1, "rollback <name>")
cmd_rollback(load_ctx(), pos[0])
}
"list" | "ls" => cmd_list(load_ctx())
"list" | "ls" =>
match resolve_project_or_none(force_global, manifest_path) {
Some(mf) => cmd_project_list(load_ctx(), mf)
None => cmd_list(load_ctx())
}
"info" => {
need(pos, 1, "info <name>")
need(pos, 1, "info [channel::]<name>")
cmd_info(load_ctx(), pos[0])
}
"versions" => {
@@ -140,11 +338,7 @@ fn dispatch(args : Array[String]) -> Unit raise OrbitError {
}
///|
fn main {
if sh("command -v oras >/dev/null 2>&1") != 0 {
println("orbit: error: `oras` not found on PATH (https://oras.land)")
c_exit(1)
}
async fn main {
dispatch(cli_args()) catch {
OrbitError(msg) => {
println("orbit: error: \{msg}")
+76 -5
View File
@@ -3,6 +3,10 @@
///|
const CONFIG_MEDIA_TYPE : String = "application/vnd.latha.orbit.config.v1+json"
///|
/// Manifest artifactType that marks a repository as an Orbit package.
const ORBIT_ARTIFACT_TYPE : String = "application/vnd.latha.orbit.v1"
///|
const LAYER_MEDIA_TYPE : String = "application/vnd.latha.orbit.layer.v1.tar+gzip"
@@ -23,6 +27,7 @@ struct Gen {
channel : String
version : String
digest : String
description : String
bins : Array[String]
depends : Map[String, String]
}
@@ -33,6 +38,7 @@ struct Installed {
mut channel : String
mut version : String
mut digest : String
mut description : String
mut explicit : Bool
mut constraint : String
mut bins : Array[String]
@@ -173,6 +179,21 @@ fn valid_rel_path(p : String) -> Bool {
true
}
///|
/// Split a dependency key "[channel::]name" into (channel_pin, package_name).
fn parse_dep_key(key : String) -> (String?, String) {
split_channel(key)
}
///|
fn valid_dep_key(key : String) -> Bool {
let (ch, name) = parse_dep_key(key)
match ch {
Some(c) => valid_name(c) && valid_name(name)
None => valid_name(name)
}
}
///|
fn parse_manifest(text : String) -> Manifest raise OrbitError {
let o = parse_object(text, "orbit.json")
@@ -197,10 +218,15 @@ fn parse_manifest(text : String) -> Manifest raise OrbitError {
raise OrbitError("orbit.json: bin path '\{b}' must be relative")
}
}
for dep, _ in m.depends {
if !valid_name(dep) {
for dep, constraint in m.depends {
if !valid_dep_key(dep) {
raise OrbitError("orbit.json: invalid dependency name '\{dep}'")
}
if !valid_constraint(constraint) {
raise OrbitError(
"orbit.json: invalid version constraint '\{constraint}' for '\{dep}'",
)
}
}
m
}
@@ -213,6 +239,7 @@ fn gen_json(g : Gen) -> Json {
o["channel"] = Json::string(g.channel)
o["version"] = Json::string(g.version)
o["digest"] = Json::string(g.digest)
o["description"] = Json::string(g.description)
o["bin"] = strs_json(g.bins)
o["depends"] = map_json(g.depends)
Json::object(o)
@@ -224,6 +251,7 @@ fn installed_json(p : Installed) -> Json {
o["channel"] = Json::string(p.channel)
o["version"] = Json::string(p.version)
o["digest"] = Json::string(p.digest)
o["description"] = Json::string(p.description)
o["explicit"] = bool_json(p.explicit)
o["constraint"] = Json::string(p.constraint)
o["bin"] = strs_json(p.bins)
@@ -267,6 +295,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError {
channel: jstr(h, "channel", MAIN_CHANNEL),
version: jstr(h, "version", ""),
digest: jstr(h, "digest", ""),
description: jstr(h, "description", ""),
bins: jstrs(h, "bin"),
depends: jmap(h, "depends"),
})
@@ -280,6 +309,7 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError {
channel: jstr(o, "channel", MAIN_CHANNEL),
version: jstr(o, "version", ""),
digest: jstr(o, "digest", ""),
description: jstr(o, "description", ""),
explicit: jbool(o, "explicit", false),
constraint: jstr(o, "constraint", "*"),
bins: jstrs(o, "bin"),
@@ -295,6 +325,17 @@ fn state_from_text(text : String) -> Map[String, Installed] raise OrbitError {
out
}
///|
test "installed and rollback descriptions round trip with legacy entries" {
let text =
#|{"packages":{"tool":{"description":"Current build","history":[{"description":"Previous build"},{}]}}}
let state = state_from_text(state_to_text(state_from_text(text)))
guard state.get("tool") is Some(p) else { fail("missing installed package") }
assert_eq(p.description, "Current build")
assert_eq(p.history[0].description, "Previous build")
assert_eq(p.history[1].description, "")
}
// ---------------------------------------------------------------- context
///|
@@ -309,7 +350,7 @@ fn orbit_root() -> String {
///|
/// Load channels and state.
fn load_ctx() -> Ctx raise OrbitError {
async fn load_ctx() -> Ctx raise OrbitError {
let root = orbit_root()
let channels = resolve_channels(
load_listed_channels(root),
@@ -324,7 +365,7 @@ fn load_ctx() -> Ctx raise OrbitError {
}
///|
fn save_state(ctx : Ctx) -> Unit raise OrbitError {
async fn save_state(ctx : Ctx) -> Unit raise OrbitError {
write_text_atomic(ctx.root + "/state.json", state_to_text(ctx.state))
}
@@ -346,15 +387,45 @@ fn bin_dir(ctx : Ctx) -> String {
ctx.root + "/bin"
}
///|
fn cache_dir(root : String) -> String {
root + "/cache/manifests"
}
///|
test "manifest roundtrip" {
let m = parse_manifest(
"{\"name\":\"hello\",\"version\":\"1.0.0\",\"bin\":[\"bin/hello\"],\"depends\":{\"lib\":\"^1\"}}",
"{\"name\":\"hello\",\"version\":\"1.0.0\",\"bin\":[\"bin/hello\"],\"depends\":{\"lib\":\"^1\",\"example::greet\":\">=1.0.0, <2.0.0\"}}",
)
assert_eq(m.name, "hello")
assert_eq(m.bins, ["bin/hello"])
assert_eq(m.depends.get("lib"), Some("^1"))
assert_eq(m.depends.get("example::greet"), Some(">=1.0.0, <2.0.0"))
assert_eq(parse_dep_key("example::greet"), (Some("example"), "greet"))
assert_eq(parse_dep_key("lib"), (None, "lib"))
assert_true(!valid_rel_path("../x"))
assert_true(!valid_rel_path("/bin/sh"))
assert_eq(store_id("sha256:0123456789abcdef0123"), "0123456789abcdef")
let bad_dep = try {
parse_manifest(
"{\"name\":\"hello\",\"version\":\"1.0.0\",\"depends\":{\"BadName\":\"^1\"}}",
)
|> ignore
false
} catch {
OrbitError(_) => true
}
assert_true(bad_dep)
let bad_con = try {
parse_manifest(
"{\"name\":\"hello\",\"version\":\"1.0.0\",\"depends\":{\"lib\":\">=abc\"}}",
)
|> ignore
false
} catch {
OrbitError(_) => true
}
assert_true(bad_con)
}
+13
View File
@@ -1,8 +1,21 @@
import {
"latha/orbit/kernel",
"moonbitlang/core/json",
"moonbitlang/core/encoding/base64",
"moonbitlang/core/encoding/hex",
"moonbitlang/core/encoding/percent",
"moonbit-community/toml",
"moonbitlang/async",
"moonbitlang/async/fs",
"moonbitlang/async/http",
"moonbitlang/async/process",
"moonbitlang/async/stdio",
}
import {
"moonbitlang/async/socket",
} for "wbtest"
pkgtype(kind: "executable")
options(
+858
View File
@@ -0,0 +1,858 @@
// OCI Distribution v2 HTTP transport, auth challenges, redirects, and streaming.
///|
const OCI_MANIFEST_MEDIA_TYPE : String = "application/vnd.oci.image.manifest.v1+json"
///|
const MANIFEST_ACCEPT : String = "application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json, application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json"
///|
struct ParsedUrl {
scheme : String
host : String
path : String
}
///|
enum AuthChallenge {
Bearer(String, String, String)
Basic(String)
Unknown
}
///|
let token_cache : Map[String, String] = Map([])
///|
fn hdr(name : String) -> @http.CaseInsensitiveString {
@http.CaseInsensitiveString(name)
}
///|
fn split_channel_url(url : String) -> (String, String) {
let clean = strip_url_scheme(trim(url))
let (host, ns) = split_first(clean, '/')
(host, trim_slashes(ns))
}
///|
fn trim_slashes(s : String) -> String {
let a = chars(s)
let mut start = 0
let mut end = a.length()
while start < end && a[start] == '/' {
start = start + 1
}
while end > start && a[end - 1] == '/' {
end = end - 1
}
slice(a, start, end)
}
///|
fn channel_scheme(ch : Channel) -> String {
if ch.plain_http {
"http"
} else {
"https"
}
}
///|
fn parse_url(raw : String) -> ParsedUrl raise OrbitError {
let u = trim(raw)
guard u.find("://") is Some(idx) else {
raise OrbitError("invalid URL '\{raw}'")
}
let scheme = ascii_lower(u[:idx].to_owned())
if scheme != "http" && scheme != "https" {
raise OrbitError("unsupported URL scheme '\{scheme}'")
}
let rest = u[idx + 3:].to_owned()
let a = chars(rest)
let mut split_at = a.length()
let mut needs_slash = true
for i = 0; i < a.length(); i = i + 1 {
if a[i] == '/' {
split_at = i
needs_slash = false
break
}
if a[i] == '?' {
split_at = i
needs_slash = true
break
}
}
let host = slice(a, 0, split_at)
if host == "" {
raise OrbitError("URL missing host: '\{raw}'")
}
let path = if split_at == a.length() {
"/"
} else if needs_slash {
"/" + slice(a, split_at, a.length())
} else {
slice(a, split_at, a.length())
}
ParsedUrl::{ scheme, host, path }
}
///|
fn same_origin(a : ParsedUrl, b : ParsedUrl) -> Bool {
ascii_lower(a.scheme) == ascii_lower(b.scheme) &&
ascii_lower(a.host) == ascii_lower(b.host)
}
///|
fn resolve_location(
base : ParsedUrl,
location : String,
) -> ParsedUrl raise OrbitError {
let loc = trim(location)
if loc == "" {
raise OrbitError("empty redirect Location")
}
let lower = ascii_lower(loc)
if has_prefix(lower, "http://") || has_prefix(lower, "https://") {
return parse_url(loc)
}
if has_prefix(loc, "//") {
return parse_url(base.scheme + ":" + loc)
}
if has_prefix(loc, "/") {
return ParsedUrl::{ scheme: base.scheme, host: base.host, path: loc }
}
let (path_only, _) = split_first(base.path, '?')
let a = chars(path_only)
let mut last_slash = -1
for i = 0; i < a.length(); i = i + 1 {
if a[i] == '/' {
last_slash = i
}
}
let dir = if last_slash >= 0 { slice(a, 0, last_slash + 1) } else { "/" }
ParsedUrl::{ scheme: base.scheme, host: base.host, path: dir + loc }
}
///|
fn parse_auth_params(rest : String) -> Map[String, String] {
let out : Map[String, String] = Map([])
let a = chars(rest)
let n = a.length()
let mut i = 0
while i < n {
while i < n && (is_space(a[i]) || a[i] == ',') {
i = i + 1
}
if i >= n {
break
}
let key_start = i
while i < n && a[i] != '=' && a[i] != ',' && !is_space(a[i]) {
i = i + 1
}
let key = ascii_lower(slice(a, key_start, i))
while i < n && is_space(a[i]) {
i = i + 1
}
if i >= n || a[i] != '=' {
while i < n && a[i] != ',' {
i = i + 1
}
continue
}
i = i + 1
while i < n && is_space(a[i]) {
i = i + 1
}
let val = StringBuilder()
if i < n && a[i] == '"' {
i = i + 1
while i < n && a[i] != '"' {
if a[i] == '\\' && i + 1 < n {
val.write_char(a[i + 1])
i = i + 2
} else {
val.write_char(a[i])
i = i + 1
}
}
if i < n && a[i] == '"' {
i = i + 1
}
} else {
while i < n && a[i] != ',' {
val.write_char(a[i])
i = i + 1
}
}
if key != "" {
out[key] = val.to_string()
}
}
out
}
///|
fn parse_www_authenticate(value : String) -> AuthChallenge {
let s = trim(value)
if s == "" {
return Unknown
}
let a = chars(s)
let mut i = 0
while i < a.length() && !is_space(a[i]) {
i = i + 1
}
let scheme = ascii_lower(slice(a, 0, i))
let rest = trim(slice(a, i, a.length()))
if scheme == "bearer" {
let params = parse_auth_params(rest)
let realm = params.get("realm").unwrap_or("")
if realm == "" {
return Unknown
}
let service = params.get("service").unwrap_or("")
let scope = params.get("scope").unwrap_or("")
Bearer(realm, service, scope)
} else if scheme == "basic" {
let params = parse_auth_params(rest)
Basic(params.get("realm").unwrap_or(""))
} else {
Unknown
}
}
///|
fn unquote(s : String) -> String {
let t = trim(s)
let a = chars(t)
if a.length() >= 2 && a[0] == '"' && a[a.length() - 1] == '"' {
slice(a, 1, a.length() - 1)
} else {
t
}
}
///|
fn is_next_rel_param(params : String) -> Bool {
for part in split_on(params, ';') {
let p = trim(part)
if p == "" {
continue
}
let (k, v) = split_first(p, '=')
if ascii_lower(trim(k)) == "rel" {
let rels = unquote(v)
for tok in split_on(rels, ' ') {
if ascii_lower(trim(tok)) == "next" {
return true
}
}
}
}
false
}
///|
fn parse_next_link(value : String) -> String? {
let a = chars(value)
let n = a.length()
let mut i = 0
while i < n {
while i < n && a[i] != '<' {
i = i + 1
}
if i >= n {
break
}
i = i + 1
let url_start = i
while i < n && a[i] != '>' {
i = i + 1
}
if i >= n {
break
}
let target = trim(slice(a, url_start, i))
i = i + 1
let param_start = i
let mut in_quotes = false
while i < n {
if a[i] == '"' {
in_quotes = !in_quotes
} else if a[i] == ',' && !in_quotes {
break
}
i = i + 1
}
let params = slice(a, param_start, i)
if target != "" && is_next_rel_param(params) {
return Some(target)
}
if i < n && a[i] == ',' {
i = i + 1
}
}
None
}
///|
fn extract_digest_header(headers : @http.Headers) -> String? {
match headers.get(hdr("Docker-Content-Digest")) {
Some(v) => {
let t = trim(v)
if t != "" {
return Some(t)
}
}
None => ()
}
match headers.get(hdr("ETag")) {
Some(v) => {
let mut t = trim(v)
if has_prefix(t, "W/") || has_prefix(t, "w/") {
t = trim(drop_chars(t, 2))
}
let d = unquote(t)
if has_prefix(d, "sha256:") || has_prefix(d, "sha512:") {
return Some(d)
}
}
None => ()
}
None
}
///|
fn format_oci_error(code : Int32, reason : String, body : Bytes) -> String {
let text = utf8_decode(body)
let obj : Map[String, Json]? = Some(parse_object(text, "oci error")) catch {
_ => None
}
match obj {
Some(o) =>
match o.get("errors") {
Some(Json::Array(errs)) =>
if errs.length() > 0 {
match errs[0] {
Json::Object(e) => {
let c = jstr(e, "code", "")
let m = jstr(e, "message", "")
if c != "" && m != "" {
return "HTTP \{code}: \{c}: \{m}"
} else if m != "" {
return "HTTP \{code}: \{m}"
} else if c != "" {
return "HTTP \{code}: \{c}"
}
}
_ => ()
}
}
_ => ()
}
None => ()
}
let base = if reason != "" { "HTTP \{code} \{reason}" } else { "HTTP \{code}" }
let snippet = trim(text)
if snippet != "" && chars(snippet).length() < 200 {
base + ": " + snippet
} else {
base
}
}
///|
fn token_cache_key(host : String, scope_key : String) -> String {
ascii_lower(host) + "|" + scope_key
}
///|
fn is_redirect_code(code : Int32) -> Bool {
code == 301 || code == 302 || code == 303 || code == 307 || code == 308
}
///|
fn build_http_headers(
headers : Map[String, String],
auth_header : String?,
content_length : Int64?,
) -> @http.Headers {
let out : @http.Headers = Map([])
for k, v in headers {
out[hdr(k)] = v
}
match auth_header {
Some(a) => out[hdr("Authorization")] = a
None => ()
}
match content_length {
Some(n) => out[hdr("Content-Length")] = n.to_string()
None => ()
}
out
}
///|
async fn connect_http(url : ParsedUrl) -> @http.Client raise OrbitError {
let base_headers : @http.Headers = Map([])
base_headers[hdr("User-Agent")] = "orbit/0.1"
base_headers[hdr("Accept-Encoding")] = "identity"
@http.Client::Client(url.scheme + "://" + url.host, headers=base_headers) catch {
e => raise OrbitError("cannot connect to \{url.host}: \{e}")
}
}
///|
async fn raw_http_bytes(
meth : @http.RequestMethod,
url_str : String,
headers : Map[String, String],
auth_header : String?,
body : Bytes,
) -> (ParsedUrl, @http.Response, Bytes) raise OrbitError {
let mut cur_url = parse_url(url_str)
let mut cur_meth = meth
let mut cur_body = body
let mut cur_auth = auth_header
for hop = 0; hop < 10; hop = hop + 1 {
let clen : Int64? = if cur_body.length() > 0 ||
cur_meth is Post ||
cur_meth is Put {
Some(cur_body.length().to_int64())
} else {
None
}
let extra = build_http_headers(headers, cur_auth, clen)
let client = connect_http(cur_url)
defer client.close()
let resp = try {
client.request(cur_meth, cur_url.path, extra_headers=extra)
if cur_body.length() > 0 {
client.write(cur_body)
}
client.end_request()
} catch {
e => raise OrbitError("HTTP request to \{cur_url.host} failed: \{e}")
}
if is_redirect_code(resp.code) {
match resp.headers.get(hdr("Location")) {
Some(loc) => {
let next_url = resolve_location(cur_url, loc)
if !same_origin(cur_url, next_url) {
cur_auth = None
}
if (resp.code == 301 || resp.code == 302 || resp.code == 303) &&
cur_meth is Post {
cur_meth = Get
cur_body = b""
}
cur_url = next_url
continue
}
None => ()
}
}
let resp_body = if cur_meth is Head {
b""
} else {
client.read_all().binary() catch {
e => raise OrbitError("failed reading response from \{cur_url.host}: \{e}")
}
}
return (cur_url, resp, resp_body)
}
raise OrbitError("too many redirects for \{url_str}")
}
///|
async fn fetch_bearer_token(
realm : String,
service : String,
scope : String,
creds : Creds?,
) -> String raise OrbitError {
let mut token_url = realm
let mut sep = if has_char(realm, '?') { "&" } else { "?" }
if service != "" {
token_url = token_url + sep + "service=" + @percent.encode(service)
sep = "&"
}
if scope != "" {
token_url = token_url + sep + "scope=" + @percent.encode(scope)
}
let auth_header = creds.map(fn(c) { "Basic " + encode_basic_auth(c) })
let (_, resp, body) = raw_http_bytes(
Get,
token_url,
Map([("Accept", "application/json")]),
auth_header,
b"",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"authentication failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
let obj = parse_object(utf8_decode(body), "token response")
let tok = jstr(obj, "token", "")
if tok != "" {
return tok
}
let access = jstr(obj, "access_token", "")
if access != "" {
return access
}
raise OrbitError("token response missing token")
}
///|
async fn resolve_auth_retry(
host : String,
scope_key : String,
used_cached : Bool,
www_auth : String,
creds_override : Creds?,
) -> String? raise OrbitError {
if used_cached && scope_key != "" {
token_cache.remove(token_cache_key(host, scope_key))
}
let creds = match creds_override {
Some(c) => Some(c)
None => load_creds(host)
}
match parse_www_authenticate(www_auth) {
Bearer(realm, service, scope) => {
let tok = fetch_bearer_token(realm, service, scope, creds)
if creds_override is None && scope_key != "" {
token_cache[token_cache_key(host, scope_key)] = tok
}
Some("Bearer " + tok)
}
Basic(_) =>
match creds {
Some(c) => Some("Basic " + encode_basic_auth(c))
None => None
}
Unknown => None
}
}
///|
async fn oci_request(
meth : @http.RequestMethod,
url_str : String,
headers : Map[String, String],
body : Bytes,
scope_key : String,
creds_override? : Creds,
) -> (@http.Response, Bytes) raise OrbitError {
let initial_url = parse_url(url_str)
let (initial_auth, used_cached) = if creds_override is None && scope_key != "" {
match token_cache.get(token_cache_key(initial_url.host, scope_key)) {
Some(t) => (Some("Bearer " + t), true)
None => (None, false)
}
} else {
(None, false)
}
let (final_url, resp, resp_body) = raw_http_bytes(
meth, url_str, headers, initial_auth, body,
)
if resp.code != 401 {
return (resp, resp_body)
}
let www_auth = match resp.headers.get(hdr("WWW-Authenticate")) {
Some(v) => v
None => return (resp, resp_body)
}
let retry_auth = match
resolve_auth_retry(
final_url.host,
scope_key,
used_cached,
www_auth,
creds_override,
) {
Some(a) => a
None => return (resp, resp_body)
}
let (_, retry_resp, retry_body) = raw_http_bytes(
meth,
url_str,
headers,
Some(retry_auth),
body,
)
(retry_resp, retry_body)
}
///|
async fn try_download_once(
url_str : String,
dest_path : String,
expected_digest : String,
auth_header : String?,
) -> (ParsedUrl, @http.Response, Bytes) raise OrbitError {
let mut cur_url = parse_url(url_str)
let mut cur_auth = auth_header
for hop = 0; hop < 10; hop = hop + 1 {
let extra = build_http_headers(Map([]), cur_auth, None)
let client = connect_http(cur_url)
defer client.close()
let resp = try {
client.request(Get, cur_url.path, extra_headers=extra)
client.end_request()
} catch {
e => raise OrbitError("download from \{cur_url.host} failed: \{e}")
}
if is_redirect_code(resp.code) {
match resp.headers.get(hdr("Location")) {
Some(loc) => {
let next_url = resolve_location(cur_url, loc)
if !same_origin(cur_url, next_url) {
cur_auth = None
}
cur_url = next_url
continue
}
None => ()
}
}
if resp.code < 200 || resp.code >= 300 {
let err_body = client.read_all().binary() catch { _ => b"" }
return (cur_url, resp, err_body)
}
let out = @fs.open(
dest_path,
mode=WriteOnly,
create_mode=CreateOrTruncate,
) catch {
e => raise OrbitError("cannot write \{dest_path}: \{e}")
}
defer out.close()
let hasher = Sha256::new()
let buf = FixedArray::make(32768, b'\x00')
for ;; {
let n = client.read(buf) catch {
e => raise OrbitError("download interrupted from \{cur_url.host}: \{e}")
}
if n == 0 {
break
}
hasher.update_fixed(buf, n)
out.write(buf.unsafe_reinterpret_as_bytes()[:n]) catch {
e => raise OrbitError("cannot write \{dest_path}: \{e}")
}
}
if has_prefix(expected_digest, "sha256:") {
let actual = "sha256:" + hasher.finish_hex()
if actual != expected_digest {
raise OrbitError(
"digest mismatch for \{dest_path}: expected \{expected_digest}, got \{actual}",
)
}
}
return (cur_url, resp, b"")
}
raise OrbitError("too many redirects downloading \{url_str}")
}
///|
async fn oci_download_to_file(
url_str : String,
dest_path : String,
expected_digest : String,
scope_key : String,
) -> Unit raise OrbitError {
let initial_url = parse_url(url_str)
let (initial_auth, used_cached) = if scope_key != "" {
match token_cache.get(token_cache_key(initial_url.host, scope_key)) {
Some(t) => (Some("Bearer " + t), true)
None => (None, false)
}
} else {
(None, false)
}
let (final_url, resp, err_body) = try_download_once(
url_str, dest_path, expected_digest, initial_auth,
)
if resp.code >= 200 && resp.code < 300 {
return
}
if resp.code == 401 {
match resp.headers.get(hdr("WWW-Authenticate")) {
Some(www_auth) =>
match
resolve_auth_retry(final_url.host, scope_key, used_cached, www_auth, None) {
Some(retry_auth) => {
let (_, retry_resp, retry_err) = try_download_once(
url_str,
dest_path,
expected_digest,
Some(retry_auth),
)
if retry_resp.code >= 200 && retry_resp.code < 300 {
return
}
raise OrbitError(
"download failed (\{format_oci_error(retry_resp.code, retry_resp.reason, retry_err)})",
)
}
None => ()
}
None => ()
}
}
raise OrbitError(
"download failed (\{format_oci_error(resp.code, resp.reason, err_body)})",
)
}
///|
async fn try_upload_file_once(
url_str : String,
file_path : String,
size : Int64,
content_type : String,
auth_header : String?,
) -> (ParsedUrl, @http.Response, Bytes) raise OrbitError {
let mut cur_url = parse_url(url_str)
let mut cur_auth = auth_header
for hop = 0; hop < 10; hop = hop + 1 {
let extra = build_http_headers(
Map([("Content-Type", content_type)]),
cur_auth,
Some(size),
)
let client = connect_http(cur_url)
defer client.close()
let file = @fs.open(file_path, mode=ReadOnly) catch {
e => raise OrbitError("cannot open \{file_path}: \{e}")
}
defer file.close()
let resp = try {
client.request(Put, cur_url.path, extra_headers=extra)
client.write_reader(file)
client.end_request()
} catch {
e => raise OrbitError("upload to \{cur_url.host} failed: \{e}")
}
if is_redirect_code(resp.code) {
match resp.headers.get(hdr("Location")) {
Some(loc) => {
let next_url = resolve_location(cur_url, loc)
if !same_origin(cur_url, next_url) {
cur_auth = None
}
cur_url = next_url
continue
}
None => ()
}
}
let resp_body = client.read_all().binary() catch {
e => raise OrbitError("failed reading upload response: \{e}")
}
return (cur_url, resp, resp_body)
}
raise OrbitError("too many redirects uploading to \{url_str}")
}
///|
async fn oci_upload_file(
url_str : String,
file_path : String,
size : Int64,
content_type : String,
scope_key : String,
) -> (@http.Response, Bytes) raise OrbitError {
let initial_url = parse_url(url_str)
let (initial_auth, used_cached) = if scope_key != "" {
match token_cache.get(token_cache_key(initial_url.host, scope_key)) {
Some(t) => (Some("Bearer " + t), true)
None => (None, false)
}
} else {
(None, false)
}
let (final_url, resp, resp_body) = try_upload_file_once(
url_str, file_path, size, content_type, initial_auth,
)
if resp.code != 401 {
return (resp, resp_body)
}
let www_auth = match resp.headers.get(hdr("WWW-Authenticate")) {
Some(v) => v
None => return (resp, resp_body)
}
let retry_auth = match
resolve_auth_retry(final_url.host, scope_key, used_cached, www_auth, None) {
Some(a) => a
None => return (resp, resp_body)
}
let (_, retry_resp, retry_body) = try_upload_file_once(
url_str,
file_path,
size,
content_type,
Some(retry_auth),
)
(retry_resp, retry_body)
}
///|
test "parse_url and resolve_location" {
let base = parse_url("https://git.site.latha.org/v2/nandi/hello/tags/list")
assert_eq(base.scheme, "https")
assert_eq(base.host, "git.site.latha.org")
assert_eq(base.path, "/v2/nandi/hello/tags/list")
let root_rel = resolve_location(base, "/v2/nandi/hello/blobs/uploads/123")
assert_eq(root_rel.host, "git.site.latha.org")
assert_eq(root_rel.path, "/v2/nandi/hello/blobs/uploads/123")
let abs = resolve_location(base, "https://cdn.example.com/blob?sig=1")
assert_eq(abs.host, "cdn.example.com")
assert_eq(abs.path, "/blob?sig=1")
assert_false(same_origin(base, abs))
assert_true(same_origin(base, root_rel))
let rel = resolve_location(base, "next?n=10")
assert_eq(rel.path, "/v2/nandi/hello/tags/next?n=10")
}
///|
test "parse_www_authenticate handles Bearer with commas in scope and Basic" {
match
parse_www_authenticate(
"Bearer realm=\"https://git.site.latha.org/v2/token\",service=\"container_registry\",scope=\"repository:nandi/hello:pull,push\"",
) {
Bearer(realm, service, scope) => {
assert_eq(realm, "https://git.site.latha.org/v2/token")
assert_eq(service, "container_registry")
assert_eq(scope, "repository:nandi/hello:pull,push")
}
_ => fail("expected Bearer challenge")
}
match parse_www_authenticate("Basic realm=\"Registry\"") {
Basic(realm) => assert_eq(realm, "Registry")
_ => fail("expected Basic challenge")
}
}
///|
test "parse_next_link and split_channel_url" {
assert_eq(
parse_next_link("</v2/nandi/hello/tags/list?last=latest>; rel=\"next\""),
Some("/v2/nandi/hello/tags/list?last=latest"),
)
assert_eq(
parse_next_link(
"</v2/_catalog?last=a>; rel=\"prev\", </v2/_catalog?last=b>; rel=\"next\"",
),
Some("/v2/_catalog?last=b"),
)
assert_eq(parse_next_link("</v2/_catalog?last=a>; rel=\"prev\""), None)
assert_eq(split_channel_url("git.site.latha.org/nandi/"), ("git.site.latha.org", "nandi"))
assert_eq(split_channel_url("localhost:5000"), ("localhost:5000", ""))
}
+580 -243
View File
File diff suppressed because it is too large. Load diff
+1653
View File
File diff suppressed because it is too large. Load diff
+608 -82
View File
@@ -1,10 +1,4 @@
// Everything that talks to the registry goes through the `oras` CLI.
// Authentication is whatever `oras login` has stored.
///|
fn oras(ch : Channel, args : String) -> String {
"oras " + args + (if ch.plain_http { " --plain-http" } else { "" })
}
// Native OCI Distribution v2 registry client operations.
///|
fn repo_of(ch : Channel, name : String) -> String {
@@ -12,76 +6,434 @@ fn repo_of(ch : Channel, name : String) -> String {
}
///|
/// Whether oras output says the repository doesn't exist, as opposed to the
/// registry being unreachable or refusing access.
fn is_missing_repo(err : String) -> Bool {
contains_str(err, "name unknown") ||
contains_str(err, "response status code 404")
fn channel_base_url(ch : Channel) -> String {
let (host, _) = split_channel_url(ch.url)
channel_scheme(ch) + "://" + host
}
///|
fn channel_repo_path(ch : Channel, name : String) -> String {
let (_, ns) = split_channel_url(ch.url)
if ns == "" {
name
} else {
ns + "/" + name
}
}
///|
/// Whether an HTTP status says the repository doesn't exist, as opposed to
/// the registry being unreachable or refusing access.
fn is_missing_status(code : Int32) -> Bool {
code == 404
}
///|
async fn verify_login(
host : String,
plain_http : Bool,
creds : Creds,
) -> Unit raise OrbitError {
let scheme = if plain_http { "http" } else { "https" }
let url = scheme + "://" + host + "/v2/"
let (resp, body) = oci_request(
Get,
url,
Map([("Accept", "application/json")]),
b"",
"",
creds_override=creds,
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"login to \{host} failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
}
///|
async fn list_repos(ch : Channel) -> Array[String] raise OrbitError {
with_spinner("Listing packages in \{ch.name}", () => {
let base = channel_base_url(ch)
let (_, ns) = split_channel_url(ch.url)
let ns_prefix = if ns == "" { "" } else { ns + "/" }
let out : Array[String] = []
let seen : Array[String] = []
let mut next_url : String? = Some(base + "/v2/_catalog")
while next_url is Some(url) {
if seen.contains(url) {
break
}
seen.push(url)
let (resp, body) = oci_request(
Get,
url,
Map([("Accept", "application/json")]),
b"",
"catalog",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"channel '\{ch.name}' (\{ch.url}): \{format_oci_error(resp.code, resp.reason, body)}",
)
}
let obj = parse_object(utf8_decode(body), "catalog")
let page = jstrs(obj, "repositories")
if page.length() == 0 {
break
}
for r in page {
if ns_prefix == "" {
out.push(r)
} else if has_prefix(r, ns_prefix) {
out.push(drop_chars(r, chars(ns_prefix).length()))
}
}
next_url = match resp.headers.get(hdr("Link")) {
Some(link) =>
match parse_next_link(link) {
Some(target) => {
let resolved = resolve_location(parse_url(url), target)
let full = resolved.scheme + "://" + resolved.host + resolved.path
if seen.contains(full) {
None
} else {
Some(full)
}
}
None => None
}
None => None
}
}
out
})
}
///|
/// The tags of `name` in a channel, or None if the channel doesn't have it.
/// Any other failure is an error: falling through to a lower priority channel
/// could install a different package with the same name.
fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError {
let errfile = trim(capture("mktemp"))
let cmd = oras(ch, "repo tags " + sq(repo_of(ch, name))) + " 2>" + sq(errfile)
let out = Some(capture(cmd)) catch { _ => None }
let err = match read_text(errfile) {
Some(t) => trim(t)
None => ""
}
sh("rm -f " + sq(errfile)) |> ignore
match out {
Some(o) => Some(lines(o))
None =>
if is_missing_repo(err) {
None
} else {
raise OrbitError("channel '\{ch.name}' (\{ch.url}): \{err}")
async fn list_tags_inner(
ch : Channel,
name : String,
) -> Array[String]? raise OrbitError {
let base = channel_base_url(ch)
let repo = channel_repo_path(ch, name)
let scope_key = repo + ":pull"
let out : Array[String] = []
let seen : Array[String] = []
let mut next_url : String? = Some(base + "/v2/" + repo + "/tags/list")
let mut first = true
while next_url is Some(url) {
if seen.contains(url) {
break
}
seen.push(url)
let (resp, body) = oci_request(
Get,
url,
Map([("Accept", "application/json")]),
b"",
scope_key,
)
if first && is_missing_status(resp.code) {
return None
}
first = false
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"channel '\{ch.name}' (\{ch.url}): \{format_oci_error(resp.code, resp.reason, body)}",
)
}
let obj = parse_object(utf8_decode(body), "tags/list")
let page = jstrs(obj, "tags")
if page.length() == 0 {
break
}
for t in page {
if !out.contains(t) {
out.push(t)
}
}
next_url = match resp.headers.get(hdr("Link")) {
Some(link) =>
match parse_next_link(link) {
Some(target) => {
let resolved = resolve_location(parse_url(url), target)
let full = resolved.scheme + "://" + resolved.host + resolved.path
if seen.contains(full) {
None
} else {
Some(full)
}
}
None => None
}
None => None
}
}
Some(out)
}
///|
fn resolve_digest(
async fn list_tags(ch : Channel, name : String) -> Array[String]? raise OrbitError {
with_spinner("Checking versions of \{ch.name}::\{name}", () => {
list_tags_inner(ch, name)
})
}
///|
async fn list_tags_quiet(
ch : Channel,
name : String,
) -> Array[String]? raise OrbitError {
list_tags_inner(ch, name)
}
///|
async fn resolve_digest(
ch : Channel,
name : String,
tag : String,
) -> String raise OrbitError {
let d = trim(
capture(oras(ch, "resolve " + sq(repo_of(ch, name) + ":" + tag))),
with_spinner("Resolving \{ch.name}::\{name}@\{tag}", () => {
let repo = channel_repo_path(ch, name)
let url = channel_base_url(ch) + "/v2/" + repo + "/manifests/" + tag
let scope_key = repo + ":pull"
let req_headers = Map([("Accept", MANIFEST_ACCEPT)])
let (head_resp, head_body) = oci_request(
Head,
url,
req_headers,
b"",
scope_key,
)
let mut digest = if head_resp.code >= 200 && head_resp.code < 300 {
extract_digest_header(head_resp.headers).unwrap_or("")
} else {
""
}
if head_resp.code == 405 ||
(head_resp.code >= 200 && head_resp.code < 300 && digest == "") {
let (get_resp, get_body) = oci_request(
Get,
url,
req_headers,
b"",
scope_key,
)
if get_resp.code < 200 || get_resp.code >= 300 {
raise OrbitError(
"cannot resolve \{ch.name}::\{name}@\{tag}: \{format_oci_error(get_resp.code, get_resp.reason, get_body)}",
)
}
digest = match extract_digest_header(get_resp.headers) {
Some(d) => d
None => sha256_digest(get_body)
}
} else if head_resp.code < 200 || head_resp.code >= 300 {
raise OrbitError(
"cannot resolve \{ch.name}::\{name}@\{tag}: \{format_oci_error(head_resp.code, head_resp.reason, head_body)}",
)
}
if !(has_prefix(digest, "sha256:") || has_prefix(digest, "sha512:")) {
raise OrbitError("unexpected digest for \{name}:\{tag}: '\{digest}'")
}
digest
})
}
///|
async fn fetch_raw_manifest_bytes(
ch : Channel,
name : String,
ref_str : String,
) -> Bytes raise OrbitError {
let repo = channel_repo_path(ch, name)
let url = channel_base_url(ch) + "/v2/" + repo + "/manifests/" + ref_str
let (resp, body) = oci_request(
Get,
url,
Map([("Accept", MANIFEST_ACCEPT)]),
b"",
repo + ":pull",
)
if !(has_prefix(d, "sha256:") || has_prefix(d, "sha512:")) {
raise OrbitError("unexpected digest for \{name}:\{tag}: '\{d}'")
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"cannot fetch manifest \{ch.name}::\{name}@\{ref_str}: \{format_oci_error(resp.code, resp.reason, body)}",
)
}
d
if has_prefix(ref_str, "sha256:") {
let actual = sha256_digest(body)
if actual != ref_str {
raise OrbitError(
"manifest digest mismatch for \{name}@\{ref_str}: got \{actual}",
)
}
}
body
}
///|
async fn fetch_raw_manifest(
ch : Channel,
name : String,
ref_str : String,
) -> String raise OrbitError {
utf8_decode(fetch_raw_manifest_bytes(ch, name, ref_str))
}
///|
fn manifest_cache_path(root : String, digest : String) -> String? {
if root == "" || !has_prefix(digest, "sha256:") {
return None
}
let hex = drop_chars(digest, 7)
if hex == "" {
return None
}
for c in hex {
let ok = (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F')
if !ok {
return None
}
}
Some(cache_dir(root) + "/" + ascii_lower(hex) + ".json")
}
///|
/// Fetch only the config blob (orbit.json); no layer download needed to plan.
fn fetch_manifest(
async fn fetch_manifest_with_raw(
ch : Channel,
name : String,
digest : String,
) -> (Manifest, String) raise OrbitError {
with_spinner("Reading metadata for \{ch.name}::\{name}", () => {
let repo = channel_repo_path(ch, name)
let manifest_text = fetch_raw_manifest(ch, name, digest)
let manifest_obj = parse_object(manifest_text, "manifest")
let cfg_digest = match manifest_obj.get("config") {
Some(Json::Object(c)) => jstr(c, "digest", "")
_ => ""
}
if cfg_digest == "" {
raise OrbitError("\{name}@\{digest} manifest missing config.digest")
}
let blob_url = channel_base_url(ch) + "/v2/" + repo + "/blobs/" + cfg_digest
let (resp, body) = oci_request(
Get,
blob_url,
Map([("Accept", CONFIG_MEDIA_TYPE + ", application/json")]),
b"",
repo + ":pull",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"cannot fetch config for \{name}@\{digest}: \{format_oci_error(resp.code, resp.reason, body)}",
)
}
if has_prefix(cfg_digest, "sha256:") {
let actual = sha256_digest(body)
if actual != cfg_digest {
raise OrbitError(
"config digest mismatch for \{name}@\{digest}: expected \{cfg_digest}, got \{actual}",
)
}
}
let raw = utf8_decode(body)
let m = parse_manifest(raw)
if m.name != name {
raise OrbitError(
"\{name}@\{digest} declares name '\{m.name}'; refusing to install",
)
}
(m, raw)
})
}
///|
/// Fetch config blob (orbit.json) using a digest-keyed local cache under
/// `<root>/cache/manifests/<hex>.json`. Pass `root = ""` to skip caching.
async fn fetch_manifest_cached(
root : String,
ch : Channel,
name : String,
digest : String,
) -> Manifest raise OrbitError {
let text = capture(
oras(ch, "manifest fetch-config " + sq(repo_of(ch, name) + "@" + digest)),
)
let m = parse_manifest(text)
if m.name != name {
raise OrbitError(
"\{name}@\{digest} declares name '\{m.name}'; refusing to install",
)
match manifest_cache_path(root, digest) {
Some(path) =>
match read_text(path) {
Some(raw) => {
let cached : Manifest? = Some(parse_manifest(raw)) catch { _ => None }
match cached {
Some(m) => if m.name == name { return m }
None => ()
}
}
None => ()
}
None => ()
}
let (m, raw) = fetch_manifest_with_raw(ch, name, digest)
match manifest_cache_path(root, digest) {
Some(path) => {
try {
@fs.mkdir(cache_dir(root), recursive=true, allow_exist=true)
write_text_atomic(path, raw)
} catch {
_ => ()
}
}
None => ()
}
m
}
///|
fn find_pkg_layer_digest(manifest_obj : Map[String, Json]) -> String? {
let layers = match manifest_obj.get("layers") {
Some(Json::Array(xs)) => xs
_ => return None
}
for item in layers {
match item {
Json::Object(l) =>
if jstr(l, "mediaType", "") == LAYER_MEDIA_TYPE {
let d = jstr(l, "digest", "")
if d != "" {
return Some(d)
}
}
_ => ()
}
}
for item in layers {
match item {
Json::Object(l) =>
match l.get("annotations") {
Some(Json::Object(ann)) =>
if jstr(ann, "org.opencontainers.image.title", "") == "pkg.tar.gz" {
let d = jstr(l, "digest", "")
if d != "" {
return Some(d)
}
}
_ => ()
}
_ => ()
}
}
None
}
///|
/// Pull a package layer by digest and unpack it into the store.
/// Unpacks into a temp dir first, then renames, so a store dir is either
/// complete or absent.
fn fetch_into_store(
async fn fetch_into_store(
ctx : Ctx,
ch : Channel,
name : String,
@@ -91,14 +443,39 @@ fn fetch_into_store(
if exists(dir) {
return dir
}
let manifest_text = fetch_raw_manifest(ch, name, digest)
let manifest_obj = parse_object(manifest_text, "manifest")
let layer_digest = match find_pkg_layer_digest(manifest_obj) {
Some(d) => d
None => raise OrbitError("\{name}@\{digest} has no pkg.tar.gz layer")
}
let repo = channel_repo_path(ch, name)
let blob_url = channel_base_url(ch) + "/v2/" + repo + "/blobs/" + layer_digest
let tmp = ctx.root + "/tmp/" + name + "-" + store_id(digest)
sh_ok("rm -rf " + sq(tmp) + " && mkdir -p " + sq(tmp + "/root"))
sh_ok(
oras(ch, "pull -o " + sq(tmp) + " " + sq(repo_of(ch, name) + "@" + digest)) +
" >/dev/null",
)
if !exists(tmp + "/pkg.tar.gz") {
raise OrbitError("\{name}@\{digest} has no pkg.tar.gz layer")
let dl_res : Result[Unit, Error] = try {
with_spinner("Downloading \{ch.name}::\{name}", () => {
oci_download_to_file(
blob_url,
tmp + "/pkg.tar.gz",
layer_digest,
repo + ":pull",
)
})
Ok(())
} catch {
e => Err(e)
}
match dl_res {
Ok(_) => ()
Err(OrbitError(msg)) => {
sh("rm -rf " + sq(tmp)) |> ignore
raise OrbitError(msg)
}
Err(e) => {
sh("rm -rf " + sq(tmp)) |> ignore
raise OrbitError(e.to_string())
}
}
sh_ok(
"tar -xzf " +
@@ -174,9 +551,167 @@ test "package config exposes Gitea labels and preserves Orbit metadata" {
)
}
///|
fn json_int64(n : Int64) -> Json {
Json::number(n.to_double(), repr=n.to_string())
}
///|
fn append_digest_param(upload_url : String, digest : String) -> String {
let sep = if has_char(upload_url, '?') { "&" } else { "?" }
upload_url + sep + "digest=" + @percent.encode(digest)
}
///|
async fn blob_exists(
base : String,
repo : String,
digest : String,
) -> Bool raise OrbitError {
let url = base + "/v2/" + repo + "/blobs/" + digest
let (resp, body) = oci_request(Head, url, Map([]), b"", repo + ":pull")
if resp.code >= 200 && resp.code < 300 {
return true
}
if resp.code == 404 {
return false
}
raise OrbitError(
"blob check failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
///|
async fn start_blob_upload(base : String, repo : String) -> String raise OrbitError {
let init_url = base + "/v2/" + repo + "/blobs/uploads/"
let (resp, body) = oci_request(Post, init_url, Map([]), b"", repo + ":push")
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"failed to initiate blob upload (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
let loc = match resp.headers.get(hdr("Location")) {
Some(l) => l
None => raise OrbitError("blob upload response missing Location header")
}
let resolved = resolve_location(parse_url(init_url), loc)
resolved.scheme + "://" + resolved.host + resolved.path
}
///|
async fn upload_blob_bytes(
base : String,
repo : String,
digest : String,
data : Bytes,
) -> Unit raise OrbitError {
if blob_exists(base, repo, digest) {
return
}
let upload_url = append_digest_param(start_blob_upload(base, repo), digest)
let (resp, body) = oci_request(
Put,
upload_url,
Map([("Content-Type", "application/octet-stream")]),
data,
repo + ":push",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"blob upload failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
}
///|
async fn upload_blob_file(
base : String,
repo : String,
digest : String,
path : String,
size : Int64,
) -> Unit raise OrbitError {
if blob_exists(base, repo, digest) {
return
}
let upload_url = append_digest_param(start_blob_upload(base, repo), digest)
let (resp, body) = oci_upload_file(
upload_url,
path,
size,
"application/octet-stream",
repo + ":push",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"layer upload failed (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
}
///|
fn build_oci_manifest_bytes(
m : Manifest,
config_digest : String,
config_size : Int64,
layer_digest : String,
layer_size : Int64,
) -> Bytes {
let cfg : Map[String, Json] = Map([])
cfg["mediaType"] = Json::string(CONFIG_MEDIA_TYPE)
cfg["digest"] = Json::string(config_digest)
cfg["size"] = json_int64(config_size)
let layer_ann : Map[String, Json] = Map([])
layer_ann["org.opencontainers.image.title"] = Json::string("pkg.tar.gz")
let layer : Map[String, Json] = Map([])
layer["mediaType"] = Json::string(LAYER_MEDIA_TYPE)
layer["digest"] = Json::string(layer_digest)
layer["size"] = json_int64(layer_size)
layer["annotations"] = Json::object(layer_ann)
let ann : Map[String, Json] = Map([])
ann["org.opencontainers.image.created"] = Json::string(utc_now())
ann["org.opencontainers.image.version"] = Json::string(m.version)
if m.description != "" {
ann["org.opencontainers.image.description"] = Json::string(m.description)
}
let manifest : Map[String, Json] = Map([])
manifest["schemaVersion"] = json_int64(2L)
manifest["mediaType"] = Json::string(OCI_MANIFEST_MEDIA_TYPE)
manifest["artifactType"] = Json::string(ORBIT_ARTIFACT_TYPE)
manifest["config"] = Json::object(cfg)
manifest["layers"] = Json::array([Json::object(layer)])
manifest["annotations"] = Json::object(ann)
utf8_encode(Json::object(manifest).stringify() + "\n")
}
///|
async fn put_manifest(
base : String,
repo : String,
tag : String,
manifest_bytes : Bytes,
) -> Unit raise OrbitError {
let url = base + "/v2/" + repo + "/manifests/" + tag
let (resp, body) = oci_request(
Put,
url,
Map([("Content-Type", OCI_MANIFEST_MEDIA_TYPE)]),
manifest_bytes,
repo + ":push",
)
if resp.code < 200 || resp.code >= 300 {
raise OrbitError(
"manifest push failed for tag '\{tag}' (\{format_oci_error(resp.code, resp.reason, body)})",
)
}
}
///|
/// Pack `<dir>/files` and push it with the enriched Orbit config blob.
fn publish(
async fn publish(
ch : Channel,
dir : String,
also_latest : Bool,
@@ -196,37 +731,28 @@ fn publish(
raise OrbitError("bin '\{b}' listed in orbit.json is missing from files/")
}
}
let tmp = trim(capture("mktemp -d"))
sh_ok(
"tar -czf " +
sq(tmp + "/pkg.tar.gz") +
" --owner=0 --group=0 -C " +
sq(files) +
" .",
)
write_text_atomic(tmp + "/orbit.json", config)
let tags = if also_latest { m.version + ",latest" } else { m.version }
let push = oras(
ch,
"push " +
sq(repo_of(ch, m.name) + ":" + tags) +
" --config " +
sq("orbit.json:" + CONFIG_MEDIA_TYPE) +
" --annotation " +
sq("org.opencontainers.image.version=" + m.version) +
(if m.description != "" {
" --annotation " +
sq("org.opencontainers.image.description=" + m.description)
} else {
""
}) +
" " +
sq("pkg.tar.gz:" + LAYER_MEDIA_TYPE),
)
let rc = sh("cd " + sq(tmp) + " && " + push)
sh("rm -rf " + sq(tmp)) |> ignore
if rc != 0 {
raise OrbitError("oras push failed (exit \{rc})")
let tmp = @fs.tmpdir(prefix="orbit-publish-") catch {
e => raise OrbitError("cannot create temp dir: \{e}")
}
defer (@fs.rmdir(tmp, recursive=true, allow_missing=true) catch { _ => () })
let pkg_path = tmp + "/pkg.tar.gz"
sh_ok("tar -czf " + sq(pkg_path) + " --owner=0 --group=0 -C " + sq(files) + " .")
let config_bytes = utf8_encode(config)
let config_digest = sha256_digest(config_bytes)
let config_size = config_bytes.length().to_int64()
let (layer_digest, layer_size) = sha256_file(pkg_path)
let base = channel_base_url(ch)
let repo = channel_repo_path(ch, m.name)
let manifest_bytes = build_oci_manifest_bytes(
m, config_digest, config_size, layer_digest, layer_size,
)
with_spinner("Publishing \{m.name} \{m.version} to \{ch.name}", () => {
upload_blob_bytes(base, repo, config_digest, config_bytes)
upload_blob_file(base, repo, layer_digest, pkg_path, layer_size)
put_manifest(base, repo, m.version, manifest_bytes)
if also_latest {
put_manifest(base, repo, "latest", manifest_bytes)
}
})
println("published \{m.name} \{m.version} to \{repo_of(ch, m.name)}")
}
+872
View File
@@ -0,0 +1,872 @@
// In-process mock OCI Distribution v2 integration tests.
///|
fn strip_query(path : String) -> (String, String) {
split_first(path, '?')
}
///|
async test "native OCI publish, search catalog, tags pagination, resolve, and install" {
token_cache.clear()
let work = @fs.tmpdir(prefix="orbit-wb-reg-")
defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () })
// Stage a test package under work/pkg.
let pkg_dir = work + "/pkg"
@fs.mkdir(pkg_dir + "/files/bin", recursive=true)
@fs.write_file(
pkg_dir + "/orbit.json",
(
#|{
#| "name": "mytool",
#| "version": "1.2.0",
#| "description": "Mock OCI tool",
#| "documentation": "https://example.com/mytool",
#| "bin": ["bin/mytool"],
#| "depends": {}
#|}
),
create_mode=CreateOrTruncate,
)
@fs.write_file(
pkg_dir + "/files/bin/mytool",
"#!/bin/sh\necho ok\n",
create_mode=CreateOrTruncate,
permission=0o755,
)
let blobs : Map[String, Bytes] = Map([])
let uploads : Map[String, String] = Map([])
let manifests : Map[String, (String, Bytes)] = Map([])
let tags : Array[String] = []
let mut upload_seq = 0
let head_405 = Ref(false)
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, query) = strip_query(req.path)
if req.meth is Get && path == "/v2/_catalog" {
let payload = "{\"repositories\":[\"other/ignored\",\"pkgs/mytool\"]}"
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/json",
})
conn.write(payload)
conn.end_response()
return
}
if req.meth is Get && path == "/v2/pkgs/mytool/tags/list" {
if query == "" {
let t0 = if tags.length() > 0 { tags[0] } else { "" }
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/json",
"Link": "</v2/pkgs/mytool/tags/list?page=2>; rel=\"next\"",
})
conn.write("{\"name\":\"pkgs/mytool\",\"tags\":[\"" + t0 + "\"]}")
} else if query == "page=2" {
let t1 = if tags.length() > 1 { tags[1] } else { "" }
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/json",
// Trailing Link header with next empty page (emulates Gitea).
"Link": "</v2/pkgs/mytool/tags/list?page=3>; rel=\"next\"",
})
conn.write("{\"name\":\"pkgs/mytool\",\"tags\":[\"" + t1 + "\"]}")
} else {
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/json",
})
conn.write("{\"name\":\"pkgs/mytool\",\"tags\":null}")
}
conn.end_response()
return
}
if has_prefix(path, "/v2/pkgs/mytool/blobs/uploads/") {
if req.meth is Post {
upload_seq = upload_seq + 1
let id = upload_seq.to_string()
uploads[id] = "pkgs/mytool"
conn.send_response(202, "Accepted", extra_headers={
"Location": "/v2/pkgs/mytool/blobs/uploads/" + id,
})
conn.end_response()
return
}
if req.meth is Put {
let (_, dq) = split_first(query, '=')
let digest = @percent.decode(dq) catch { _ => "" }
blobs[digest] = req_bytes
conn.send_response(201, "Created", extra_headers={
"Docker-Content-Digest": digest,
})
conn.end_response()
return
}
}
if has_prefix(path, "/v2/pkgs/mytool/blobs/") {
let digest = drop_chars(path, 22)
match blobs.get(digest) {
Some(data) => {
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/octet-stream",
"Docker-Content-Digest": digest,
"Content-Length": data.length().to_string(),
})
if !(req.meth is Head) {
conn.write(data)
}
conn.end_response()
}
None => {
conn.send_response(404, "Not Found")
conn.end_response()
}
}
return
}
if has_prefix(path, "/v2/pkgs/mytool/manifests/") {
let ref_str = drop_chars(path, 26)
if req.meth is Put {
let d = sha256_digest(req_bytes)
manifests[ref_str] = (d, req_bytes)
manifests[d] = (d, req_bytes)
if !tags.contains(ref_str) {
tags.push(ref_str)
}
conn.send_response(201, "Created", extra_headers={
"Docker-Content-Digest": d,
})
conn.end_response()
return
}
if req.meth is Head && head_405.val {
conn.send_response(405, "Method Not Allowed")
conn.end_response()
return
}
match manifests.get(ref_str) {
Some((d, data)) => {
conn.send_response(200, "OK", extra_headers={
"Content-Type": OCI_MANIFEST_MEDIA_TYPE,
"Docker-Content-Digest": d,
"Content-Length": data.length().to_string(),
})
if !(req.meth is Head) {
conn.write(data)
}
conn.end_response()
}
None => {
conn.send_response(404, "Not Found")
conn.end_response()
}
}
return
}
conn.send_response(404, "Not Found")
conn.end_response()
})
})
let addr = "127.0.0.1:" + server.addr.port().to_string()
let ch = Channel::{ name: "local", url: addr + "/pkgs", plain_http: true }
publish(ch, pkg_dir, true)
let repos = list_repos(ch)
assert_eq(repos, ["mytool"])
let got_tags = list_tags(ch, "mytool").unwrap()
assert_eq(got_tags, ["1.2.0", "latest"])
let d1 = resolve_digest(ch, "mytool", "1.2.0")
head_405.val = true
let d2 = resolve_digest(ch, "mytool", "1.2.0")
assert_eq(d1, d2)
let mf = fetch_manifest_cached("", ch, "mytool", d1)
assert_eq(mf.name, "mytool")
assert_eq(mf.version, "1.2.0")
assert_eq(mf.description, "Mock OCI tool")
assert_eq(mf.bins, ["bin/mytool"])
let orbit_dir = work + "/orbit"
let mf_cached = fetch_manifest_cached(orbit_dir, ch, "mytool", d1)
assert_eq(mf_cached.version, "1.2.0")
let ctx = Ctx::{ root: orbit_dir, channels: [ch], state: Map([]) }
let installed_dir = fetch_into_store(ctx, ch, "mytool", d1)
assert_true(exists(installed_dir + "/bin/mytool"))
})
}
///|
async test "Bearer token exchange, Basic auth login, and cross-origin redirect strip" {
token_cache.clear()
let work = @fs.tmpdir(prefix="orbit-wb-auth-")
defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () })
let payload = b"hello-blob-payload"
let payload_digest = sha256_digest(payload)
let cdn_auth_seen : Ref[String?] = Ref(None)
let cdn = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
let reg = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
@async.with_task_group(group => {
defer cdn.close()
defer reg.close()
let cdn_addr = "127.0.0.1:" + cdn.addr.port().to_string()
let reg_addr = "127.0.0.1:" + reg.addr.port().to_string()
group.spawn_bg(no_wait=true, () => {
cdn.run_forever((req, body, conn) => {
ignore(body.read_all())
cdn_auth_seen.val = req.headers.get(hdr("Authorization"))
conn.send_response(200, "OK", extra_headers={
"Content-Length": payload.length().to_string(),
})
conn.write(payload)
conn.end_response()
})
})
group.spawn_bg(no_wait=true, () => {
reg.run_forever((req, body, conn) => {
ignore(body.read_all())
let (path, _) = strip_query(req.path)
let auth = req.headers.get(hdr("Authorization")).unwrap_or("")
if path == "/v2/token" {
let expected = "Basic " +
encode_basic_auth(Creds::{ username: "alice", password: "pw" })
if auth == expected {
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/json",
})
conn.write("{\"token\":\"tok123\"}")
} else {
conn.send_response(401, "Unauthorized")
}
conn.end_response()
return
}
if path == "/v2/" {
if auth == "Bearer tok123" {
conn.send_response(200, "OK")
} else {
conn.send_response(401, "Unauthorized", extra_headers={
"WWW-Authenticate": "Bearer realm=\"http://" +
reg_addr +
"/v2/token\",service=\"test\",scope=\"*\"",
})
}
conn.end_response()
return
}
if path == "/v2/pkgs/a/blobs/" + payload_digest {
if auth == "Bearer tok123" {
conn.send_response(307, "Temporary Redirect", extra_headers={
"Location": "http://" + cdn_addr + "/blob-data",
})
} else {
conn.send_response(401, "Unauthorized", extra_headers={
"WWW-Authenticate": "Bearer realm=\"http://" +
reg_addr +
"/v2/token\",service=\"test\",scope=\"repository:pkgs/a:pull\"",
})
}
conn.end_response()
return
}
if path == "/v2/pkgs/a/blobs/sha256:0000" {
conn.send_response(200, "OK")
conn.write(b"corrupted-bytes")
conn.end_response()
return
}
conn.send_response(404, "Not Found")
conn.end_response()
})
})
verify_login(reg_addr, true, Creds::{ username: "alice", password: "pw" })
let bad_login = try {
verify_login(reg_addr, true, Creds::{ username: "alice", password: "bad" })
false
} catch {
OrbitError(_) => true
}
assert_true(bad_login)
// Pre-seed token cache for reg_addr to verify cross-origin redirect strips Authorization.
token_cache[token_cache_key(reg_addr, "pkgs/a:pull")] = "tok123"
let dl_path = work + "/blob.bin"
oci_download_to_file(
"http://" + reg_addr + "/v2/pkgs/a/blobs/" + payload_digest,
dl_path,
payload_digest,
"pkgs/a:pull",
)
assert_true(cdn_auth_seen.val is None)
assert_eq(@fs.read_file(dl_path).binary(), payload)
let mismatch_err = try {
oci_download_to_file(
"http://" + reg_addr + "/v2/pkgs/a/blobs/sha256:0000",
work + "/bad.bin",
"sha256:0000",
"pkgs/a:pull",
)
false
} catch {
OrbitError(msg) => contains_str(msg, "digest mismatch")
}
assert_true(mismatch_err)
})
}
///|
async test "channel locate falls through on 404 and fails on 500" {
token_cache.clear()
let mode1 = Ref(404)
let s1 = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
let s2 = @http.Server(@socket.Addr::parse("127.0.0.1:0"))
@async.with_task_group(group => {
defer s1.close()
defer s2.close()
group.spawn_bg(no_wait=true, () => {
s1.run_forever((_req, body, conn) => {
ignore(body.read_all())
conn.send_response(mode1.val, "Status")
conn.end_response()
})
})
group.spawn_bg(no_wait=true, () => {
s2.run_forever((_req, body, conn) => {
ignore(body.read_all())
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/json",
})
conn.write("{\"name\":\"c2/pkg\",\"tags\":[\"1.0.0\"]}")
conn.end_response()
})
})
let ch1 = Channel::{
name: "first",
url: "127.0.0.1:" + s1.addr.port().to_string() + "/c1",
plain_http: true,
}
let ch2 = Channel::{
name: "second",
url: "127.0.0.1:" + s2.addr.port().to_string() + "/c2",
plain_http: true,
}
let ctx = Ctx::{ root: "/tmp/unused", channels: [ch1, ch2], state: Map([]) }
let (picked, ts) = locate(ctx, "pkg", None)
assert_eq(picked.name, "second")
assert_eq(ts, ["1.0.0"])
mode1.val = 500
let failed = try {
ignore(locate(ctx, "pkg", None))
false
} catch {
OrbitError(_) => true
}
assert_true(failed)
})
}
///|
fn split_sub(s : String, sep : String) -> (String, String)? {
let a = chars(s)
let b = chars(sep)
if b.length() == 0 || a.length() < b.length() {
return None
}
for i = 0; i + b.length() <= a.length(); i = i + 1 {
let mut ok = true
for j = 0; j < b.length(); j = j + 1 {
if a[i + j] != b[j] {
ok = false
break
}
}
if ok {
return Some((slice(a, 0, i), slice(a, i + b.length(), a.length())))
}
}
None
}
///|
struct MockOciState {
blobs : Map[String, Bytes]
manifests : Map[String, Map[String, (String, Bytes)]]
tags : Map[String, Array[String]]
blob_gets : Ref[Int32]
}
///|
fn new_mock_oci_state() -> MockOciState {
MockOciState::{
blobs: Map([]),
manifests: Map([]),
tags: Map([]),
blob_gets: Ref(0),
}
}
///|
async fn handle_mock_oci(
st : MockOciState,
upload_seq : Ref[Int32],
req : @http.Request,
req_bytes : Bytes,
conn : @http.ServerConnection,
) -> Unit {
let (path, query) = strip_query(req.path)
if req.meth is Get && path == "/v2/_catalog" {
let repos : Array[Json] = []
for r, _ in st.tags {
repos.push(Json::string(r))
}
let top : Map[String, Json] = Map([])
top["repositories"] = Json::array(repos)
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/json",
})
conn.write(Json::object(top).stringify())
conn.end_response()
return
}
if !has_prefix(path, "/v2/") {
conn.send_response(404, "Not Found")
conn.end_response()
return
}
let rest = drop_chars(path, 4)
match split_sub(rest, "/tags/list") {
Some((repo, "")) =>
match st.tags.get(repo) {
Some(ts) => {
let jtags = ts.map(fn(t) { Json::string(t) })
let obj : Map[String, Json] = Map([])
obj["name"] = Json::string(repo)
obj["tags"] = Json::array(jtags)
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/json",
})
conn.write(Json::object(obj).stringify())
conn.end_response()
return
}
None => {
conn.send_response(404, "Not Found")
conn.end_response()
return
}
}
_ => ()
}
match split_sub(rest, "/blobs/uploads/") {
Some((repo, _id)) => {
if req.meth is Post {
upload_seq.val = upload_seq.val + 1
conn.send_response(202, "Accepted", extra_headers={
"Location": "/v2/" + repo + "/blobs/uploads/" + upload_seq.val.to_string(),
})
conn.end_response()
return
}
if req.meth is Put {
let (_, dq) = split_first(query, '=')
let digest = @percent.decode(dq) catch { _ => "" }
st.blobs[repo + "|" + digest] = req_bytes
conn.send_response(201, "Created", extra_headers={
"Docker-Content-Digest": digest,
})
conn.end_response()
return
}
}
None => ()
}
match split_sub(rest, "/blobs/") {
Some((repo, digest)) => {
match st.blobs.get(repo + "|" + digest) {
Some(data) => {
if !(req.meth is Head) {
st.blob_gets.val = st.blob_gets.val + 1
}
conn.send_response(200, "OK", extra_headers={
"Content-Type": "application/octet-stream",
"Docker-Content-Digest": digest,
"Content-Length": data.length().to_string(),
})
if !(req.meth is Head) {
conn.write(data)
}
conn.end_response()
}
None => {
conn.send_response(404, "Not Found")
conn.end_response()
}
}
return
}
None => ()
}
match split_sub(rest, "/manifests/") {
Some((repo, ref_str)) => {
if req.meth is Put {
let d = sha256_digest(req_bytes)
let repo_map = match st.manifests.get(repo) {
Some(m) => m
None => {
let m : Map[String, (String, Bytes)] = Map([])
st.manifests[repo] = m
m
}
}
repo_map[ref_str] = (d, req_bytes)
repo_map[d] = (d, req_bytes)
let ts = match st.tags.get(repo) {
Some(xs) => xs
None => {
let xs : Array[String] = []
st.tags[repo] = xs
xs
}
}
if !ts.contains(ref_str) {
ts.push(ref_str)
}
conn.send_response(201, "Created", extra_headers={
"Docker-Content-Digest": d,
})
conn.end_response()
return
}
match st.manifests.get(repo) {
Some(repo_map) =>
match repo_map.get(ref_str) {
Some((d, data)) => {
conn.send_response(200, "OK", extra_headers={
"Content-Type": OCI_MANIFEST_MEDIA_TYPE,
"Docker-Content-Digest": d,
"Content-Length": data.length().to_string(),
})
if !(req.meth is Head) {
conn.write(data)
}
conn.end_response()
}
None => {
conn.send_response(404, "Not Found")
conn.end_response()
}
}
None => {
conn.send_response(404, "Not Found")
conn.end_response()
}
}
return
}
None => ()
}
conn.send_response(404, "Not Found")
conn.end_response()
}
///|
async fn publish_mock_pkg(
ch : Channel,
work : String,
name : String,
version : String,
depends : Map[String, String],
bins : Array[String],
script? : String = "#!/bin/sh\necho ok\n",
) -> Unit raise Error {
let pkg_dir = work + "/stage-" + name + "-" + version
@fs.mkdir(pkg_dir + "/files/bin", recursive=true)
let mf_obj : Map[String, Json] = Map([])
mf_obj["name"] = Json::string(name)
mf_obj["version"] = Json::string(version)
mf_obj["description"] = Json::string("Mock " + name + " " + version)
mf_obj["bin"] = strs_json(bins)
mf_obj["depends"] = map_json(depends)
@fs.write_file(
pkg_dir + "/orbit.json",
Json::object(mf_obj).stringify(indent=2) + "\n",
create_mode=CreateOrTruncate,
)
for b in bins {
let p = pkg_dir + "/files/" + b
@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)
}
///|
async test "SAT global install, backtracking, manifest cache, and joint upgrade" {
token_cache.clear()
let work = @fs.tmpdir(prefix="orbit-wb-sat-global-")
defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () })
let st = new_mock_oci_state()
let upload_seq = Ref(0)
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()
handle_mock_oci(st, upload_seq, req, req_bytes, conn)
})
})
let addr = "127.0.0.1:" + server.addr.port().to_string()
let main_ch = Channel::{
name: "main",
url: addr + "/main",
plain_http: true,
}
let extra_ch = Channel::{
name: "extra",
url: addr + "/extra",
plain_http: true,
}
publish_mock_pkg(main_ch, work, "lib", "1.0.0", Map([]), [])
publish_mock_pkg(main_ch, work, "lib", "2.0.0", Map([]), [])
publish_mock_pkg(
main_ch,
work,
"app",
"1.0.0",
Map([("lib", "^1.0")]),
["bin/app"],
script="#!/bin/sh\necho app-1.0.0\n",
)
publish_mock_pkg(
main_ch,
work,
"app",
"2.0.0",
Map([("lib", "^2.0")]),
["bin/app"],
script="#!/bin/sh\necho app-2.0.0\n",
)
publish_mock_pkg(
extra_ch,
work,
"helper",
"1.0.0",
Map([("main::lib", "^1.0")]),
["bin/helper"],
script="#!/bin/sh\necho helper-1.0.0\n",
)
let orbit_root = work + "/orbit"
let ctx = Ctx::{
root: orbit_root,
channels: [main_ch, extra_ch],
state: Map([]),
}
cmd_install(ctx, ["app", "helper"])
assert_eq(ctx.state["app"].version, "1.0.0")
assert_eq(ctx.state["helper"].version, "1.0.0")
assert_eq(ctx.state["helper"].channel, "extra")
assert_eq(ctx.state["lib"].version, "1.0.0")
assert_true(exists(orbit_root + "/bin/app"))
assert_true(exists(orbit_root + "/bin/helper"))
let cached_files = @fs.readdir(cache_dir(orbit_root))
assert_true(cached_files.length() > 0)
// Verify digest-keyed manifest cache avoids HTTP blob GET on re-solve.
let gets_before = st.blob_gets.val
let _ = fetch_manifest_cached(
orbit_root,
main_ch,
"app",
ctx.state["app"].digest,
)
assert_eq(st.blob_gets.val, gets_before)
// Publish helper 2.0.0 compatible with lib ^2.0, then upgrade jointly.
publish_mock_pkg(
extra_ch,
work,
"helper",
"2.0.0",
Map([("main::lib", "^2.0")]),
["bin/helper"],
script="#!/bin/sh\necho helper-2.0.0\n",
)
cmd_upgrade(ctx, [])
assert_eq(ctx.state["app"].version, "2.0.0")
assert_eq(ctx.state["helper"].version, "2.0.0")
assert_eq(ctx.state["lib"].version, "2.0.0")
})
}
///|
async test "Pixi-style project workflow: new, add, sync --locked, run, update, remove" {
try {
token_cache.clear()
let work = @fs.tmpdir(prefix="orbit-wb-project-")
defer (@fs.rmdir(work, recursive=true, allow_missing=true) catch { _ => () })
let st = new_mock_oci_state()
let upload_seq = Ref(0)
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()
handle_mock_oci(st, upload_seq, req, req_bytes, conn)
})
})
let addr = "127.0.0.1:" + server.addr.port().to_string()
let main_ch = Channel::{
name: "main",
url: addr + "/main",
plain_http: true,
}
publish_mock_pkg(main_ch, work, "lib", "1.0.0", Map([]), [])
publish_mock_pkg(main_ch, work, "lib", "2.0.0", Map([]), [])
publish_mock_pkg(
main_ch,
work,
"app",
"1.0.0",
Map([("lib", "^1.0")]),
["bin/app"],
script="#!/bin/sh\necho proj-app-1\n",
)
publish_mock_pkg(
main_ch,
work,
"app",
"2.0.0",
Map([("lib", "^2.0")]),
["bin/app"],
script="#!/bin/sh\necho proj-app-2\n",
)
publish_mock_pkg(
main_ch,
work,
"helper",
"1.0.0",
Map([("lib", "^1.0")]),
["bin/helper"],
script="#!/bin/sh\nexit 0\n",
)
let proj = work + "/proj"
cmd_project_init(Some(proj))
let mf = proj + "/orbit.toml"
assert_true(exists(mf))
// Configure project channel + tasks.
let m0 = parse_project_manifest(
"[project]\nname = \"proj\"\nversion = \"0.1.0\"\n\n[[channels]]\nname = \"main\"\nurl = \"" +
main_ch.url +
"\"\nplain-http = true\n\n[dependencies]\n\n[tasks]\nshow = \"app\"\ncheck = [\"helper\", \"--ok\"]\n",
"proj",
)
write_text_atomic(mf, project_to_toml(m0))
let orbit_root = work + "/orbit"
let ctx = Ctx::{ root: orbit_root, channels: [main_ch], state: Map([]) }
// Discovery via explicit directory & manifest path.
assert_eq(find_project_manifest(Some(proj)).unwrap(), mf)
assert_eq(find_project_manifest(Some(mf)).unwrap(), mf)
// Add packages -> SAT solver picks 1.0.0 + 1.0.0 + lib 1.0.0, pins ^1.0.0,
// writes orbit.lock, and syncs .orbit/bin.
cmd_project_add(ctx, mf, ["app", "helper"])
let m_after_add = parse_project_manifest(read_text(mf).unwrap(), "proj")
assert_eq(m_after_add.dependencies["app"].constraint, "^1.0.0")
assert_eq(m_after_add.dependencies["helper"].constraint, "^1.0.0")
let lock1 = parse_lockfile(read_text(proj + "/orbit.lock").unwrap())
assert_eq(lock1.packages.length(), 3)
assert_true(exists(proj + "/.orbit/.gitignore"))
assert_true(exists(proj + "/.orbit/bin/app"))
assert_true(exists(proj + "/.orbit/bin/helper"))
// Run tasks and direct commands through .orbit/bin.
assert_eq(run_project_command(ctx, mf, ["show"], false, false), 0)
assert_eq(run_project_command(ctx, mf, ["check"], true, false), 0)
assert_eq(run_project_command(ctx, mf, ["helper", "--direct"], true, false), 0)
// --locked passes while in sync.
cmd_project_sync(ctx, mf, true, false)
// Transactional rollback on failed `orbit add`: files remain identical.
let saved_toml = read_text(mf).unwrap()
let saved_lock = read_text(proj + "/orbit.lock").unwrap()
let bad_add = try {
cmd_project_add(ctx, mf, ["missingpkg"])
false
} catch {
OrbitError(_) => true
}
assert_true(bad_add)
assert_eq(read_text(mf).unwrap(), saved_toml)
assert_eq(read_text(proj + "/orbit.lock").unwrap(), saved_lock)
// Require >=2.0.0 so lockfile (at 1.0.0) is out of date -> --locked fails.
m_after_add.dependencies["app"].constraint = ">=2.0.0"
write_text_atomic(mf, project_to_toml(m_after_add))
let locked_fail = try {
cmd_project_sync(ctx, mf, true, false)
false
} catch {
OrbitError(_) => true
}
assert_true(locked_fail)
// Broaden constraints to "*", re-lock, then publish helper 2.0.0 and update.
m_after_add.dependencies["app"].constraint = "*"
m_after_add.dependencies["helper"].constraint = "*"
write_text_atomic(mf, project_to_toml(m_after_add))
cmd_project_lock(ctx, mf, false)
// Publish helper 2.0.0 -> update upgrades app, helper, lib to 2.0.0.
publish_mock_pkg(
main_ch,
work,
"helper",
"2.0.0",
Map([("lib", "^2.0")]),
["bin/helper"],
script="#!/bin/sh\nexit 0\n",
)
cmd_project_update(ctx, mf, [])
let lock2 = parse_lockfile(read_text(proj + "/orbit.lock").unwrap())
for p in lock2.packages {
assert_eq(p.version, "2.0.0")
}
// Remove packages -> cleans dependencies, orbit.lock, and .orbit/bin.
cmd_project_remove(ctx, mf, ["app", "helper"])
let m_final = parse_project_manifest(read_text(mf).unwrap(), "proj")
assert_eq(m_final.dependencies.length(), 0)
let lock_final = parse_lockfile(read_text(proj + "/orbit.lock").unwrap())
assert_eq(lock_final.packages.length(), 0)
assert_false(exists(proj + "/.orbit/bin/app"))
assert_false(exists(proj + "/.orbit/bin/helper"))
})
} catch {
OrbitError(msg) => fail("unexpected OrbitError: " + msg)
e => raise e
}
}
+263 -135
View File
@@ -1,34 +1,31 @@
// Minimal semantic versions and constraints.
//
// Constraint forms:
// Constraint forms (comma-separated clauses are ANDed together):
// "" | "*" | "latest" any stable version
// "1.2.3" | "=1.2.3" exact
// "1" | "1.2" prefix (1.x.x / 1.2.x)
// "1.2.3" | "=1.2.3" | "==1.2.3" exact
// "1" | "1.2" | "1.*" | "1.2.*" prefix (1.x.x / 1.2.x)
// "^1.2.3" same major (same minor while major is 0), >= base
// "~1.2.3" same major and minor, >= base
// ">=1.2.3" at least base
// "~1.2.3" same major and minor (or major if ~1), >= base
// ">=1.2.3" | "<=1.2.3" | ">1.2.3" | "<1.2.3" relational
// "!=1.2.3" | "!=1.2.*" exclusion
// Prerelease versions (1.0.0-rc1) only match constraints that mention a '-'.
///|
struct Ver {
nums : Array[Int32]
nums : Array[Int64]
parts : Int32
pre : String
}
///|
fn parse_nat(s : String) -> Int32? {
if s == "" {
return None
fn parse_nat(s : String) -> Int64? {
let codes = FixedArray::from_array(chars(s).map(c => c.to_int().to_int64()))
let n = @kernel.parse_nat(codes)
if n < 0L {
None
} else {
Some(n)
}
let mut n = 0
for c in s {
if c < '0' || c > '9' {
return None
}
n = n * 10 + (c.to_int() - '0'.to_int())
}
Some(n)
}
///|
@@ -40,7 +37,7 @@ fn parse_ver(s0 : String) -> Ver? {
if parts.length() == 0 || parts.length() > 3 {
return None
}
let nums = [0, 0, 0]
let nums = [0L, 0L, 0L]
for i = 0; i < parts.length(); i = i + 1 {
match parse_nat(parts[i]) {
Some(n) => nums[i] = n
@@ -59,20 +56,107 @@ fn is_ver(s : String) -> Bool {
}
///|
fn cmp_ver(a : Ver, b : Ver) -> Int32 {
for i = 0; i < 3; i = i + 1 {
if a.nums[i] != b.nums[i] {
return if a.nums[i] < b.nums[i] { -1 } else { 1 }
}
}
if a.pre == b.pre {
fn ver_key(v : Ver, pre : Int32) -> @kernel.Key {
{ major: v.nums[0], minor: v.nums[1], patch: v.nums[2], pre, }
}
///|
/// Order of prereleases; a release ("") comes after all of them.
fn cmp_pre(a : String, b : String) -> Int32 {
if a == b {
0
} else if a.pre == "" {
} else if a == "" {
1
} else if b.pre == "" {
} else if b == "" {
-1
} else {
a.pre.compare(b.pre)
a.compare(b)
}
}
///|
fn cmp_ver(a : Ver, b : Ver) -> Int32 {
@kernel.compare(ver_key(a, cmp_pre(a.pre, b.pre)), ver_key(b, 0))
}
///|
fn strip_dot_star(s : String) -> (String, Bool) {
let a = chars(s)
let n = a.length()
if n >= 2 && a[n - 2] == '.' && a[n - 1] == '*' {
(slice(a, 0, n - 2), true)
} else {
(s, false)
}
}
///|
/// Split a clause into its operator and the version it applies to; `None` if it
/// is malformed.
fn parse_clause(cl : String) -> (@kernel.Op, Ver)? {
let c = trim(cl)
if c == "*" || c == "latest" {
return Some((Any, Ver::{ nums: [0L, 0L, 0L], parts: 3, pre: "", }))
}
let plain = fn(op : @kernel.Op, rest : String) -> (@kernel.Op, Ver)? {
match parse_ver(trim(rest)) {
Some(b) => Some((op, b))
None => None
}
}
// An exact version, or a prefix when parts are missing or end in ".*".
let exact = fn(
whole : @kernel.Op,
prefix : @kernel.Op,
rest : String,
) -> (@kernel.Op, Ver)? {
let (ver_str, had_wild) = strip_dot_star(trim(rest))
match parse_ver(ver_str) {
Some(b) =>
if b.parts < 3 {
Some((prefix, b))
} else if had_wild {
None
} else {
Some((whole, b))
}
None => None
}
}
if has_prefix(c, ">=") {
plain(Ge, drop_chars(c, 2))
} else if has_prefix(c, "<=") {
plain(Le, drop_chars(c, 2))
} else if has_prefix(c, "!=") {
exact(Ne, NotPrefix, drop_chars(c, 2))
} else if has_prefix(c, "==") {
exact(Eq, Prefix, drop_chars(c, 2))
} else if has_prefix(c, ">") {
plain(Gt, drop_chars(c, 1))
} else if has_prefix(c, "<") {
plain(Lt, drop_chars(c, 1))
} else if has_prefix(c, "^") {
plain(Caret, drop_chars(c, 1))
} else if has_prefix(c, "~") {
plain(Tilde, drop_chars(c, 1))
} else if has_prefix(c, "=") {
exact(Eq, Prefix, drop_chars(c, 1))
} else {
exact(Eq, Prefix, c)
}
}
///|
fn satisfies_clause(v : Ver, cl : String) -> Bool {
match parse_clause(cl) {
Some((op, b)) =>
@kernel.matches(
op,
ver_key(v, cmp_pre(v.pre, b.pre)),
ver_key(b, 0),
b.parts,
)
None => false
}
}
@@ -82,43 +166,54 @@ fn satisfies(v : Ver, c0 : String) -> Bool {
if c == "" || c == "*" || c == "latest" {
return v.pre == ""
}
if v.pre != "" && !(has_char(c, '-')) {
if v.pre != "" && !has_char(c, '-') {
return false
}
let with_base = fn(rest : String, rule : (Ver) -> Bool) -> Bool {
match parse_ver(rest) {
Some(b) => cmp_ver(v, b) >= 0 && rule(b)
None => false
let pieces = split_on(c, ',')
for piece in pieces {
let p = trim(piece)
if p == "" || !satisfies_clause(v, p) {
return false
}
}
if has_prefix(c, ">=") {
with_base(drop_chars(c, 2), fn(_b) { true })
} else if has_prefix(c, "^") {
with_base(drop_chars(c, 1), fn(b) {
v.nums[0] == b.nums[0] && (b.nums[0] != 0 || v.nums[1] == b.nums[1])
})
} else if has_prefix(c, "~") {
with_base(drop_chars(c, 1), fn(b) {
v.nums[0] == b.nums[0] && v.nums[1] == b.nums[1]
})
} else {
let exact = if has_prefix(c, "=") { drop_chars(c, 1) } else { c }
match parse_ver(exact) {
Some(b) =>
if b.parts == 3 {
cmp_ver(v, b) == 0
} else {
let mut ok = true
for i = 0; i < b.parts; i = i + 1 {
if v.nums[i] != b.nums[i] {
ok = false
}
}
ok
}
None => false
}
true
}
///|
fn valid_semver_clause(cl : String) -> Bool {
parse_clause(cl) is Some(_)
}
///|
fn valid_constraint(c0 : String) -> Bool {
let c = trim(c0)
if c == "" || c == "*" || c == "latest" {
return true
}
if !has_char(c, ',') && valid_semver_clause(c) {
return true
}
if has_char(c, ',') {
let pieces = split_on(c, ',')
for piece in pieces {
if !valid_semver_clause(piece) {
return false
}
}
return true
}
// Allow non-semver literal tag pins (e.g. "edge") when they aren't malformed
// version numbers or operator expressions.
let a = chars(c)
let looks_like_ver = a.length() > 0 &&
(
(a[0] >= '0' && a[0] <= '9') ||
(a.length() > 1 && a[0] == 'v' && a[1] >= '0' && a[1] <= '9')
)
if looks_like_ver {
return false
}
valid_name(c)
}
///|
@@ -126,7 +221,7 @@ fn satisfies_all(version : String, cons : Array[String]) -> Bool {
match parse_ver(version) {
Some(v) => {
for c in cons {
if !(satisfies(v, c)) {
if !satisfies(v, c) {
return false
}
}
@@ -136,7 +231,11 @@ fn satisfies_all(version : String, cons : Array[String]) -> Bool {
None => {
for c in cons {
let t = trim(c)
if t != "" && t != "*" && t != version {
if t != "" &&
t != "*" &&
t != version &&
t != "=" + version &&
t != "==" + version {
return false
}
}
@@ -145,97 +244,126 @@ fn satisfies_all(version : String, cons : Array[String]) -> Bool {
}
}
///|
/// Pick the highest tag that satisfies every constraint. Falls back to a
/// literal non-semver tag when a constraint names one exactly.
fn pick_tag(tags : Array[String], cons : Array[String]) -> String? {
let mut best : (String, Ver)? = None
for t in tags {
match parse_ver(t) {
Some(v) =>
if satisfies_all(t, cons) {
match best {
None => best = Some((t, v))
Some((_, bv)) => if cmp_ver(v, bv) > 0 { best = Some((t, v)) }
}
}
None => ()
}
}
match best {
Some((t, _)) => Some(t)
None => {
for c in cons {
let t = trim(c)
if t != "" && t != "*" && !(is_ver(t)) && tags.contains(t) {
return Some(t)
}
}
None
}
}
}
///|
/// Semver tags, highest first.
fn sorted_versions(tags : Array[String]) -> Array[String] {
let out : Array[(String, Ver)] = []
let names : Array[String] = []
let vers : Array[Ver] = []
for t in tags {
match parse_ver(t) {
Some(v) => out.push((t, v))
Some(v) => {
names.push(t)
vers.push(v)
}
None => ()
}
}
// insertion sort, descending
for i = 1; i < out.length(); i = i + 1 {
let mut j = i
while j > 0 && cmp_ver(out[j].1, out[j - 1].1) > 0 {
let tmp = out[j]
out[j] = out[j - 1]
out[j - 1] = tmp
j = j - 1
let order = @kernel.sort_desc(FixedArray::from_array(ver_keys(vers)))
Array::makei(order.length(), fn(i) { names[order[i]] })
}
///|
/// Keys that order `vers`: the prerelease rank is how many prereleases among
/// `vers` come before it.
fn ver_keys(vers : Array[Ver]) -> Array[@kernel.Key] {
vers.map(fn(v) {
let mut rank = 0
for other in vers {
if cmp_pre(other.pre, v.pre) < 0 {
rank = rank + 1
}
}
ver_key(v, rank)
})
}
// Number parsing, ordering, interval and sorting laws are proved in
// src/kernel. The tests below cover what the prover cannot see: splitting
// strings into versions and clauses, and ranking prereleases.
///|
test "versions parse into numbers and a prerelease" {
let a = parse_ver("v1.10-rc1+build").unwrap()
assert_eq(a.nums, [1L, 10L, 0L])
assert_eq(a.parts, 2)
assert_eq(a.pre, "rc1")
assert_eq(parse_ver("1.0.20261130123000").unwrap().nums, [
1L, 0L, 20261130123000L,
])
for bad in ["", "1.x", "1.", "1.2.3.4", "1.-2", "1.0.1000000000000000000"] {
assert_true(parse_ver(bad) is None)
}
let r : Array[String] = []
for p in out {
r.push(p.0)
}
r
}
///|
test "parse and compare" {
let a = parse_ver("1.2.3").unwrap()
let b = parse_ver("v1.10.0").unwrap()
assert_true(cmp_ver(a, b) < 0)
assert_true(
cmp_ver(parse_ver("1.0.0-rc1").unwrap(), parse_ver("1.0.0").unwrap()) < 0,
test "prereleases rank below their release and by name" {
assert_eq(
sorted_versions([
"1.0.0-rc1", "edge", "2.0.0", "1.0.0", "1.0.0-rc2", "2.1.0-rc1",
]),
["2.1.0-rc1", "2.0.0", "1.0.0", "1.0.0-rc2", "1.0.0-rc1"],
)
assert_true(parse_ver("1.x") is None)
let rc1 = parse_ver("1.0.0-rc1").unwrap()
assert_true(cmp_ver(rc1, parse_ver("1.0.0").unwrap()) < 0)
assert_true(cmp_ver(rc1, parse_ver("1.0.0-rc2").unwrap()) < 0)
assert_eq(cmp_ver(rc1, rc1), 0)
}
///|
test "constraints" {
test "clauses parse into an operator and a version" {
let table : Array[(String, (@kernel.Op, Array[Int64], Int32)?)] = [
("*", Some((Any, [0L, 0L, 0L], 3))),
("latest", Some((Any, [0L, 0L, 0L], 3))),
(">=1.2", Some((Ge, [1L, 2L, 0L], 2))),
("<= 1.2.3", Some((Le, [1L, 2L, 3L], 3))),
(">1", Some((Gt, [1L, 0L, 0L], 1))),
("<2.0.0", Some((Lt, [2L, 0L, 0L], 3))),
("^1.2.0", Some((Caret, [1L, 2L, 0L], 3))),
("~1", Some((Tilde, [1L, 0L, 0L], 1))),
("1.4.2", Some((Eq, [1L, 4L, 2L], 3))),
("=1.4.2", Some((Eq, [1L, 4L, 2L], 3))),
("==1.4.2", Some((Eq, [1L, 4L, 2L], 3))),
("1.4", Some((Prefix, [1L, 4L, 0L], 2))),
("==1.4.*", Some((Prefix, [1L, 4L, 0L], 2))),
("1.*", Some((Prefix, [1L, 0L, 0L], 1))),
("!=1.4.2", Some((Ne, [1L, 4L, 2L], 3))),
("!=1.2.*", Some((NotPrefix, [1L, 2L, 0L], 2))),
("", None),
("<=", None),
(">=abc", None),
("^^1.0", None),
("~>1.0", None),
("1.2.3.*", None),
("1.2.3.4", None),
]
for row in table {
let (text, want) = row
let got = match parse_clause(text) {
Some((op, b)) => Some((op, b.nums, b.parts))
None => None
}
assert_eq(got, want, msg=text)
}
}
///|
test "constraints join clauses and gate prereleases" {
let v = parse_ver("1.4.2").unwrap()
assert_true(satisfies(v, "^1.2.0"))
assert_true(!(satisfies(v, "^2.0.0")))
assert_true(satisfies(v, "~1.4.0"))
assert_true(!(satisfies(v, "~1.3.0")))
assert_true(satisfies(v, ">=1.0"))
assert_true(satisfies(v, "1"))
assert_true(satisfies(v, "1.4"))
assert_true(!(satisfies(v, "1.5")))
let rc = parse_ver("1.2.0-rc1").unwrap()
assert_true(satisfies(v, ">=1.0, !=1.4.1, <2.0"))
assert_false(satisfies(v, ">=1.0, !=1.4.2, <2.0"))
assert_true(satisfies(v, "*"))
assert_true(!(satisfies(parse_ver("0.3.1").unwrap(), "^0.2.0")))
}
assert_false(satisfies(rc, "*"))
assert_true(satisfies(rc, ">=1.0.0-rc1, <2.0.0"))
assert_false(satisfies(rc, ">=1.0.0, <2.0.0"))
///|
test "pick" {
let tags = ["1.0.0", "1.2.0", "2.0.0", "2.1.0-rc1", "latest"]
assert_eq(pick_tag(tags, ["*"]), Some("2.0.0"))
assert_eq(pick_tag(tags, ["^1.0.0"]), Some("1.2.0"))
assert_eq(pick_tag(tags, ["^1.0.0", "~1.0.0"]), Some("1.0.0"))
assert_eq(pick_tag(tags, ["latest"]), Some("2.0.0"))
assert_eq(pick_tag(tags, ["^3"]), None)
assert_eq(sorted_versions(tags), ["2.1.0-rc1", "2.0.0", "1.2.0", "1.0.0"])
assert_true(satisfies_all("1.4.2", ["^1.0.0", "~1.4.0"]))
assert_false(satisfies_all("1.4.2", ["^1.0.0", "~1.3.0"]))
assert_true(satisfies_all("edge", ["edge", "=edge", "==edge", "*"]))
assert_false(satisfies_all("edge", [">=1.0"]))
assert_true(valid_constraint(">=1.2.0, <2.0.0"))
assert_true(valid_constraint("edge"))
assert_false(valid_constraint(">=1,"))
assert_false(valid_constraint("1.2.3.4"))
}
+226
View File
@@ -0,0 +1,226 @@
// Pure MoonBit streaming SHA-256 (FIPS 180-4).
///|
let sha256_k : FixedArray[UInt32] = [
0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U,
0x923f82a4U, 0xab1c5ed5U, 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U,
0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U, 0xe49b69c1U, 0xefbe4786U,
0x0fc19dc6U, 0x240ca1ccU, 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU,
0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, 0xc6e00bf3U, 0xd5a79147U,
0x06ca6351U, 0x14292967U, 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U,
0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, 0xa2bfe8a1U, 0xa81a664bU,
0xc24b8b70U, 0xc76c51a3U, 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U,
0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU,
0x5b9cca4fU, 0x682e6ff3U, 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U,
0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U,
]
///|
struct Sha256 {
state : FixedArray[UInt32]
block : FixedArray[Byte]
mut buf_len : Int32
mut total_len : UInt64
}
///|
fn rotr(x : UInt32, n : Int32) -> UInt32 {
(x >> n) | (x << (32 - n))
}
///|
fn Sha256::new() -> Sha256 {
{
state: [
0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, 0x510e527fU, 0x9b05688cU,
0x1f83d9abU, 0x5be0cd19U,
],
block: FixedArray::make(64, b'\x00'),
buf_len: 0,
total_len: 0UL,
}
}
///|
fn Sha256::compress(self : Sha256) -> Unit {
let w = FixedArray::make(64, 0U)
for i = 0; i < 16; i = i + 1 {
let j = i * 4
w[i] = (self.block[j].to_uint() << 24) |
(self.block[j + 1].to_uint() << 16) |
(self.block[j + 2].to_uint() << 8) |
self.block[j + 3].to_uint()
}
for i = 16; i < 64; i = i + 1 {
let x = w[i - 15]
let y = w[i - 2]
let s0 = rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3)
let s1 = rotr(y, 17) ^ rotr(y, 19) ^ (y >> 10)
w[i] = w[i - 16] + s0 + w[i - 7] + s1
}
let mut a = self.state[0]
let mut b = self.state[1]
let mut c = self.state[2]
let mut d = self.state[3]
let mut e = self.state[4]
let mut f = self.state[5]
let mut g = self.state[6]
let mut h = self.state[7]
for i = 0; i < 64; i = i + 1 {
let s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)
let ch = (e & f) ^ ((e ^ 0xFFFFFFFFU) & g)
let temp1 = h + s1 + ch + sha256_k[i] + w[i]
let s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)
let maj = (a & b) ^ (a & c) ^ (b & c)
let temp2 = s0 + maj
h = g
g = f
f = e
e = d + temp1
d = c
c = b
b = a
a = temp1 + temp2
}
self.state[0] = self.state[0] + a
self.state[1] = self.state[1] + b
self.state[2] = self.state[2] + c
self.state[3] = self.state[3] + d
self.state[4] = self.state[4] + e
self.state[5] = self.state[5] + f
self.state[6] = self.state[6] + g
self.state[7] = self.state[7] + h
}
///|
fn Sha256::push_byte(self : Sha256, byte : Byte) -> Unit {
self.block[self.buf_len] = byte
self.buf_len = self.buf_len + 1
self.total_len = self.total_len + 1UL
if self.buf_len == 64 {
self.compress()
self.buf_len = 0
}
}
///|
fn Sha256::update_bytes(self : Sha256, data : Bytes) -> Unit {
for i = 0; i < data.length(); i = i + 1 {
self.push_byte(data[i])
}
}
///|
fn Sha256::update_fixed(
self : Sha256,
data : FixedArray[Byte],
len : Int32,
) -> Unit {
for i = 0; i < len; i = i + 1 {
self.push_byte(data[i])
}
}
///|
fn Sha256::finish_hex(self : Sha256) -> String {
let bit_len = self.total_len * 8UL
self.block[self.buf_len] = b'\x80'
self.buf_len = self.buf_len + 1
if self.buf_len > 56 {
while self.buf_len < 64 {
self.block[self.buf_len] = b'\x00'
self.buf_len = self.buf_len + 1
}
self.compress()
self.buf_len = 0
}
while self.buf_len < 56 {
self.block[self.buf_len] = b'\x00'
self.buf_len = self.buf_len + 1
}
let len_bytes = bit_len.to_be_bytes()
for i = 0; i < 8; i = i + 1 {
self.block[56 + i] = len_bytes[i]
}
self.compress()
self.buf_len = 0
let digest = FixedArray::make(32, b'\x00')
for i = 0; i < 8; i = i + 1 {
let w = self.state[i]
let j = i * 4
digest[j] = (w >> 24).to_byte()
digest[j + 1] = (w >> 16).to_byte()
digest[j + 2] = (w >> 8).to_byte()
digest[j + 3] = w.to_byte()
}
@hex.encode(Bytes::makei(32, fn(i) { digest[i] })[:])
}
///|
fn sha256_digest(data : Bytes) -> String {
let h = Sha256::new()
h.update_bytes(data)
"sha256:" + h.finish_hex()
}
///|
async fn sha256_file(path : String) -> (String, Int64) raise OrbitError {
let file = @fs.open(path, mode=ReadOnly) catch {
e => raise OrbitError("cannot read \{path}: \{e}")
}
defer file.close()
let h = Sha256::new()
let buf = FixedArray::make(32768, b'\x00')
let mut total = 0L
for ;; {
let n = file.read(buf) catch {
e => raise OrbitError("cannot read \{path}: \{e}")
}
if n == 0 {
break
}
h.update_fixed(buf, n)
total = total + n.to_int64()
}
("sha256:" + h.finish_hex(), total)
}
///|
test "sha256 FIPS 180-4 vectors" {
assert_eq(
sha256_digest(b""),
"sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
)
assert_eq(
sha256_digest(b"abc"),
"sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
)
let msg56 = b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
assert_eq(
sha256_digest(msg56),
"sha256:248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
)
}
///|
test "sha256 chunked updates match single-shot across block boundaries" {
let payload = FixedArray::make(135, b'\x00')
for i = 0; i < payload.length(); i = i + 1 {
payload[i] = ((i * 31 + 7) & 0xFF).to_byte()
}
let full = Bytes::makei(payload.length(), fn(i) { payload[i] })
let expected = sha256_digest(full)
let h = Sha256::new()
let mut offset = 0
let chunk_sizes = [1, 7, 47, 1, 8, 64, 7]
for sz in chunk_sizes {
let part = FixedArray::make(sz, b'\x00')
for i = 0; i < sz; i = i + 1 {
part[i] = payload[offset + i]
}
h.update_fixed(part, sz)
offset = offset + sz
}
assert_eq(offset, payload.length())
assert_eq("sha256:" + h.finish_hex(), expected)
}
+1526
View File
File diff suppressed because it is too large. Load diff
+43 -86
View File
@@ -1,17 +1,12 @@
// Native glue for orbit: process execution, file IO and environment access.
// Every string crosses the boundary as UTF-8 `Bytes` (not NUL-terminated).
// Arguments are never decref'd here: if the compiler passes them owned we leak
// a few bytes in a short-lived CLI, which is harmless; if it passes them
// borrowed, decref'ing would be a use-after-free.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <time.h>
#include <termios.h>
#include "moonbit.h"
static int last_status = 0;
static char *to_cstr(moonbit_bytes_t b) {
int32_t n = Moonbit_array_length(b);
char *s = (char *)malloc((size_t)n + 1);
@@ -27,84 +22,6 @@ static moonbit_bytes_t from_buf(const char *buf, size_t len) {
return out;
}
static int decode_status(int r) {
if (r == -1) return -1;
if (WIFEXITED(r)) return WEXITSTATUS(r);
return 128;
}
int32_t orbit_run(moonbit_bytes_t cmd) {
char *c = to_cstr(cmd);
fflush(stdout);
int r = system(c);
free(c);
return decode_status(r);
}
moonbit_bytes_t orbit_capture(moonbit_bytes_t cmd) {
char *c = to_cstr(cmd);
fflush(stdout);
FILE *p = popen(c, "r");
free(c);
if (!p) {
last_status = -1;
return from_buf("", 0);
}
size_t cap = 4096, len = 0;
char *buf = (char *)malloc(cap);
size_t got;
while ((got = fread(buf + len, 1, cap - len, p)) > 0) {
len += got;
if (len == cap) {
cap *= 2;
buf = (char *)realloc(buf, cap);
if (!buf) abort();
}
}
last_status = decode_status(pclose(p));
moonbit_bytes_t out = from_buf(buf, len);
free(buf);
return out;
}
int32_t orbit_last_status(void) { return last_status; }
moonbit_bytes_t orbit_read_file(moonbit_bytes_t path) {
char *p = to_cstr(path);
FILE *f = fopen(p, "rb");
free(p);
if (!f) {
last_status = -1;
return from_buf("", 0);
}
size_t cap = 4096, len = 0, got;
char *buf = (char *)malloc(cap);
while ((got = fread(buf + len, 1, cap - len, f)) > 0) {
len += got;
if (len == cap) {
cap *= 2;
buf = (char *)realloc(buf, cap);
if (!buf) abort();
}
}
fclose(f);
last_status = 0;
moonbit_bytes_t out = from_buf(buf, len);
free(buf);
return out;
}
int32_t orbit_write_file(moonbit_bytes_t path, moonbit_bytes_t data) {
char *p = to_cstr(path);
FILE *f = fopen(p, "wb");
free(p);
if (!f) return -1;
int32_t n = Moonbit_array_length(data);
size_t w = fwrite(data, 1, (size_t)n, f);
int rc = fclose(f);
return (w == (size_t)n && rc == 0) ? 0 : -1;
}
moonbit_bytes_t orbit_getenv(moonbit_bytes_t name) {
char *n = to_cstr(name);
const char *v = getenv(n);
@@ -117,3 +34,43 @@ void orbit_exit(int32_t code) {
fflush(stdout);
exit(code);
}
int32_t orbit_symlink(moonbit_bytes_t target, moonbit_bytes_t linkpath) {
char *t = to_cstr(target);
char *l = to_cstr(linkpath);
unlink(l);
int rc = symlink(t, l);
free(t);
free(l);
return rc;
}
void orbit_print_err(moonbit_bytes_t msg) {
char *m = to_cstr(msg);
fputs(m, stderr);
fflush(stderr);
free(m);
}
moonbit_bytes_t orbit_utc_now(void) {
time_t t = time(NULL);
struct tm tm_utc;
if (!gmtime_r(&t, &tm_utc)) {
return from_buf("1970-01-01T00:00:00Z", 20);
}
char buf[32];
size_t n = strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", &tm_utc);
return from_buf(buf, n);
}
int32_t orbit_set_echo(int32_t enable) {
if (!isatty(0)) return -1;
struct termios t;
if (tcgetattr(0, &t) != 0) return -1;
if (enable) {
t.c_lflag |= (tcflag_t)ECHO;
} else {
t.c_lflag &= ~(tcflag_t)ECHO;
}
return tcsetattr(0, TCSANOW, &t);
}
+135 -60
View File
@@ -1,31 +1,10 @@
// System access through the C stub, plus small string helpers.
// Helpers are written against `for c in s` only, to stay independent of
// String APIs that have changed between MoonBit releases.
// System access through process execution, MoonBit async fs/process, and small helpers.
///|
suberror OrbitError {
OrbitError(String)
}
///|
#borrow(cmd)
extern "C" fn c_run(cmd : Bytes) -> Int32 = "orbit_run"
///|
#borrow(cmd)
extern "C" fn c_capture(cmd : Bytes) -> Bytes = "orbit_capture"
///|
extern "C" fn c_last_status() -> Int32 = "orbit_last_status"
///|
#borrow(path)
extern "C" fn c_read_file(path : Bytes) -> Bytes = "orbit_read_file"
///|
#borrow(path, data)
extern "C" fn c_write_file(path : Bytes, data : Bytes) -> Int32 = "orbit_write_file"
///|
#borrow(name)
extern "C" fn c_getenv(name : Bytes) -> Bytes = "orbit_getenv"
@@ -33,6 +12,23 @@ extern "C" fn c_getenv(name : Bytes) -> Bytes = "orbit_getenv"
///|
extern "C" fn c_exit(code : Int32) = "orbit_exit"
///|
extern "C" fn c_isatty(fd : Int32) -> Int32 = "isatty"
///|
#borrow(msg)
extern "C" fn c_print_err(msg : Bytes) -> Unit = "orbit_print_err"
///|
#borrow(target, linkpath)
extern "C" fn c_symlink(target : Bytes, linkpath : Bytes) -> Int32 = "orbit_symlink"
///|
extern "C" fn c_utc_now() -> Bytes = "orbit_utc_now"
///|
extern "C" fn c_set_echo(enable : Int32) -> Int32 = "orbit_set_echo"
// ---------------------------------------------------------------- UTF-8
///|
@@ -219,19 +215,6 @@ fn trim(s : String) -> String {
slice(a, start, end)
}
///|
/// Non-empty, trimmed lines.
fn lines(s : String) -> Array[String] {
let out : Array[String] = []
for l in split_on(s, '\n') {
let t = trim(l)
if t != "" {
out.push(t)
}
}
out
}
///|
fn join(xs : Array[String], sep : String) -> String {
let sb = StringBuilder()
@@ -266,15 +249,19 @@ fn sq(s : String) -> String {
sb.to_string()
}
// ---------------------------------------------------------------- process / fs
// ---------------------------------------------------------------- process / fs (async)
///|
fn sh(cmd : String) -> Int32 {
c_run(utf8_encode(cmd))
async fn sh(cmd : String) -> Int32 noraise {
try {
@process.run("sh", ["-c", cmd])
} catch {
_ => 128
}
}
///|
fn sh_ok(cmd : String) -> Unit raise OrbitError {
async fn sh_ok(cmd : String) -> Unit raise OrbitError {
let code = sh(cmd)
if code != 0 {
raise OrbitError("command failed (exit \{code}): \{cmd}")
@@ -282,39 +269,46 @@ fn sh_ok(cmd : String) -> Unit raise OrbitError {
}
///|
/// Run a command and return its stdout; stderr goes to the terminal.
fn capture(cmd : String) -> String raise OrbitError {
let out = utf8_decode(c_capture(utf8_encode(cmd)))
let code = c_last_status()
if code != 0 {
raise OrbitError("command failed (exit \{code}): \{cmd}")
/// Braille spinner on stderr until cancelled.
async fn spin(label : String) -> Unit noraise {
let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
let mut i = 0
while true {
c_print_err(utf8_encode("\r\u001B[2K" + frames[i % 10] + " " + label))
i = i + 1
@async.sleep(80)
}
out
}
///|
fn exists(path : String) -> Bool {
sh("test -e " + sq(path)) == 0
async fn exists(path : String) -> Bool noraise {
try {
@fs.exists(path)
} catch {
_ => false
}
}
///|
fn read_text(path : String) -> String? {
let b = c_read_file(utf8_encode(path))
if c_last_status() != 0 {
None
} else {
Some(utf8_decode(b))
async fn read_text(path : String) -> String? noraise {
try {
let data = @fs.read_file(path)
Some(data.text())
} catch {
_ => None
}
}
///|
/// Write via a temp file and rename, so readers never see a half-written file.
fn write_text_atomic(path : String, text : String) -> Unit raise OrbitError {
async fn write_text_atomic(path : String, text : String) -> Unit raise OrbitError {
let tmp = path + ".tmp"
if c_write_file(utf8_encode(tmp), utf8_encode(text)) != 0 {
raise OrbitError("cannot write \{tmp}")
try {
@fs.write_file(tmp, text, create_mode=CreateOrTruncate)
@fs.rename(tmp, path)
} catch {
e => raise OrbitError("cannot write " + path + ": " + e.to_string())
}
sh_ok("mv -f " + sq(tmp) + " " + sq(path))
}
///|
@@ -322,10 +316,91 @@ fn getenv(name : String) -> String {
utf8_decode(c_getenv(utf8_encode(name)))
}
///|
fn utc_now() -> String {
utf8_decode(c_utc_now())
}
///|
async fn[T] with_spinner(
label : String,
f : async () -> T,
) -> T raise OrbitError {
let is_tty = c_isatty(2) != 0 && getenv("TERM") != "dumb"
if !is_tty || label == "" {
try f() catch {
OrbitError(msg) => raise OrbitError(msg)
e => raise OrbitError(e.to_string())
}
} else {
let res : Result[T, Error] = try {
let out = @async.with_task_group(group => {
let spinner = group.spawn(() => {
ignore(@async.handle_cancellation(() => spin(label)))
})
defer {
spinner.cancel()
c_print_err(utf8_encode("\r\u001B[2K"))
}
f()
})
Ok(out)
} catch {
e => Err(e)
}
match res {
Ok(v) => v
Err(OrbitError(msg)) => raise OrbitError(msg)
Err(e) => raise OrbitError(e.to_string())
}
}
}
///|
async fn write_secret_atomic(
path : String,
text : String,
) -> Unit raise OrbitError {
let tmp = path + ".tmp"
try {
@fs.write_file(tmp, text, create_mode=CreateOrTruncate, permission=0o600)
@fs.chmod(tmp, 0o600)
@fs.rename(tmp, path)
} catch {
e => raise OrbitError("cannot write " + path + ": " + e.to_string())
}
}
///|
async fn run_with_stdin(
cmd : String,
args : Array[String],
stdin_text : String,
) -> (Int32, String) raise OrbitError {
try {
@async.with_task_group(group => {
let (stdin, writer) = @process.write_to_process()
let runner = group.spawn(() => @process.collect_output(cmd, args, stdin~))
group.spawn_bg(allow_failure=true, () => {
defer writer.close()
writer.write(utf8_encode(stdin_text))
})
let (code, stdout, _) = runner.wait()
(code, stdout.text())
})
} catch {
e => raise OrbitError(e.to_string())
}
}
///|
/// Command-line arguments without the program name (Linux: /proc/self/cmdline).
fn cli_args() -> Array[String] {
let raw = c_read_file(utf8_encode("/proc/self/cmdline"))
async fn cli_args() -> Array[String] noraise {
let raw = try {
@fs.read_file("/proc/self/cmdline").binary()
} catch {
_ => Default::default()
}
let out : Array[String] = []
let cur : Array[Byte] = []
for i = 0; i < raw.length(); i = i + 1 {