From 5284815ebc941d178cc3aef2f651b2d3ee239042 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:38:06 -0800 Subject: [PATCH 01/30] ci: Lint workflows with actionlint Run the shared actionlint action on pull requests that change a workflow, as the other SDK repositories do. Signed-off-by: Alexander Jung --- .github/workflows/actionlint.yaml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 .github/workflows/actionlint.yaml diff --git a/.github/workflows/actionlint.yaml b/.github/workflows/actionlint.yaml new file mode 100644 index 0000000..4bae324 --- /dev/null +++ b/.github/workflows/actionlint.yaml @@ -0,0 +1,24 @@ +name: actionlint + +on: + pull_request: + branches: + - prod-staging + paths: + - '.github/workflows/**' + + workflow_call: + +# Automatically cancel in-progress actions on the same branch +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request_target' && github.head_ref || github.ref }} + cancel-in-progress: true + +jobs: + actionlint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - name: Run actionlint + uses: unikraft-cloud/x/.github/actions/actionlint@prod-staging From d8e3056e3828c50a869705bc4e25ead7a88836f6 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:38:06 -0800 Subject: [PATCH 02/30] ci: Check pull requests Run the shared commit and title checks, RuboCop on one Ruby, the unit tests on Ruby 3.3, 3.4 and 4.0, and build and load the packaged gem on the oldest and the newest supported Ruby. Signed-off-by: Alexander Jung --- .github/workflows/check-pr.yaml | 92 +++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 .github/workflows/check-pr.yaml diff --git a/.github/workflows/check-pr.yaml b/.github/workflows/check-pr.yaml new file mode 100644 index 0000000..4755763 --- /dev/null +++ b/.github/workflows/check-pr.yaml @@ -0,0 +1,92 @@ +name: check/pr + +on: + pull_request: + types: + - opened + - synchronize + - reopened + - edited + branches: + - prod-staging + - prod-stable + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + pr: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - name: Run check-pr + uses: unikraft-cloud/x/.github/actions/check-pr@prod-staging + + # RuboCop's verdict does not depend on the interpreter running it, so lint + # runs on one Ruby only. + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: '4.0' + bundler-cache: true + + - name: Lint + run: bundle exec rake lint + + # The test suite covers every supported Ruby. + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + ruby-version: + - '3.3' + - '3.4' + - '4.0' + steps: + - uses: actions/checkout@v7 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby-version }} + bundler-cache: true + + - name: Test + run: bundle exec rake test + + # The packaged gem is checked on the oldest and the newest supported Ruby. + build: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + ruby-version: + - '3.3' + - '4.0' + steps: + - uses: actions/checkout@v7 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby-version }} + bundler-cache: true + + - name: Build + run: bundle exec rake build + + - name: Check the packaged gem + run: bundle exec rake check_package From 752271f9254ca5a3fe2f9bb472c89a34cb780b8e Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:38:06 -0800 Subject: [PATCH 03/30] ci: Publish the gem to RubyGems from the channel branches Derive the version with svu as js-sdk does. prod-stable publishes X.Y.Z and pushes the tag; prod-staging publishes X.Y.Z.pre.next.N, a RubyGems prerelease that sorts below X.Y.Z, since RubyGems has no dist-tags. The version is stamped into version.rb in the runner only, and the gem is pushed with RubyGems trusted publishing, so no API key is stored. Signed-off-by: Alexander Jung --- .github/workflows/release.yaml | 249 +++++++++++++++++++++++++++++++++ 1 file changed, 249 insertions(+) create mode 100644 .github/workflows/release.yaml diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 0000000..40ccfe2 --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,249 @@ +name: release + +# Publishes the gem to RubyGems. The branch selects the channel: +# prod-stable -> stable versions (0.2.0) +# prod-staging -> prerelease versions (0.2.1.pre.next.3) +# +# The version is never committed. lib/unikraft/cloud/version.rb carries a 0.0.0 +# placeholder, and svu derives the real version from the conventional-commit +# messages since the last release tag. The run stamps it into version.rb +# seconds before building the gem. +# +# svu speaks semver and prints 0.2.1-next.3. RubyGems has no dist-tags, so the +# version alone tells the channels apart: the run rewrites that to +# 0.2.1.pre.next.3, the canonical form Gem::Version itself gives the semver +# string. Any letter makes a RubyGems version a prerelease, which sorts below +# 0.2.1 and above 0.2.0, and the numeric counter segment sorts next.10 above +# next.9. `gem install unikraft-cloud` therefore never picks it up, and +# `gem install unikraft-cloud --pre` does. +# +# Only prod-stable pushes a tag, and both channels measure from that same tag, +# so a prerelease always sorts above the newest stable release. It needs no +# cross-branch coordination, because there is no committed version for the +# two branches to disagree about. +# +# Authentication uses RubyGems trusted publishing (OIDC): RubyGems exchanges +# the GitHub Actions ID token for a short-lived API key, so no long-lived +# RubyGems secret is involved. The trusted publisher registered on +# rubygems.org must name this repository and this workflow file +# (.github/workflows/release.yaml); renaming or moving this file breaks +# publishing until the RubyGems side is updated to match. Unlike npm, +# RubyGems accepts a *pending* trusted publisher for a gem that does not exist +# yet, so the first release needs no manual push: register this repository +# and this workflow file as a pending publisher of unikraft-cloud, then push. +on: + push: + branches: + - prod-stable + - prod-staging + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +permissions: + contents: write # required to push the release tag + id-token: write # required for trusted publishing + +env: + GEM_NAME: unikraft-cloud + SVU_VERSION: '3.2.3' + # sha256 of svu_${SVU_VERSION}_linux_amd64.tar.gz, from the release's checksums.txt. + SVU_SHA256: '2509db2b9a5d97a212efb8e242e5782a1a62459ac516b3663c525db6b8474c02' + +jobs: + release: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + + - name: Fetch all tags + run: git fetch --force --tags + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: '4.0' + bundler-cache: true + + - name: Install svu + run: | + curl -fsSL -o svu.tar.gz \ + "https://github.com/caarlos0/svu/releases/download/v${SVU_VERSION}/svu_${SVU_VERSION}_linux_amd64.tar.gz" + echo "${SVU_SHA256} svu.tar.gz" | sha256sum -c - + tar -xzf svu.tar.gz -C /usr/local/bin svu + rm svu.tar.gz + + - name: Resolve the version + id: version + env: + CHANNEL: ${{ github.ref_name }} + run: | + api=https://rubygems.org/api + base=$(svu current) + + # Tags are the only record of what has been released. If RubyGems + # holds a stable release that this repository has no tag for, svu + # starts again from zero and publishes below what is already out + # there, so stop instead. Prereleases alone carry no tag by design. + if ! git rev-parse -q --verify "refs/tags/$base" >/dev/null; then + status=$(curl -sSL -o "$RUNNER_TEMP/versions.json" -w '%{http_code}' \ + "$api/v1/versions/$GEM_NAME.json") || status=000 + case "$status" in + 404) ;; + 200) + if jq -e 'any(.[]; .prerelease | not)' "$RUNNER_TEMP/versions.json" >/dev/null; then + echo "::error::$GEM_NAME is published on RubyGems but this \ + repository has no release tag. Tag the commit behind the current \ + release, for example git tag v1.2.3 && git push origin v1.2.3, \ + then re-run." + exit 1 + fi + ;; + *) + echo "::error::Could not list $GEM_NAME versions on RubyGems (HTTP $status)." + exit 1 + ;; + esac + fi + + if [ "$CHANNEL" = prod-stable ]; then + channel=stable + # No --always here: a push carrying nothing bumpable (docs, CI, a + # refactor) must not burn a version number. svu then returns the + # current tag, the version is already on RubyGems, and the run + # skips. + tag=$(svu next --v0) + # An untagged repository with nothing bumpable resolves to the + # placeholder, which is no first version to release. + if [ "$tag" = v0.0.0 ]; then + echo "::error::No release tag and no feat or fix commit, so there \ + is no first version to release. Land one, or tag it by hand." + exit 1 + fi + else + channel=prerelease + # The prerelease counter is the commit distance from the last release + # tag. It rises on every staging push, and resets when a stable + # release moves the tag forward. An untagged repository has nothing + # to measure from, and the guard above has already proved it has + # published no stable release either. + if git rev-parse -q --verify "refs/tags/$base" >/dev/null; then + count=$(git rev-list --count "$base..HEAD") + else + count=$(git rev-list --count HEAD) + fi + # --always, unlike the stable path: staging must sit above the newest + # stable release even when only chores landed, or `--pre` would + # resolve below the stable release. + tag=$(svu next --always --v0 --prerelease "next.$count") + fi + + # v0.2.1-next.3 -> 0.2.1.pre.next.3, see the header. + version=${tag#v} + version=${version/-/.pre.} + { + echo "tag=$tag" + echo "version=$version" + echo "channel=$channel" + } >> "$GITHUB_OUTPUT" + echo "Resolved $GEM_NAME $version ($channel)" + + # Re-running a finished release, or a run whose tag push succeeded but + # whose publish did not, must not fail. Only a confirmed 404 means the + # version is absent; any other lookup failure stops the release rather + # than being read as "not published". + status=$(curl -sSL -o /dev/null -w '%{http_code}' \ + "$api/v2/rubygems/$GEM_NAME/versions/$version.json") || status=000 + case "$status" in + 200) + echo "publish=false" >> "$GITHUB_OUTPUT" + echo "::notice::$GEM_NAME $version is already published; skipping release." + ;; + 404) + echo "publish=true" >> "$GITHUB_OUTPUT" + ;; + *) + echo "::error::Could not look up $GEM_NAME $version on RubyGems (HTTP $status)." + exit 1 + ;; + esac + + - name: Test + if: steps.version.outputs.publish == 'true' + run: bundle exec rake test + + - name: Check the packaged gem + if: steps.version.outputs.publish == 'true' + run: bundle exec rake build check_package + + # Tagged before the publish, and only after the build and the tests pass, so + # that a failed publish can be retried by re-running the job: the tag step + # below is a no-op once the tag exists, and the lookup above proves the + # version is still absent from RubyGems. + - name: Tag the release + if: steps.version.outputs.publish == 'true' && github.ref_name == 'prod-stable' + env: + TAG: ${{ steps.version.outputs.tag }} + run: | + if git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then + # Publishing HEAD under a tag on another commit would ship code the + # tag does not hold: re-run the original tagged run instead. + if [ "$(git rev-list -n 1 "$TAG")" != "$(git rev-parse HEAD)" ]; then + echo "::error::tag $TAG exists on another commit; re-run its release instead." + exit 1 + fi + echo "::notice::tag $TAG already exists; not re-tagging." + exit 0 + fi + git config user.name "Unikraft Bot" + git config user.email "monkey@unikraft.io" + git tag -a "$TAG" -m "$TAG" + git push origin "$TAG" + + # Writes the resolved version into version.rb for the publish only. The + # commit keeps the 0.0.0 placeholder. The gem is built with plain + # `gem build` rather than through Bundler: the lockfile records the + # placeholder, and a frozen bundle refuses a path gem whose version moved. + - name: Build the release gem + if: steps.version.outputs.publish == 'true' + env: + VERSION: ${{ steps.version.outputs.version }} + run: | + file=lib/unikraft/cloud/version.rb + sed -i "s/VERSION = \"0\.0\.0\"/VERSION = \"$VERSION\"/" "$file" + grep -q "VERSION = \"$VERSION\"" "$file" || { + echo "::error::Could not stamp $VERSION into $file." + exit 1 + } + rm -rf pkg + mkdir pkg + gem build "$GEM_NAME.gemspec" --output "pkg/$GEM_NAME-$VERSION.gem" + + # Exchanges the OIDC token for a short-lived API key in GEM_HOST_API_KEY. + # The action has no moving major tag, so the version is exact. + - name: Configure RubyGems credentials + if: steps.version.outputs.publish == 'true' + uses: rubygems/configure-rubygems-credentials@v2.1.0 + + - name: Publish to RubyGems + if: steps.version.outputs.publish == 'true' + run: gem push pkg/*.gem + + # The version is no longer readable from the repository, so the run has to + # report what it shipped. + - name: Summary + env: + VERSION: ${{ steps.version.outputs.version }} + CHANNEL: ${{ steps.version.outputs.channel }} + PUBLISHED: ${{ steps.version.outputs.publish }} + run: | + { + if [ "$PUBLISHED" = true ]; then + echo "Published \`$GEM_NAME $VERSION\` ($CHANNEL) to RubyGems." + else + echo "\`$GEM_NAME $VERSION\` was already published; nothing to do." + fi + } >> "$GITHUB_STEP_SUMMARY" From 633623d61231def7f8d3cb454db8a782c54b3b0c Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:38:06 -0800 Subject: [PATCH 04/30] ci: Promote prod-staging with the shared workflow Signed-off-by: Alexander Jung --- .github/workflows/promote.yaml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .github/workflows/promote.yaml diff --git a/.github/workflows/promote.yaml b/.github/workflows/promote.yaml new file mode 100644 index 0000000..42e7bb0 --- /dev/null +++ b/.github/workflows/promote.yaml @@ -0,0 +1,15 @@ +name: promote + +on: + push: + branches: [prod-staging] + workflow_dispatch: + +permissions: + contents: read + +jobs: + promote: + uses: unikraft-cloud/x/.github/workflows/promote.yaml@prod-staging + secrets: + gh_pat: ${{ secrets.GH_PAT }} From 1750b92660a22fb4cb7a4893185fca411240f5fb Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:38:06 -0800 Subject: [PATCH 05/30] ci: Regenerate the plumbing client from the OpenAPI spec Run make generate for the chosen channel and open a signed-off pull request that touches lib/unikraft/cloud/api only. Signed-off-by: Alexander Jung --- .github/workflows/sync.yaml | 88 +++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 .github/workflows/sync.yaml diff --git a/.github/workflows/sync.yaml b/.github/workflows/sync.yaml new file mode 100644 index 0000000..5365fa0 --- /dev/null +++ b/.github/workflows/sync.yaml @@ -0,0 +1,88 @@ +name: sync + +on: + workflow_dispatch: + inputs: + channel: + description: The release channel (OpenAPI spec branch) to sync from. + required: true + default: prod-staging + type: choice + options: + - prod-stable + - prod-staging + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: write + pull-requests: write + +jobs: + sync: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + ref: ${{ inputs.channel }} + + # The generator, openapi-gen, is a Go program. + - name: Set up Go + uses: actions/setup-go@v7 + with: + go-version: stable + + # The Makefile formats the generated Ruby with the bundled tooling. + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: '4.0' + bundler-cache: true + + - name: Generate SDK from the OpenAPI spec + env: + CHANNEL: ${{ inputs.channel }} + run: make generate CHANNEL="$CHANNEL" + + - name: Show diff + run: git --no-pager diff --stat + + # The release workflow derives the version from the commit history, so a + # sync never touches version.rb. It only has to decide whether the + # regenerated client differs from what is already on the branch. + - name: Check for changes + id: check + run: | + if git diff --quiet -- lib/unikraft/cloud/api \ + && [ -z "$(git ls-files --others --exclude-standard -- lib/unikraft/cloud/api)" ]; then + echo "changed=false" >> "$GITHUB_OUTPUT" + echo "lib/unikraft/cloud/api unchanged; no pull request needed." + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + + - name: Create pull request + if: steps.check.outputs.changed == 'true' + uses: peter-evans/create-pull-request@v8 + with: + base: ${{ inputs.channel }} + branch: sync/${{ inputs.channel }} + # A GITHUB_TOKEN-made PR would not trigger check-pr.yaml. + token: ${{ secrets.GH_PAT }} + # feat, not chore: the release only publishes for a feat or fix. + commit-message: "feat: Update SDK from OpenAPI spec" + title: "feat: Update SDK from OpenAPI spec (${{ inputs.channel }})" + body: | + Automated regeneration of the plumbing client from the + `${{ inputs.channel }}` OpenAPI specification. + + Merging this pull request publishes a new version. The release + workflow derives the number from the commit history. + author: Unikraft Bot + committer: Unikraft Bot + signoff: true + add-paths: | + lib/unikraft/cloud/api From 654235dbb58839eee9c67efdb5ba78914e45de4b Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:38:51 -0800 Subject: [PATCH 06/30] docs: Add contributing guide Describe the plumbing and porcelain layers, the plugin transport contract, the make and rake tasks, regeneration, and the release channels, including the RubyGems prerelease spelling and trusted publishing. Signed-off-by: Alexander Jung --- CONTRIBUTING.md | 239 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..2056e63 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,239 @@ +# Contributing to `unikraft-cloud` + +Thanks for your interest in improving the Unikraft Cloud Ruby SDK! + +## Architecture + +The SDK is deliberately split into two layers: + +``` +lib/ + unikraft/ + cloud.rb # entry point: Unikraft::Cloud.new and the public requires + cloud/ + version.rb # VERSION = "0.0.0" placeholder, stamped by the release + api/ # the "plumbing" layer: raw, spec-shaped + platform/ # GENERATED (*.gen.rb): one class per tag + models + controlplane/ # GENERATED (*.gen.rb) + *.rb # hand-written API::Platform / API::ControlPlane containers + core/ # hand-written shared machinery: transport, errors, + # metros, fan-out, pagination, models + resources/ # the "porcelain" layer: hand-written idiomatic clients +templates/ # Go templates consumed by openapi-gen to produce *.gen.rb +test/ # minitest suites +``` + +Everything matching `lib/unikraft/cloud/api/**/*.gen.rb` is generated from the +[OpenAPI specification][openapi] and **must not be edited by hand**: changes +would be lost on the next regeneration. To change generated output, edit the +templates in `templates/` (or the generator itself, see below). The +hand-written container files beside the generated ones are safe to edit. + +The two layers are kept apart deliberately: + +- **Plumbing** (`lib/unikraft/cloud/api/**`) mirrors the specification: + `Unikraft::Cloud::API::Platform` and `Unikraft::Cloud::API::ControlPlane` + hold one class per tag (`API::Platform::InstancesApi`, ...), whose methods + are the snake_cased `operationId`s (`get_instances`), take keyword + arguments, and return the response envelope untouched. One plumbing client + talks to one metro. +- **Porcelain** (`lib/unikraft/cloud/resources/**`) **holds** a plumbing + client rather than inheriting from one, so its surface stays small and + deliberate: short verbs, unwrapped results, auto-pagination, metro fan-out, + chainable handles. + +Because the layers are composed rather than inherited, a newly generated +operation does **not** appear on the idiomatic client automatically. It is +reachable through the plumbing client until someone wraps it. Wrap only where +it improves the developer experience. + +When adding a porcelain method, keep the metro rules of the resource base +class in `lib/unikraft/cloud/core/`. Reads fan out across the scope and tag +results with `metro` (`Model#with_metro`). A name only identifies a resource +*within* a metro, so a ref may match in several: an operation that acts on one +resource raises `Unikraft::Cloud::AmbiguousRefError`, with the matches +attached, rather than guessing; an operation that acts on all of them works +on every match; creation picks exactly one endpoint. A fan-out that fails in +some metros raises `Unikraft::Cloud::MetroFanoutError` carrying both the +failures and the partial results. `metro` says where to send a request and +must never reach the wire inside a body. + +### The transport contract + +The generated plugin gems, `unikraft-cloud-plugin--api` (required as +`unikraft/cloud/plugin//api`, namespace +`Unikraft::Cloud::Plugin::::API`), are produced by the Ruby generator +in [plugin-sdk] at `ruby/tools/sdkgen`. They take a transport in their +constructor: any object that responds to + +- `request(method:, path:, query: nil, body: nil, headers: nil, **options)`, + returning the parsed JSON, +- `bytes(...)`, returning the body as a binary `String`, and +- `stream(...) { |chunk| ... }`, yielding the body in chunks. + +The contract is duck-typed, so a plugin gem needs no dependency on the SDK. +The porcelain hands each plugin client a `Unikraft::Cloud::Core::ApiClient`, +which satisfies it, and the test suite checks that against the published +plugin gem. Two rules follow: + +- Widening is safe. A new optional keyword or a wider accepted input is a + `fix:` or a `feat:`. +- A rename, a new required keyword, or a changed return type is a `feat!:`. + It needs the same change in the plugin-sdk generator and a republish of + every plugin gem in the same cycle. + +`ApiClient` must not rely on a keyword the contract does not declare. Ruby +checks none of this ahead of time, so only the tests can see that drift. + +## Prerequisites + +- Ruby 3.3+ (CI covers 3.3, 3.4 and 4.0) +- Go (only needed to regenerate `lib/unikraft/cloud/api`) + +```sh +bundle install +``` + +## Common tasks + +```sh +make generate # regenerate lib/unikraft/cloud/api (default channel: prod-staging) +make build # build the gem into pkg/ +make lint # rubocop +make test # minitest unit tests +make clean # remove build output + +bundle exec rake test # unit tests +bundle exec rake test:e2e # end-to-end tests against the live API (needs UKC_TOKEN) +bundle exec rake lint # rubocop +bundle exec rake build # gem build into pkg/ +bundle exec rake check_package # install the built gem into a temporary GEM_HOME and require it +``` + +## Regenerating the client + +```sh +make generate # prod-staging channel +make generate CHANNEL=prod-stable # stable channel +``` + +`make generate` runs [`openapi-gen`][openapi-gen] against the channel's +`platform.json` and `controlplane.json`, writing Ruby into +`lib/unikraft/cloud/api/platform` and `lib/unikraft/cloud/api/controlplane` +respectively. The spec-independent HTTP transport is the hand-written +`Unikraft::Cloud::Core::ApiClient`, shared by both. + +> [!NOTE] +> Some read operations still model their filters as a request body on a +> `GET` in the spec. The transport refuses to attach a body to `GET` or +> `HEAD`, so the generated methods for those operations send only their query +> parameters; the spec exposes the same filters as repeatable query +> parameters. If a new `GET` operation ever ships body-only filters with no +> query equivalent, it needs a spec fix rather than a template workaround. + +To use a locally built generator, point `OPENAPI_GEN` at the binary: + +```sh +(cd ../x/tools/openapi-gen && go build -o /tmp/openapi-gen .) +make generate OPENAPI_GEN=/tmp/openapi-gen +``` + +Commit the regenerated `lib/unikraft/cloud/api` together with the change that +motivated it. The `sync` workflow does the same from CI and opens a pull +request touching only that directory. + +## Release channels + +There are two channels, mirroring the OpenAPI spec branches: + +| Channel | OpenAPI branch | RubyGems release | Version shape | +| -------------- | -------------- | ---------------- | ------------------ | +| `prod-stable` | `prod-stable` | stable | `0.2.0` | +| `prod-staging` | `prod-staging` | prerelease | `0.2.1.pre.next.3` | + +Pushing to a channel branch publishes the gem (see +`.github/workflows/release.yaml`). RubyGems has no dist-tags, so the version +alone tells the channels apart. Any letter in a RubyGems version makes it a +prerelease, which sorts below the matching release, so +`gem install unikraft-cloud` gets the newest stable release and + +```sh +gem install unikraft-cloud --pre +``` + +gets the newest prerelease. Bundler resolves a prerelease only when the +Gemfile requirement names one. + +The prerelease spelling is the one RubyGems itself derives from the semver +string svu prints: `Gem::Version.new("0.2.1-next.3")` is `0.2.1.pre.next.3`. +It sorts above `0.2.0` and below `0.2.1`, and the counter compares +numerically, so `next.10` sorts above `next.9`. + +Publishing uses [RubyGems trusted publishing][rubygems-tp]: the workflow +exchanges its GitHub Actions OIDC token for a short-lived API key, so there +is no RubyGems secret to rotate. The trusted publisher is registered on +rubygems.org against this repository and the `release.yaml` workflow file: +renaming or moving that file breaks publishing until the RubyGems-side +configuration is updated to match. RubyGems accepts a *pending* trusted +publisher for a gem that does not exist yet, so the very first release needs +no manual `gem push`: register the pending publisher for `unikraft-cloud`, +then push to a channel branch. + +[rubygems-tp]: https://guides.rubygems.org/trusted-publishing/ + +### Versioning + +`lib/unikraft/cloud/version.rb` holds the placeholder `0.0.0` on every +branch. Leave it there. The release workflow computes the real number with +[svu][svu] and writes it in the runner, seconds before building the gem. + +That makes the commit message the input to the version: a `fix:` gives a +patch, a `feat:` a minor, and a `!` a minor for as long as the major is 0. The +largest bump in the range wins, so two fixes and a feature give one minor +bump. A range of only `chore:` commits publishes nothing from `prod-stable`. + +Git tags are the record of what shipped. Only `prod-stable` pushes them, after +the tests pass. + +### Promote `prod-staging` to `prod-stable` + +`prod-stable` receives code only through a promotion pull request, which +carries no commit of its own: + +```sh +git fetch origin +git switch -c promote/ origin/prod-stable +git merge origin/prod-staging +git push -u origin promote/ +gh pr create --base prod-stable --fill +``` + +Cut the branch from `prod-stable`. A branch cut from `prod-staging` makes the +pull request show every commit that stable has not seen, which is +unreviewable. + +Two outcomes look like failures and are not. A promotion carrying nothing +bumpable publishes nothing. And between a release and the next push to +`prod-staging`, the newest prerelease sits one notch below the newest stable +release, because both point at the same code. + +## Code style + +- Formatting and linting are enforced by [RuboCop](https://rubocop.org) + (`bundle exec rake lint`). Run `bundle exec rubocop -a` to fix. +- Keep runtime dependencies at zero: rely on the standard library + (`net/http`, `json`, `uri`, ...). The one exception is the generated plugin + plumbing gems (`unikraft-cloud-plugin--api`), which the porcelain + wraps. +- Add a test in `test/` for new idiomatic behaviour. + +## Commit messages + +This repository uses [Conventional Commits][cc]; pull requests targeting +`prod-staging` are validated in CI. Sign off every commit (`git commit -s`). + +[openapi]: https://github.com/unikraft-cloud/openapi +[plugin-sdk]: https://github.com/unikraft-cloud/plugin-sdk +[openapi-gen]: https://github.com/unikraft-cloud/x/tree/prod-staging/tools/openapi-gen +[cc]: https://www.conventionalcommits.org +[svu]: https://github.com/caarlos0/svu From 1b23a81e6414609db7f1550a1eb827294ddfaa9b Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:39:41 -0800 Subject: [PATCH 07/30] chore: Scaffold the unikraft-cloud gem Add the gemspec, Gemfile, Rakefile (test, test:e2e, lint, build, check_package), a Makefile mirroring the JS SDK's, RuboCop config, the version placeholder and the licence. Signed-off-by: Alexander Jung --- .editorconfig | 15 ++++++++ .gitignore | 22 ++++++++++++ .rubocop.yml | 59 ++++++++++++++++++++++++++++++ Gemfile | 13 +++++++ Gemfile.lock | 67 +++++++++++++++++++++++++++++++++++ LICENSE.md | 28 +++++++++++++++ Makefile | 62 ++++++++++++++++++++++++++++++++ Rakefile | 43 ++++++++++++++++++++++ lib/unikraft/cloud.rb | 6 ++++ lib/unikraft/cloud/version.rb | 11 ++++++ test/test_helper.rb | 5 +++ test/unit/version_test.rb | 9 +++++ unikraft-cloud.gemspec | 26 ++++++++++++++ 13 files changed, 366 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitignore create mode 100644 .rubocop.yml create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 LICENSE.md create mode 100644 Makefile create mode 100644 Rakefile create mode 100644 lib/unikraft/cloud.rb create mode 100644 lib/unikraft/cloud/version.rb create mode 100644 test/test_helper.rb create mode 100644 test/unit/version_test.rb create mode 100644 unikraft-cloud.gemspec diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..9c9b78b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 2 + +[Makefile] +indent_style = tab + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..733fd98 --- /dev/null +++ b/.gitignore @@ -0,0 +1,22 @@ +# Bundler +/.bundle/ +/vendor/bundle/ + +# Build output +/pkg/ +/coverage/ +/doc/ +/.yardoc/ + +# Scratch +/.tmp/ + +# Editor / OS +.DS_Store +.idea/ +.vscode/* + +# Env +.env +.env.* +!.env.example diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..2f4051d --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,59 @@ +plugins: + - rubocop-minitest + - rubocop-rake + +AllCops: + TargetRubyVersion: 3.3 + NewCops: enable + SuggestExtensions: false + Exclude: + - "pkg/**/*" + - "vendor/**/*" + +Style/StringLiterals: + EnforcedStyle: double_quotes + +Style/StringLiteralsInInterpolation: + EnforcedStyle: double_quotes + +Layout/LineLength: + Max: 100 + +Style/Documentation: + Exclude: + - "test/**/*" + +# Transport and polling code reads best as one method per request phase; +# the defaults would split it into helpers that are used exactly once. +Metrics/MethodLength: + Max: 30 + Exclude: + - "test/**/*" + +Metrics/AbcSize: + Max: 30 + Exclude: + - "test/**/*" + +Metrics/CyclomaticComplexity: + Max: 12 + +Metrics/PerceivedComplexity: + Max: 12 + +Metrics/ClassLength: + Max: 200 + Exclude: + - "test/**/*" + +Metrics/BlockLength: + Exclude: + - "Rakefile" + - "test/**/*" + +# Keyword arguments mirror the error and request fields one to one. +Metrics/ParameterLists: + CountKeywordArgs: false + +Minitest/MultipleAssertions: + Max: 8 diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..fcdcc78 --- /dev/null +++ b/Gemfile @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +gemspec + +group :development do + gem "minitest", "~> 6.0" + gem "rake", "~> 13.4" + gem "rubocop", "~> 1.92", require: false + gem "rubocop-minitest", "~> 0.41", require: false + gem "rubocop-rake", "~> 0.7", require: false +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..1bc4f4c --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,67 @@ +PATH + remote: . + specs: + unikraft-cloud (0.0.0) + +GEM + remote: https://rubygems.org/ + specs: + ast (2.4.3) + drb (2.2.3) + json (3.1.0) + language_server-protocol (3.17.0.6) + lint_roller (1.1.0) + minitest (6.0.6) + drb (~> 2.0) + prism (~> 1.5) + parallel (2.3.0) + parser (3.3.13.0) + ast (~> 2.4.1) + racc + prism (1.9.0) + racc (1.8.1) + rainbow (3.1.1) + rake (13.4.2) + regexp_parser (2.13.1) + rubocop (1.92.2) + json (>= 2.3) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.1.0) + parallel (>= 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.11.3, < 3.0) + rubocop-ast (>= 1.49.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.50.0) + parser (>= 3.3.7.2) + prism (~> 1.7) + rubocop-minitest (0.41.0) + lint_roller (~> 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.38.0, < 2.0) + rubocop-rake (0.7.1) + lint_roller (~> 1.1) + rubocop (>= 1.72.1) + ruby-progressbar (1.13.0) + unicode-display_width (3.3.0) + unicode-emoji (~> 4.3) + unicode-emoji (4.3.0) + +PLATFORMS + aarch64-linux + arm64-darwin-24 + ruby + x86_64-linux + +DEPENDENCIES + minitest (~> 6.0) + rake (~> 13.4) + rubocop (~> 1.92) + rubocop-minitest (~> 0.41) + rubocop-rake (~> 0.7) + unikraft-cloud! + +BUNDLED WITH + 2.6.3 diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..80cab90 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,28 @@ +BSD 3-Clause License + +Copyright (c) 2026, Unikraft GmbH. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..460133c --- /dev/null +++ b/Makefile @@ -0,0 +1,62 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +# Release channel to generate against (maps to a branch of the openapi repo). +CHANNEL ?= prod-staging +SPEC_BASE ?= https://raw.githubusercontent.com/unikraft-cloud/openapi/refs/heads/$(CHANNEL) +PLATFORM_SPEC ?= $(SPEC_BASE)/platform.json +CONTROLPLANE_SPEC ?= $(SPEC_BASE)/controlplane.json + +GO ?= go +BUNDLE ?= bundle +OPENAPI_GEN ?= $(GO) run unikraft.com/x/tools/openapi-gen@latest + +TEMPLATES ?= ./templates +OUTPUT ?= ./lib/unikraft/cloud/api + +.PHONY: all +all: generate build + +# TypeSpec namespaces its schemas (`Instances.Instance`), which is not a legal +# Ruby constant; --namespace-flatten=strip restores the bare names. +.PHONY: generate +generate: ## Regenerate the platform and control-plane plumbing clients. + rm -f $(OUTPUT)/platform/*.gen.rb + $(OPENAPI_GEN) \ + -i $(PLATFORM_SPEC) \ + -o $(OUTPUT)/platform \ + -t $(TEMPLATES) \ + -v module=Platform \ + --namespace-flatten=strip + rm -f $(OUTPUT)/controlplane/*.gen.rb + $(OPENAPI_GEN) \ + -i $(CONTROLPLANE_SPEC) \ + -o $(OUTPUT)/controlplane \ + -t $(TEMPLATES) \ + -v module=ControlPlane \ + --namespace-flatten=strip + +.PHONY: build +build: ## Build the gem into pkg/. + $(BUNDLE) exec rake build + +.PHONY: check-package +check-package: ## Install the built gem into a temporary GEM_HOME and load it. + $(BUNDLE) exec rake check_package + +.PHONY: lint +lint: ## Lint and format-check with RuboCop. + $(BUNDLE) exec rake lint + +.PHONY: test +test: ## Run the unit test suite. + $(BUNDLE) exec rake test + +.PHONY: clean +clean: ## Remove build output. + rm -rf pkg + +.PHONY: help +help: ## Show this help. + @grep -hE '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) \ + | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-14s\033[0m %s\n", $$1, $$2}' diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..c5589da --- /dev/null +++ b/Rakefile @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require "bundler/gem_tasks" +require "minitest/test_task" +require "rubocop/rake_task" +require "rbconfig" +require "tmpdir" + +Minitest::TestTask.create(:test) do |t| + t.test_globs = ["test/unit/**/*_test.rb"] +end + +namespace :test do + Minitest::TestTask.create(:e2e_run) do |t| + t.test_globs = ["test/e2e/**/*_test.rb"] + end + + desc "Run the end-to-end tests against a live account (needs UKC_TOKEN)" + task :e2e do + abort "test:e2e needs UKC_TOKEN in the environment" if ENV.fetch("UKC_TOKEN", "").empty? + Rake::Task["test:e2e_run"].invoke + end +end + +RuboCop::RakeTask.new(:lint) + +desc "Install the built gem into a temporary GEM_HOME and require it" +task check_package: :build do + gem = Dir["pkg/unikraft-cloud-*.gem"].max_by { |f| File.mtime(f) } + Dir.mktmpdir do |home| + env = { "GEM_HOME" => home, "GEM_PATH" => home } + Bundler.with_unbundled_env do + sh env, "gem", "install", "--local", "--no-document", gem + sh env, RbConfig.ruby, "-e", + 'require "unikraft/cloud"; puts "unikraft-cloud " + Unikraft::Cloud::VERSION' + end + end +end + +task default: %i[lint test] diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb new file mode 100644 index 0000000..8b4b70b --- /dev/null +++ b/lib/unikraft/cloud.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "cloud/version" diff --git a/lib/unikraft/cloud/version.rb b/lib/unikraft/cloud/version.rb new file mode 100644 index 0000000..56149df --- /dev/null +++ b/lib/unikraft/cloud/version.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +module Unikraft + module Cloud + # Placeholder: the release workflow stamps the real version. + VERSION = "0.0.0" + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 0000000..5663d72 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +$LOAD_PATH.unshift File.expand_path("../lib", __dir__) +require "unikraft/cloud" +require "minitest/autorun" diff --git a/test/unit/version_test.rb b/test/unit/version_test.rb new file mode 100644 index 0000000..df0ec88 --- /dev/null +++ b/test/unit/version_test.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +require_relative "../test_helper" + +class VersionTest < Minitest::Test + def test_version_is_a_semver_string + assert_match(/\A\d+\.\d+\.\d+/, Unikraft::Cloud::VERSION) + end +end diff --git a/unikraft-cloud.gemspec b/unikraft-cloud.gemspec new file mode 100644 index 0000000..6c50b1d --- /dev/null +++ b/unikraft-cloud.gemspec @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +require_relative "lib/unikraft/cloud/version" + +Gem::Specification.new do |spec| + spec.name = "unikraft-cloud" + spec.version = Unikraft::Cloud::VERSION + spec.authors = ["Unikraft GmbH"] + spec.summary = "The official Ruby SDK for Unikraft Cloud." + spec.description = "Client for the Unikraft Cloud platform and " \ + "control-plane APIs." + spec.homepage = "https://unikraft.com" + spec.license = "BSD-3-Clause" + spec.required_ruby_version = ">= 3.3" + + spec.metadata = { + "homepage_uri" => spec.homepage, + "source_code_uri" => "https://github.com/unikraft-cloud/ruby-sdk", + "rubygems_mfa_required" => "true" + } + + spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, &:read) + .split("\x0") + .select { |f| f.start_with?("lib/", "README", "LICENSE") } + spec.require_paths = ["lib"] +end From cfc245696d76227aa1a7e562ad8d7163dabe8f72 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:40:44 -0800 Subject: [PATCH 08/30] feat(core): Add the error hierarchy Unikraft::Cloud::Error carries kind (http, network, parse, fanout, config, timeout), status, errors, body and an explicit cause. AmbiguousRefError and MetroFanoutError cover the multi-metro cases. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/core/errors.rb | 96 +++++++++++++++++++++++++++++++ test/unit/errors_test.rb | 72 +++++++++++++++++++++++ 3 files changed, 169 insertions(+) create mode 100644 lib/unikraft/cloud/core/errors.rb create mode 100644 test/unit/errors_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 8b4b70b..ac31917 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -4,3 +4,4 @@ # Copyright (c) 2026, Unikraft GmbH. require_relative "cloud/version" +require_relative "cloud/core/errors" diff --git a/lib/unikraft/cloud/core/errors.rb b/lib/unikraft/cloud/core/errors.rb new file mode 100644 index 0000000..1a6fd47 --- /dev/null +++ b/lib/unikraft/cloud/core/errors.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +module Unikraft + module Cloud + # Raised for every failure the SDK reports. A single class (with + # subclasses for the multi-metro cases) so one `rescue` covers both APIs. + # + # `kind` says what went wrong: + # - `:http`: the server answered with a non-2xx status; + # - `:network`: the request never got an answer (refused, reset, DNS, TLS, + # read timeout); + # - `:parse`: a 2xx answer whose body is not the JSON it should be; + # - `:fanout`: a multi-metro operation failed in some metros, or a ref is + # ambiguous across metros; + # - `:config`: a call that could never be sent as configured (no token, + # contradicting options, a body on a GET); + # - `:timeout`: a wait ran out of time. It carries no `status`, because no + # single request failed; the last failure is the `cause`. + class Error < StandardError + KINDS = %i[http network parse fanout config timeout].freeze + + # @return [Symbol] one of {KINDS} + attr_reader :kind + # @return [Integer, nil] the HTTP status code, when there was one + attr_reader :status + # @return [Array, nil] the `errors` of the response envelope + attr_reader :errors + # @return [Object, nil] the parsed response body, or the raw text + attr_reader :body + + # @param message [String] + # @param kind [Symbol] one of {KINDS} + # @param status [Integer, nil] + # @param errors [Array, nil] + # @param body [Object, nil] + # @param cause [Exception, nil] overrides Ruby's implicit `cause` + def initialize(message = nil, kind:, status: nil, errors: nil, body: nil, cause: nil) + raise ArgumentError, "unknown error kind #{kind.inspect}" unless KINDS.include?(kind) + + super(message) + @kind = kind + @status = status + @errors = errors + @body = body + @cause = cause + end + + # The underlying failure: the one given explicitly, or else the + # exception being handled when this one was raised. + def cause + @cause || super + end + end + + # Raised when a name matches in more than one metro and the operation can + # act on only one. Names are unique within a metro, not across them, so + # this is routine: qualify the ref with a metro, narrow the scope, or act + # on every match. The matches are attached, so recovering costs nothing. + class AmbiguousRefError < Error + # @return [Array] the matching resources, each tagged with its `metro` + attr_reader :matches + + def initialize(message, matches:) + super(message, kind: :fanout, body: matches) + @matches = matches + end + + # @return [Array] the metros the name was found in + def metros + matches.map(&:metro) + end + end + + # Raised when an operation fanned out over several metros failed in some + # of them. `failures` holds `{metro:, error:}` entries in the order they + # occurred; `results` holds whatever the other metros returned. + class MetroFanoutError < Error + # @return [Array] `{metro:, error:}` per failed metro + attr_reader :failures + # @return [Array] the results of the metros that succeeded + attr_reader :results + + def initialize(message, failures:, results: []) + statuses = failures.map { |f| f[:error].respond_to?(:status) ? f[:error].status : nil }.uniq + # A single underlying status is surfaced, so `status == 403` still matches. + super(message, kind: :fanout, status: statuses.size == 1 ? statuses.first : nil, + body: failures, cause: failures.first&.dig(:error)) + @failures = failures + @results = results + end + end + end +end diff --git a/test/unit/errors_test.rb b/test/unit/errors_test.rb new file mode 100644 index 0000000..c5c4131 --- /dev/null +++ b/test/unit/errors_test.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +require_relative "../test_helper" + +class ErrorsTest < Minitest::Test + Error = Unikraft::Cloud::Error + + def test_carries_kind_status_errors_and_body + err = Error.new("nope", kind: :http, status: 404, errors: [{ status: 404 }], body: { a: 1 }) + + assert_equal "nope", err.message + assert_equal :http, err.kind + assert_equal 404, err.status + assert_equal [{ status: 404 }], err.errors + assert_equal({ a: 1 }, err.body) + assert_kind_of StandardError, err + end + + def test_rejects_unknown_kind + assert_raises(ArgumentError) { Error.new("x", kind: :bogus) } + end + + def test_explicit_cause_wins + inner = RuntimeError.new("inner") + err = Error.new("outer", kind: :timeout, cause: inner) + + assert_same inner, err.cause + end + + def test_implicit_cause_is_kept + err = assert_raises(Error) do + raise "inner" + rescue RuntimeError + raise Error.new("outer", kind: :network) + end + + assert_equal "inner", err.cause.message + end + + def test_fanout_error_surfaces_a_shared_status + a = Error.new("a", kind: :http, status: 403) + b = Error.new("b", kind: :http, status: 403) + err = Unikraft::Cloud::MetroFanoutError.new( + "2 of 3 metros failed", + failures: [{ metro: "fra", error: a }, { metro: "sin", error: b }], results: [1] + ) + + assert_equal :fanout, err.kind + assert_equal 403, err.status + assert_same a, err.cause + assert_equal [1], err.results + assert_kind_of Error, err + end + + def test_fanout_error_drops_mixed_statuses + failures = [ + { metro: "fra", error: Error.new("a", kind: :http, status: 403) }, + { metro: "sin", error: Error.new("b", kind: :network) } + ] + + assert_nil Unikraft::Cloud::MetroFanoutError.new("x", failures: failures).status + end + + def test_ambiguous_ref_error_lists_metros + match = Struct.new(:metro) + err = Unikraft::Cloud::AmbiguousRefError.new("ambiguous", + matches: [match.new("fra"), match.new("sin")]) + + assert_equal %w[fra sin], err.metros + assert_equal :fanout, err.kind + end +end From 5fdba4dd0c33f6573949da27b7b08766ac435e21 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:43:14 -0800 Subject: [PATCH 09/30] feat(core): Add the HTTP transport Core::ApiClient talks to one base URL with a bearer token, and offers request (parsed JSON), bytes (raw body) and stream (one parsed server-sent event per yield), the duck type the plugin gems take. It never retries, refuses a body on GET and HEAD, honours the proxy environment through Net::HTTP, and takes base_url and timeout per call. Core::URL and Core::Base64 are the small helpers it and the porcelain share. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 3 + lib/unikraft/cloud/core/base64.rb | 36 ++++ lib/unikraft/cloud/core/http.rb | 291 ++++++++++++++++++++++++++++++ lib/unikraft/cloud/core/url.rb | 23 +++ test/support/fake_server.rb | 75 ++++++++ test/unit/base64_test.rb | 26 +++ test/unit/http_test.rb | 187 +++++++++++++++++++ 7 files changed, 641 insertions(+) create mode 100644 lib/unikraft/cloud/core/base64.rb create mode 100644 lib/unikraft/cloud/core/http.rb create mode 100644 lib/unikraft/cloud/core/url.rb create mode 100644 test/support/fake_server.rb create mode 100644 test/unit/base64_test.rb create mode 100644 test/unit/http_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index ac31917..c3ff272 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -5,3 +5,6 @@ require_relative "cloud/version" require_relative "cloud/core/errors" +require_relative "cloud/core/url" +require_relative "cloud/core/base64" +require_relative "cloud/core/http" diff --git a/lib/unikraft/cloud/core/base64.rb b/lib/unikraft/cloud/core/base64.rb new file mode 100644 index 0000000..e754c37 --- /dev/null +++ b/lib/unikraft/cloud/core/base64.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +module Unikraft + module Cloud + module Core + # Strict base64, the way the plugins carry binary payloads. Built on + # `pack("m0")` because the `base64` library left the default gems in + # Ruby 3.4, and the SDK takes no runtime dependencies. + module Base64 + module_function + + # @param bytes [String] any encoding; its bytes are encoded + # @return [String] strict (unwrapped) base64 + def encode(bytes) + [bytes.to_s.b].pack("m0") + end + + # @param text [String] strict base64 + # @return [String] the decoded bytes, as binary + # @raise [ArgumentError] when the input is not strict base64 + def decode(text) + text.to_s.unpack1("m0") + end + + # @param text [String] strict base64 of UTF-8 text + # @return [String] the decoded text, as UTF-8 + def decode_text(text) + decode(text).force_encoding(Encoding::UTF_8) + end + end + end + end +end diff --git a/lib/unikraft/cloud/core/http.rb b/lib/unikraft/cloud/core/http.rb new file mode 100644 index 0000000..32d9bc4 --- /dev/null +++ b/lib/unikraft/cloud/core/http.rb @@ -0,0 +1,291 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# Shared, spec-independent HTTP transport for the generated plumbing clients +# and the plugin gems. + +require "json" +require "net/http" +require "openssl" +require "uri" + +require_relative "errors" +require_relative "url" +require_relative "../version" + +module Unikraft + module Cloud + module Core + # Transport for one base URL. Performs authenticated requests and + # returns the parsed response envelope. Raises {Unikraft::Cloud::Error} + # on network failures and non-2xx responses. It never retries. + # + # It satisfies the duck-typed transport the plugin gems + # (`unikraft-cloud-plugin--api`) take: `request`, `bytes` and + # `stream`, each with the keywords `method:`, `path:`, `query:`, + # `body:`, `headers:`, plus the per-call `base_url:` and `timeout:`. + # A change to one of those signatures is a breaking change for every + # plugin gem; see CONTRIBUTING.md, "The transport contract". + # + # Proxies come from the environment (`http_proxy`, `https_proxy`, + # `no_proxy`, any case) through Net::HTTP, unless `proxy_from_env:` is + # false. + # + # @example + # client = Unikraft::Cloud::Core::ApiClient.new( + # base_url: "https://api.fra.unikraft.cloud", token: ENV["UKC_TOKEN"] + # ) + # client.request(method: :get, path: "/v1/instances", query: { count: 10 }) + class ApiClient + # Seconds to wait for a connection and for each read, by default. + DEFAULT_TIMEOUT = 60 + + # Methods that must not carry a body. + BODYLESS = %w[GET HEAD].freeze + + # Separator between two server-sent events. + SSE_EVENT_BOUNDARY = /\r\n\r\n|\n\n|\r\r/ + + # What Net::HTTP raises when a request never gets an answer. + NETWORK_ERRORS = [ + IOError, SocketError, SystemCallError, Timeout::Error, + OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::ProtocolError + ].freeze + + # @return [String] the base URL, without trailing slashes + attr_reader :base_url + # @return [String, nil] the bearer token + attr_reader :token + # @return [Hash{String => String}] headers sent with every request + attr_reader :headers + # @return [Numeric, nil] the default timeout in seconds + attr_reader :timeout + + # @param base_url [String] e.g. `https://api.fra.unikraft.cloud` + # @param token [String, nil] bearer token + # @param headers [Hash{String => String}] default headers + # @param user_agent [String, nil] overrides the SDK's User-Agent + # @param timeout [Numeric, nil] seconds per connect and read; nil + # waits without limit + # @param proxy_from_env [Boolean] honour the proxy env variables + def initialize(base_url:, token: nil, headers: {}, user_agent: nil, + timeout: DEFAULT_TIMEOUT, proxy_from_env: true) + @base_url = URL.strip_trailing_slashes(base_url) + @token = token + @headers = { "User-Agent" => user_agent || "unikraft-cloud-ruby/#{VERSION}" } + headers&.each { |k, v| @headers[k.to_s] = v.to_s } + @timeout = timeout + @proxy_from_env = proxy_from_env + end + + # Perform a request and return its parsed JSON body (symbol keys). + # + # @param method [String, Symbol] HTTP method + # @param path [String] path below the base URL, already escaped + # @param query [Hash, nil] query parameters; arrays repeat the key and + # nil values are left out + # @param body [Object, nil] JSON body; refused on GET and HEAD + # @param headers [Hash, nil] merged over the defaults for this call + # @param options [Hash] `base_url:` and `timeout:` for this call + # @return [Hash, Array, nil] the parsed body, or nil when empty + # @raise [Unikraft::Cloud::Error] + def request(method:, path:, query: nil, body: nil, headers: nil, **options) + perform("application/json", method:, path:, query:, body:, headers:, + **options) do |res, url| + text = res.body.to_s + parsed = text.empty? ? nil : parse_json(text, res, url) + raise http_error(res, parsed, text) unless res.is_a?(Net::HTTPSuccess) + + parsed + end + end + + # Perform a request whose success response is an unenveloped + # `application/octet-stream` body, and return it verbatim. + # + # @param (see #request) + # @return [String] the body, binary + # @raise [Unikraft::Cloud::Error] + def bytes(method:, path:, query: nil, body: nil, headers: nil, **options) + perform("application/octet-stream", method:, path:, query:, body:, headers:, + **options) do |res, _| + raise http_error(res, *lenient_json(res.body.to_s)) unless res.is_a?(Net::HTTPSuccess) + + res.body.to_s.b + end + end + + # Perform a request whose response is a `text/event-stream`, and yield + # each event's JSON payload (symbol keys) as it arrives. Returns when + # the server closes the stream; `break` out of the block to stop early + # and release the connection. + # + # @param (see #request) + # @yieldparam event [Hash, Array] one event's parsed `data` + # @return [Enumerator, nil] an Enumerator when no block is given + # @raise [Unikraft::Cloud::Error] + def stream(method:, path:, query: nil, body: nil, headers: nil, **options, &block) + unless block + return enum_for(:stream, method: method, path: path, query: query, body: body, + headers: headers, **options) + end + + perform("text/event-stream", method:, path:, query:, body:, headers:, + **options) do |res, url| + raise http_error(res, *lenient_json(res.body.to_s)) unless res.is_a?(Net::HTTPSuccess) + + read_events(res, url, &block) + end + nil + end + + private + + # Build and send one request, and hand the response to the block while + # the connection is open (so a stream can be read from it). + def perform(accept, method:, path:, query:, body:, headers:, **options) + options = call_options(options) + verb = method.to_s.upcase + if !body.nil? && BODYLESS.include?(verb) + raise Error.new("A #{verb} request cannot carry a body; pass the filters as query " \ + "parameters instead", kind: :config) + end + + url = URL.strip_trailing_slashes(options.fetch(:base_url) || @base_url) + + path.to_s + encode_query(query) + uri = URI(url) + req = build_request(verb, uri, body, headers, accept) + via_proxy = false + begin + http = connection(uri, options.fetch(:timeout)) + via_proxy = http.proxy? + http.start do + http.request(req) do |res| + return yield(res, url) if accept == "text/event-stream" + + res.read_body + return yield(res, url) + end + end + rescue *NETWORK_ERRORS => e + raise network_error(url, e, via_proxy) + end + end + + def call_options(options) + unknown = options.keys - %i[base_url timeout] + raise ArgumentError, "unknown keyword(s): #{unknown.join(", ")}" unless unknown.empty? + + { base_url: options[:base_url], timeout: options.fetch(:timeout, @timeout) } + end + + def build_request(verb, uri, body, headers, accept) + req = Net::HTTPGenericRequest.new(verb, !body.nil?, verb != "HEAD", uri) + req["Accept"] = accept + @headers.each { |k, v| req[k] = v } + req["Authorization"] = "Bearer #{@token}" if @token + headers&.each { |k, v| req[k.to_s] = v.to_s } + unless body.nil? + req["Content-Type"] = "application/json" + req.body = JSON.generate(body) + end + req + end + + def connection(uri, timeout) + proxy = @proxy_from_env ? :ENV : nil + http = Net::HTTP.new(uri.host, uri.port, proxy) + http.use_ssl = uri.scheme == "https" + http.open_timeout = timeout + http.read_timeout = timeout + http.write_timeout = timeout + http + end + + # Serialise a query hash in form/explode style. + def encode_query(query) + return "" if query.nil? + + pairs = query.each_with_object([]) do |(key, value), out| + next if value.nil? + + Array(value).each { |item| out << [key.to_s, item.to_s] unless item.nil? } + end + pairs.empty? ? "" : "?#{URI.encode_www_form(pairs)}" + end + + def parse_json(text, res, url) + JSON.parse(text, symbolize_names: true) + rescue JSON::ParserError => e + unless res.is_a?(Net::HTTPSuccess) + raise Error.new("HTTP #{res.code} #{res.message}".strip, + kind: :http, status: res.code.to_i, body: text, cause: e) + end + + raise Error.new("Failed to parse response body from #{url}", + kind: :parse, status: res.code.to_i, body: text, cause: e) + end + + # Decode an error body that may or may not be an envelope. + def lenient_json(text) + parsed = text.empty? ? nil : JSON.parse(text, symbolize_names: true) + [parsed, text] + rescue JSON::ParserError + [nil, text] + end + + def http_error(res, parsed, text) + envelope = parsed.is_a?(Hash) ? parsed : {} + message = envelope[:message] || "HTTP #{res.code} #{res.message}".strip + Error.new(message, kind: :http, status: res.code.to_i, + errors: envelope[:errors], body: parsed.nil? ? text : parsed) + end + + def network_error(url, cause, via_proxy) + via = via_proxy ? " (through the proxy set in http_proxy/https_proxy)" : "" + Error.new("Request to #{url} failed#{via}: #{cause.class}: #{cause.message}", + kind: :network, cause: cause) + end + + def read_events(res, url) + buffer = +"" + res.read_body do |chunk| + buffer << chunk.b + while (boundary = SSE_EVENT_BOUNDARY.match(buffer)) + block = buffer[0, boundary.begin(0)] + buffer = buffer[boundary.end(0)..] + event = parse_event(block, url, res) + yield event unless event.nil? + end + end + # A last event may arrive without its trailing blank line. + event = parse_event(buffer, url, res) + yield event unless event.nil? + end + + # The JSON payload of one event block: its `data:` lines joined. Nil + # for comments and keep-alives. + def parse_event(block, url, res) + values = block.dup.force_encoding(Encoding::UTF_8).split("\n").filter_map do |raw| + line = raw.chomp("\r") + next if line.start_with?(":") + + field, sep, value = line.partition(":") + next unless field == "data" + + sep.empty? ? "" : value.delete_prefix(" ") + end + data = values.join("\n") + return nil if data.empty? + + JSON.parse(data, symbolize_names: true) + rescue JSON::ParserError => e + raise Error.new("Failed to parse event stream from #{url}", + kind: :parse, status: res.code.to_i, body: data, cause: e) + end + end + end + end +end diff --git a/lib/unikraft/cloud/core/url.rb b/lib/unikraft/cloud/core/url.rb new file mode 100644 index 0000000..fe114b6 --- /dev/null +++ b/lib/unikraft/cloud/core/url.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +module Unikraft + module Cloud + module Core + # Small URL helpers shared by the transport and the metro resolution. + module URL + module_function + + # Remove every trailing "/" from a URL. + # + # @param url [String] + # @return [String] + def strip_trailing_slashes(url) + url.to_s.sub(%r{/+\z}, "") + end + end + end + end +end diff --git a/test/support/fake_server.rb b/test/support/fake_server.rb new file mode 100644 index 0000000..44de4a0 --- /dev/null +++ b/test/support/fake_server.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +require "socket" + +# A one-thread HTTP/1.1 server on 127.0.0.1 that answers each request with the +# next canned response and records what it received. Enough HTTP for the +# transport tests: Content-Length bodies in, fixed or streamed bodies out. +class FakeServer + Request = Struct.new(:verb, :target, :headers, :body, keyword_init: true) do + def path = target.split("?", 2).first + def query = target.split("?", 2)[1] + end + + attr_reader :requests + + def initialize + @server = TCPServer.new("127.0.0.1", 0) + @responses = Queue.new + @requests = [] + @thread = Thread.new { serve } + end + + def url = "http://127.0.0.1:#{@server.addr[1]}" + + # @param chunks [Array] written one by one, with a flush between + def respond(status: 200, headers: {}, body: "", chunks: nil) + @responses << { status: status, headers: headers, body: body, chunks: chunks } + self + end + + def last_request = @requests.last + + def close + @thread.kill + @server.close + end + + private + + def serve + loop do + client = @server.accept + handle(client) + ensure + client&.close + end + end + + def handle(client) + method, target = client.gets.split + headers = {} + while (line = client.gets) && line != "\r\n" + name, value = line.chomp.split(": ", 2) + headers[name.downcase] = value + end + body = client.read(headers.fetch("content-length", "0").to_i) + @requests << Request.new(verb: method, target: target, headers: headers, body: body) + write(client, @responses.pop) + end + + def write(client, res) + client.write("HTTP/1.1 #{res[:status]} X\r\nConnection: close\r\n") + res[:headers].each { |k, v| client.write("#{k}: #{v}\r\n") } + if res[:chunks] + client.write("Transfer-Encoding: chunked\r\n\r\n") + res[:chunks].each do |c| + client.write("#{c.bytesize.to_s(16)}\r\n#{c}\r\n") + client.flush + end + client.write("0\r\n\r\n") + else + client.write("Content-Length: #{res[:body].bytesize}\r\n\r\n#{res[:body]}") + end + end +end diff --git a/test/unit/base64_test.rb b/test/unit/base64_test.rb new file mode 100644 index 0000000..fa2c750 --- /dev/null +++ b/test/unit/base64_test.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +require_relative "../test_helper" + +class Base64Test < Minitest::Test + B64 = Unikraft::Cloud::Core::Base64 + + def test_round_trips_binary + bytes = (0..255).to_a.pack("C*") + + assert_equal bytes, B64.decode(B64.encode(bytes)) + refute_includes B64.encode(bytes * 4), "\n" + end + + def test_decode_text_is_utf8 + assert_equal "héllo", B64.decode_text(B64.encode("héllo")) + end + + def test_rejects_non_strict_input + assert_raises(ArgumentError) { B64.decode("a b") } + end + + def test_strips_trailing_slashes + assert_equal "https://x", Unikraft::Cloud::Core::URL.strip_trailing_slashes("https://x///") + end +end diff --git a/test/unit/http_test.rb b/test/unit/http_test.rb new file mode 100644 index 0000000..53ebf1a --- /dev/null +++ b/test/unit/http_test.rb @@ -0,0 +1,187 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/fake_server" + +class HttpTest < Minitest::Test + ApiClient = Unikraft::Cloud::Core::ApiClient + Error = Unikraft::Cloud::Error + + def setup + @server = FakeServer.new + @client = ApiClient.new(base_url: "#{@server.url}//", token: "tok", proxy_from_env: false, + headers: { "X-Default" => "d" }) + end + + def teardown + @server.close + end + + def test_request_sends_bearer_token_query_and_parses_json + @server.respond(body: '{"status":"success","data":{"n":1}}') + res = @client.request(method: :get, path: "/v1/instances", + query: { name: %w[a b], count: 2, details: true, from: nil }) + + assert_equal({ status: "success", data: { n: 1 } }, res) + req = @server.last_request + + assert_equal "GET", req.verb + assert_equal "/v1/instances", req.path + assert_equal "name=a&name=b&count=2&details=true", req.query + assert_equal "Bearer tok", req.headers["authorization"] + assert_equal "application/json", req.headers["accept"] + assert_equal "d", req.headers["x-default"] + assert_match(/\Aunikraft-cloud-ruby/, req.headers["user-agent"]) + end + + def test_request_sends_json_body_and_per_call_headers + @server.respond(body: "") + res = @client.request(method: "PATCH", path: "/v1/x", body: [{ name: "a" }], + headers: { "X-Default" => "over", "Authorization" => "Bearer other" }) + + assert_nil res + req = @server.last_request + + assert_equal "PATCH", req.verb + assert_equal '[{"name":"a"}]', req.body + assert_equal "application/json", req.headers["content-type"] + assert_equal "over", req.headers["x-default"] + assert_equal "Bearer other", req.headers["authorization"] + end + + def test_refuses_a_body_on_get_and_head + %i[get head].each do |verb| + err = assert_raises(Error) { @client.request(method: verb, path: "/x", body: {}) } + + assert_equal :config, err.kind + end + assert_empty @server.requests + end + + def test_per_call_base_url + other = FakeServer.new.respond(body: "{}") + @client.request(method: :get, path: "/v1/x", base_url: "#{other.url}/") + + assert_equal "/v1/x", other.last_request.path + assert_empty @server.requests + ensure + other&.close + end + + def test_rejects_unknown_options + assert_raises(ArgumentError) { @client.request(method: :get, path: "/", signal: 1) } + end + + # The duck type the generated plugin gems call; see CONTRIBUTING.md. + def test_satisfies_the_plugin_transport_contract + contract = [%i[keyreq method], %i[keyreq path], %i[key query], %i[key body], %i[key headers], + %i[keyrest options]] + %i[request bytes stream].each do |name| + params = ApiClient.instance_method(name).parameters - [%i[block block]] + + assert_equal contract, params, "ApiClient##{name}" + end + end + + def test_query_accepts_string_keys + @server.respond(body: "{}") + @client.request(method: "GET", path: "/x", query: { "uuid" => %w[a b] }) + + assert_equal "uuid=a&uuid=b", @server.last_request.query + end + + def test_http_error_carries_the_envelope + @server.respond(status: 404, + body: '{"status":"error","message":"gone","errors":[{"status":404}]}') + err = assert_raises(Error) { @client.request(method: :get, path: "/v1/x") } + + assert_equal :http, err.kind + assert_equal 404, err.status + assert_equal "gone", err.message + assert_equal [{ status: 404 }], err.errors + end + + def test_http_error_with_non_json_body + @server.respond(status: 502, body: "bad gateway") + err = assert_raises(Error) { @client.request(method: :get, path: "/v1/x") } + + assert_equal :http, err.kind + assert_equal 502, err.status + assert_equal "bad gateway", err.body + assert_kind_of JSON::ParserError, err.cause + end + + def test_parse_error_on_success + @server.respond(body: "not json") + err = assert_raises(Error) { @client.request(method: :get, path: "/v1/x") } + + assert_equal :parse, err.kind + assert_equal 200, err.status + end + + def test_network_error + port = TCPServer.open("127.0.0.1", 0) { |s| s.addr[1] } + client = ApiClient.new(base_url: "http://127.0.0.1:#{port}", proxy_from_env: false) + err = assert_raises(Error) { client.request(method: :get, path: "/") } + + assert_equal :network, err.kind + assert_nil err.status + assert_kind_of SystemCallError, err.cause + end + + def test_timeout_is_a_network_error + client = ApiClient.new(base_url: "http://10.255.255.1", proxy_from_env: false) + err = assert_raises(Error) { client.request(method: :get, path: "/", timeout: 0.05) } + + assert_equal :network, err.kind + end + + def test_bytes_returns_the_body_verbatim + @server.respond(body: "\x00\x01\xFF".b, + headers: { "Content-Type" => "application/octet-stream" }) + out = @client.bytes(method: :get, path: "/file") + + assert_equal "\x00\x01\xFF".b, out + assert_equal Encoding::BINARY, out.encoding + assert_equal "application/octet-stream", @server.last_request.headers["accept"] + end + + def test_bytes_error_decodes_the_envelope + @server.respond(status: 410, body: "") + err = assert_raises(Error) { @client.bytes(method: :get, path: "/file") } + + assert_equal 410, err.status + assert_equal "", err.body + end + + def test_stream_yields_each_event + @server.respond(chunks: [": keep-alive\n\n", "data: {\"a\":", "1}\n\ndata: {\"a\":2}\r\n\r\n", + "event: x\ndata: {\"a\":\ndata: 3}"]) + events = [] + @client.stream(method: :post, path: "/v1/auth/check", body: {}) { |e| events << e } + + assert_equal [{ a: 1 }, { a: 2 }, { a: 3 }], events + assert_equal "text/event-stream", @server.last_request.headers["accept"] + end + + def test_stream_without_a_block_is_an_enumerator + @server.respond(chunks: ["data: 1\n\ndata: 2\n\n"]) + + assert_equal [1, 2], @client.stream(method: :get, path: "/s").to_a + end + + def test_stream_bad_event_is_a_parse_error + @server.respond(chunks: ["data: nope\n\n"]) + err = assert_raises(Error) { @client.stream(method: :get, path: "/s") { nil } } + + assert_equal :parse, err.kind + end + + def test_stream_http_error + @server.respond(status: 401, body: '{"message":"unauthorized"}') + err = assert_raises(Error) { @client.stream(method: :get, path: "/s") { nil } } + + assert_equal 401, err.status + assert_equal "unauthorized", err.message + end +end From 816fc9ebe90e000b137541eec202e88bd5415187 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:44:31 -0800 Subject: [PATCH 10/30] feat(core): Add the Model base class Generated models inherit Unikraft::Cloud::Model: built from a Hash, one reader per declared property, nested models cast by declared type, unknown keys kept, #[], #to_h, #to_json and value equality. The porcelain tags results with their metro through #with_metro, which never reaches #to_h. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/model.rb | 184 ++++++++++++++++++++++++++++++++++++ test/unit/model_test.rb | 97 +++++++++++++++++++ 3 files changed, 282 insertions(+) create mode 100644 lib/unikraft/cloud/model.rb create mode 100644 test/unit/model_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index c3ff272..f7fa0eb 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -8,3 +8,4 @@ require_relative "cloud/core/url" require_relative "cloud/core/base64" require_relative "cloud/core/http" +require_relative "cloud/model" diff --git a/lib/unikraft/cloud/model.rb b/lib/unikraft/cloud/model.rb new file mode 100644 index 0000000..0ec14b4 --- /dev/null +++ b/lib/unikraft/cloud/model.rb @@ -0,0 +1,184 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require "json" + +module Unikraft + module Cloud + # Base class of every generated model: a read-only view over a JSON + # object with one reader per declared property. + # + # A model is built from a Hash with symbol or string keys. Every field is + # optional (a reader returns nil for a missing key) and unknown keys are + # kept, so a newer server never breaks an older SDK: they stay reachable + # through {#[]} and {#to_h}. Nested objects become their declared model + # class, recursively. + # + # @example + # class Instance < Unikraft::Cloud::Model + # attribute :name + # end + # inst = Instance.new(name: "web", extra: 1) + # inst.name # => "web" + # inst[:extra] # => 1 + # inst.to_h # => { name: "web", extra: 1 } + class Model + # Fields {#inspect} masks: keys, tokens and credentials the API returns. + REDACTED = %i[authorization credentials pkey secret token].freeze + MASK = Object.new.tap { |o| o.define_singleton_method(:inspect) { "[REDACTED]" } }.freeze + private_constant :MASK + + class << self + # @return [Hash{Symbol => Array}] the declared properties, by wire key + def attributes + @attributes ||= superclass <= Model ? superclass.attributes.dup : {} + end + + # Declare a property and define its reader. + # + # @param name [Symbol] the reader, and the wire key unless `key:` is given + # @param type [String, Class, nil] the model class of the value, by + # constant name relative to this class's namespace; nil for scalars + # @param array [Boolean] the value is an array of `type` + # @param map [Boolean] the value is an object whose values are `type` + # @param key [Symbol] the wire key, when it is no valid reader name + def attribute(name, type = nil, array: false, map: false, key: name) + attributes[key.to_sym] = [type, array, map].freeze + # A reader the base class already defines (`metro`) keeps its own. + return if Model.method_defined?(name) + + define_method(name) { @values[key.to_sym] } + end + + # Build a model from a Hash, pass a model or nil through. + # + # @param value [Hash, Model, nil] + # @return [Model, nil] + def from(value) + value.nil? || value.is_a?(self) ? value : new(value) + end + end + + # @param values [Hash, Model] the JSON object + def initialize(values = {}) + values = values.to_h unless values.is_a?(Hash) + @values = values.to_h do |k, v| + key = k.to_sym + [key, cast(self.class.attributes[key], v)] + end.freeze + @metro = nil + end + + # Read a field by its wire key, declared or not. + # + # @param key [Symbol, String] + def [](key) + @values[key.to_sym] + end + + # The metro this model was read from, when the porcelain tagged it (see + # {#with_metro}), or else its own `metro` field. + # + # @return [String, nil] + def metro + @metro || @values[:metro] + end + + # A copy tagged with the metro it came from. The tag is not part of + # {#to_h}, so it never reaches the wire. + # + # @param metro [String] + # @return [Model] + def with_metro(metro) + copy = dup + copy.instance_variable_set(:@metro, metro) + copy + end + + # The JSON object, nested models included, with symbol keys. + # + # @return [Hash] + def to_h + @values.transform_values { |v| plain(v) } + end + + # @return [String] + def to_json(*) + to_h.to_json(*) + end + + def ==(other) + other.instance_of?(self.class) && other.to_h == to_h && other.metro == metro + end + alias eql? == + + def hash + [self.class, to_h, metro].hash + end + + def inspect = "#<#{self.class.name || "Model"} #{inspect_fields}>" + alias to_s inspect + + # The fields as {#inspect} shows them, secrets ({REDACTED}) masked at + # any depth, untyped Hashes included. + # + # @api private + # @return [String] + def inspect_fields + fields = redact(@values).map { |k, v| "#{k}=#{v.inspect}" } + fields << "metro=#{@metro.inspect}" if @metro + fields.join(", ") + end + + private + + def cast(spec, value) + type, array, map = spec + return value if type.nil? || value.nil? + + klass = resolve(type) + if array && value.is_a?(Array) + value.map { |v| cast_one(klass, v) } + elsif map && value.is_a?(Hash) + value.transform_values { |v| cast_one(klass, v) } + else + cast_one(klass, value) + end + end + + # Anything other than an object (a newer server's shape) is kept as is. + def cast_one(klass, value) + value.is_a?(Hash) ? klass.new(value) : value + end + + def resolve(type) + return type if type.is_a?(Class) + + namespace = self.class.name.to_s.rpartition("::").first + Object.const_get(namespace.empty? ? type : "#{namespace}::#{type}") + end + + def redact(value) + case value + when Hash then value.to_h { |k, v| [k, secret?(k) ? MASK : redact(v)] } + when Array then value.map { |v| redact(v) } + else value + end + end + + # HTTP headers come in any case, e.g. `Authorization`. + def secret?(key) = REDACTED.include?(key.to_s.downcase.to_sym) + + def plain(value) + case value + when Model then value.to_h + when Array then value.map { |v| plain(v) } + when Hash then value.transform_values { |v| plain(v) } + else value + end + end + end + end +end diff --git a/test/unit/model_test.rb b/test/unit/model_test.rb new file mode 100644 index 0000000..6509d96 --- /dev/null +++ b/test/unit/model_test.rb @@ -0,0 +1,97 @@ +# frozen_string_literal: true + +require_relative "../test_helper" + +module ModelTestModels + class Volume < Unikraft::Cloud::Model + attribute :name + end + + class Instance < Unikraft::Cloud::Model + attribute :name + attribute :volumes, "Volume", array: true + attribute :env + attribute :by_name, "Volume", map: true + attribute :root, "Volume" + attribute :metro + end +end + +class ModelTest < Minitest::Test + Instance = ModelTestModels::Instance + Volume = ModelTestModels::Volume + + def wire + { "name" => "web", volumes: [{ name: "v1" }], env: { "A" => "1" }, + by_name: { v2: { name: "v2" } }, root: { name: "r" }, extra: { deep: 1 } } + end + + def test_readers_and_nested_models + inst = Instance.new(wire) + + assert_equal "web", inst.name + assert_equal [Volume.new(name: "v1")], inst.volumes + assert_equal({ "A" => "1" }, inst.env) + assert_equal "v2", inst.by_name[:v2].name + assert_equal "r", inst.root.name + end + + def test_missing_fields_are_nil_and_unknown_keys_kept + inst = Instance.new(extra: 1) + + assert_nil inst.name + assert_nil inst.volumes + assert_equal 1, inst[:extra] + assert_equal 1, inst["extra"] + end + + def test_to_h_round_trips + inst = Instance.new(wire) + + assert_equal "v1", inst.to_h[:volumes].first[:name] + assert_equal inst, Instance.new(inst.to_h) + assert_equal JSON.parse(JSON.generate(inst.to_h)), JSON.parse(inst.to_json) + end + + def test_tolerates_unexpected_shapes + inst = Instance.new(volumes: "oops", root: 3) + + assert_equal "oops", inst.volumes + assert_equal 3, inst.root + end + + def test_equality_and_hash + a = Instance.new(name: "x") + b = Instance.new("name" => "x") + + assert_equal a, b + assert_equal a.hash, b.hash + refute_equal a, Volume.new(name: "x") + end + + def test_with_metro_tags_a_copy + inst = Instance.new(name: "x") + tagged = inst.with_metro("fra") + + assert_equal "fra", tagged.metro + assert_nil inst.metro + refute_includes tagged.to_h, :metro + refute_equal inst, tagged + end + + def test_metro_falls_back_to_the_field + assert_equal "sin", Instance.new(metro: "sin").metro + end + + def test_from + inst = Instance.new(name: "x") + + assert_same inst, Instance.from(inst) + assert_nil Instance.from(nil) + assert_equal inst, Instance.from(name: "x") + end + + def test_json_generate_accepts_models + assert_equal '{"name":"x"}', JSON.generate(Volume.new(name: "x")) + end +end From 1e809f5922045ff8bad18841c875a2a0b733a13b Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:45:40 -0800 Subject: [PATCH 11/30] feat(core): Add wait_until_ready polling Core::Ready.wait_until_ready probes until a block succeeds: 100 ms doubling to 2 s with jitter, a 60 s deadline, retrying only network failures and 404/502/503/504. 401 and 403 are rethrown at once, and the deadline raises a :timeout error whose cause is the last failure. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/core/ready.rb | 145 +++++++++++++++++++++++++++++++ test/unit/ready_test.rb | 99 +++++++++++++++++++++ 3 files changed, 245 insertions(+) create mode 100644 lib/unikraft/cloud/core/ready.rb create mode 100644 test/unit/ready_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index f7fa0eb..f219b15 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -8,4 +8,5 @@ require_relative "cloud/core/url" require_relative "cloud/core/base64" require_relative "cloud/core/http" +require_relative "cloud/core/ready" require_relative "cloud/model" diff --git a/lib/unikraft/cloud/core/ready.rb b/lib/unikraft/cloud/core/ready.rb new file mode 100644 index 0000000..3093fbe --- /dev/null +++ b/lib/unikraft/cloud/core/ready.rb @@ -0,0 +1,145 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# Asking a service repeatedly whether it is ready yet. +# +# This module owns the mechanism only: the backoff, the deadline and, most +# importantly, which failures are worth asking again about. What to ask, and +# what to say when the answer never comes, belong to the caller. + +require_relative "errors" + +module Unikraft + module Cloud + module Core + # Polling with capped, jittered exponential backoff and a deadline. + module Ready + # The values {wait_until_ready} uses for anything left out, in seconds. + DEFAULTS = { initial_delay: 0.1, max_delay: 2.0, timeout: 60.0 }.freeze + + # The HTTP statuses worth probing again for. 502/503/504 are a proxy + # with nothing to forward to yet; 404 is a plugin route not registered + # yet while the instance boots. Everything else is final, and 401/403 + # especially so: retrying a rejected token would turn "unauthorized" + # into a timeout and hide the one error the caller can act on. + RETRYABLE_STATUSES = [404, 502, 503, 504].freeze + + module_function + + # Whether a failed probe says "not yet" rather than "no". + # + # @param err [Exception] + # @return [Boolean] + def retryable?(err) + return false unless err.is_a?(Unikraft::Cloud::Error) + # A refused connection, a reset, a DNS miss: still coming up. + return true if err.kind == :network + + err.kind == :http && RETRYABLE_STATUSES.include?(err.status) + end + + # Probe until it succeeds, and return once it does. + # + # The block is the probe. It should be cheap, idempotent, and answer as + # soon as the service is usable. It is given the seconds left until the + # deadline, and should pass them on as the request's `timeout:`, since + # a probe in flight is not interrupted. + # + # @param initial_delay [Numeric] first delay between probes (0.1 s) + # @param max_delay [Numeric] cap on the delay between probes (2 s) + # @param timeout [Numeric] give up after this long (60 s) + # @param what [String] the subject of the timeout message + # @param diagnose [#call, nil] asked once, only after the deadline, with + # the last error; returns a phrase naming the real cause, appended to + # the timeout message + # @yieldparam remaining [Float] seconds left until the deadline + # @return [nil] + # @raise [Unikraft::Cloud::Error] kind `:timeout` when the deadline + # passes, with the last probe failure as `cause`; or the probe's own + # error when it is not retryable + # @raise [ArgumentError] when a duration is not a usable number + # + # @example + # Ready.wait_until_ready(timeout: 10, what: "sandbox #{uuid}") do |left| + # api.list_commands(timeout: left) + # end + def wait_until_ready(initial_delay: DEFAULTS[:initial_delay], + max_delay: DEFAULTS[:max_delay], timeout: DEFAULTS[:timeout], + what: "the service", diagnose: nil) + delay = duration(:initial_delay, initial_delay, zero: false) + max_delay = duration(:max_delay, max_delay, zero: false) + timeout = duration(:timeout, timeout, zero: true) + deadline = now + timeout + attempts = 0 + last_error = nil + + loop do + attempts += 1 + begin + yield [deadline - now, 0.0].max + return nil + rescue Unikraft::Cloud::Error => e + raise unless retryable?(e) + + last_error = e + end + + delay = back_off(delay, max_delay, deadline - now) + next if now < deadline + + raise timed_out(what, timeout, attempts, last_error, diagnose) + end + end + + # Sleep before the next probe, never past the deadline, and return the + # next delay. Jitter covers the lower half of the window, so a fleet + # created together does not probe in lockstep. + def back_off(delay, max_delay, remaining) + return delay unless remaining.positive? + + window = [delay, max_delay].min + sleep([(window / 2.0) + (rand * window / 2.0), remaining].min) + [delay * 2, max_delay].min + end + + def timed_out(what, timeout, attempts, last_error, diagnose) + why = begin + diagnose&.call(last_error) + rescue StandardError + nil # A failed diagnosis must not replace the timeout it explains. + end + last = if last_error + "The last attempt failed with: #{last_error.message}" + else + "The last probe never answered." + end + # No `status`: the deadline failed, not one request. Carrying the last + # probe's 404 would make this look like a missing resource. + Unikraft::Cloud::Error.new( + "#{what} was not ready within #{timeout} s (#{attempts} " \ + "#{attempts == 1 ? "probe" : "probes"})#{": #{why}" if why}. #{last}", + kind: :timeout, cause: last_error + ) + end + + # A value the loop cannot use (NaN, negative) would poll flat out + # instead of waiting, so it is refused rather than clamped. + def duration(name, value, zero:) + ok = value.is_a?(Numeric) && value.to_f.finite? && (zero ? value >= 0 : value.positive?) + return value.to_f if ok + + raise ArgumentError, "`#{name}` must be a number of seconds, " \ + "#{zero ? "0 or more" : "above 0"}. Received #{value.inspect}." + end + + def now + Process.clock_gettime(Process::CLOCK_MONOTONIC) + end + + private_class_method :back_off, :timed_out, :duration, :now + end + end + end +end diff --git a/test/unit/ready_test.rb b/test/unit/ready_test.rb new file mode 100644 index 0000000..dc7aab4 --- /dev/null +++ b/test/unit/ready_test.rb @@ -0,0 +1,99 @@ +# frozen_string_literal: true + +require_relative "../test_helper" + +class ReadyTest < Minitest::Test + Ready = Unikraft::Cloud::Core::Ready + Error = Unikraft::Cloud::Error + + FAST = { initial_delay: 0.001, max_delay: 0.002 }.freeze + + def http(status) = Error.new("HTTP #{status}", kind: :http, status: status) + + def test_returns_once_the_probe_succeeds + calls = 0 + Ready.wait_until_ready(**FAST) do |left| + calls += 1 + + assert_operator left, :>, 0 + raise http(503) if calls < 3 + end + + assert_equal 3, calls + end + + def test_retries_network_and_gateway_statuses + errors = [Error.new("refused", kind: :network), http(404), http(502), http(503), http(504)] + Ready.wait_until_ready(**FAST) do + raise errors.shift unless errors.empty? + end + + assert_empty errors + end + + def test_rethrows_401_and_403_at_once + [401, 403, 500].each do |status| + calls = 0 + err = assert_raises(Error) do + Ready.wait_until_ready(**FAST) do + calls += 1 + raise http(status) + end + end + + assert_equal status, err.status + assert_equal 1, calls + end + end + + def test_rethrows_foreign_exceptions + assert_raises(KeyError) { Ready.wait_until_ready(**FAST) { raise KeyError } } + end + + def test_times_out_with_the_last_error_as_cause + last = http(502) + err = assert_raises(Error) do + Ready.wait_until_ready(**FAST, timeout: 0.02, what: "sandbox x", + diagnose: ->(e) { "state is #{e.status}" }) { raise last } + end + + assert_equal :timeout, err.kind + assert_nil err.status + assert_same last, err.cause + assert_match(/\Asandbox x was not ready within 0.02 s \(\d+ probes\): state is 502\. /, + err.message) + assert_match(/The last attempt failed with: HTTP 502\z/, err.message) + end + + def test_a_failing_diagnosis_keeps_the_timeout + err = assert_raises(Error) do + Ready.wait_until_ready(**FAST, timeout: 0, diagnose: ->(_) { raise "boom" }) do + raise http(503) + end + end + + assert_equal :timeout, err.kind + assert_match(/\(1 probe\)\. /, err.message) + end + + def test_backoff_doubles_up_to_the_cap + stamps = [] + assert_raises(Error) do + Ready.wait_until_ready(initial_delay: 0.01, max_delay: 0.04, timeout: 0.2) do + stamps << Process.clock_gettime(Process::CLOCK_MONOTONIC) + raise http(503) + end + end + gaps = stamps.each_cons(2).map { |a, b| b - a } + + assert_operator gaps.first, :>=, 0.005 + assert(gaps[0...-1].all? { |g| g < 0.06 }, "a gap exceeded the cap: #{gaps}") + end + + def test_rejects_unusable_durations + [{ initial_delay: 0 }, { max_delay: -1 }, { timeout: Float::NAN }, + { timeout: "1" }].each do |bad| + assert_raises(ArgumentError) { Ready.wait_until_ready(**bad) { nil } } + end + end +end From 4b80d939490852dba4cb81f9717a060d22a88932 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:55:03 -0800 Subject: [PATCH 12/30] feat(api): Add the openapi-gen templates for Ruby models.rb.tmpl renders a Model subclass per object schema and a frozen constants module per enum. resources.rb.tmpl renders one class per tag whose methods are the snake_cased operationIds with keyword arguments, returning the envelope wrapped in its model, the raw bytes, or each event of a stream. As in the JS SDK, the body of a GET or HEAD is dropped in favour of its query parameters. The templates use only the generic helpers of the published openapi-gen. Signed-off-by: Alexander Jung --- templates/models.rb.tmpl | 123 ++++++++++++++++++++++ templates/resources.rb.tmpl | 198 ++++++++++++++++++++++++++++++++++++ 2 files changed, 321 insertions(+) create mode 100644 templates/models.rb.tmpl create mode 100644 templates/resources.rb.tmpl diff --git a/templates/models.rb.tmpl b/templates/models.rb.tmpl new file mode 100644 index 0000000..61669f3 --- /dev/null +++ b/templates/models.rb.tmpl @@ -0,0 +1,123 @@ +{{- /* The models of one API surface: a frozen constants module per enum, and a + Unikraft::Cloud::Model subclass per object schema. Ruby resolves the nested + model types by name when a model is built, so the order of the classes does + not matter. A schema that is neither (a union of scalars without an enum + branch) is left out: its values stay plain. */ -}} +{{- $module := .Var "module" "Platform" -}} +{{- /* Schemas by name: a reference the preprocessor hoisted carries no + resolved value, so it is looked up here. */ -}} +{{- $schemas := dict -}} +{{- range $m := .Models }}{{ $_ := set $schemas $m.SchemaName $m.Schema }}{{ end -}} +{{- range $m := .Models }} +{{- if not (regexMatch "^[A-Z][A-Za-z0-9_]*$" $m.SchemaName) }} +{{- fail (printf "schema %q cannot name a Ruby constant; rename it in the specification" $m.SchemaName) }} +{{- end }} +{{- end -}} +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../model" + +module Unikraft + module Cloud + class API + class {{ $module }} + # The models of the {{ $module }} API, mirroring the wire format. + module Models +{{- $first := true }} +{{- range $m := .Models }} +{{- $schema := $m.Schema }} +{{- $name := $m.SchemaName }} +{{- /* Enumerations: closed (`enum`) or open (a union with enum branches). */ -}} +{{- $values := list }} +{{- if $schema.Enum }}{{ $values = $schema.Enum }} +{{- else if not $schema.Properties }} +{{- range $branch := concat $schema.AnyOf $schema.OneOf }}{{ with $branch.Value }}{{ range .Enum }}{{ $values = append $values . }}{{ end }}{{ end }}{{ end }} +{{- end }} +{{- if $values }} +{{- if not $first }} +{{ end }}{{ $first = false }} +{{ template "doc" (list (default (printf "The `%s` enumeration." $name) $schema.Description) " ") }} module {{ $name }} +{{- $consts := list }} +{{- range $v := $values }} +{{- $const := screamingsnakecase (printf "%v" $v) }} +{{- if not (regexMatch "^[A-Z]" $const) }}{{ $const = printf "V_%s" $const }}{{ end }} +{{- if has $const $consts }}{{ fail (printf "enum %s: two values render the constant %s" $name $const) }}{{ end }} +{{- $consts = append $consts $const }} + {{ $const }} = {{ if kindIs "string" $v }}{{ printf "%q" $v }}{{ else }}{{ $v }}{{ end }} +{{- end }} + + # Every value of this enumeration. + ALL = [{{ join ", " $consts }}].freeze + end +{{- else if or $schema.Properties $schema.AllOf (and $schema.Type ($schema.Type.Is "object")) }} +{{- if not $first }} +{{ end }}{{ $first = false }} +{{ template "doc" (list (default (printf "The `%s` model." $name) $schema.Description) " ") }} class {{ $name }} < Unikraft::Cloud::Model +{{- range $prop := propertyNamesOrdered $name $schema }} +{{- /* Find the property's reference: on the schema, or in a branch of its + composition (two levels deep, as the control-plane spec nests a oneOf + in an allOf). */ -}} +{{- $ref := index $schema.Properties $prop }} +{{- if not $ref }} +{{- range $part := concat $schema.AllOf $schema.OneOf $schema.AnyOf }}{{ if and (not $ref) $part.Value }} +{{- with index $part.Value.Properties $prop }}{{ $ref = . }}{{ end }} +{{- range $sub := concat $part.Value.AllOf $part.Value.OneOf $part.Value.AnyOf }}{{ if and (not $ref) $sub.Value }} +{{- with index $sub.Value.Properties $prop }}{{ $ref = . }}{{ end }} +{{- end }}{{ end }} +{{- end }}{{ end }} +{{- end }} +{{- $p := getProperty $schema $prop }} +{{- $type := "" }}{{ $array := false }}{{ $map := false }}{{ $yard := "Object" }} +{{- if $ref }} +{{- /* `allOf: [$ref]` is how a description is attached to a reference. */ -}} +{{- if and (not $ref.Ref) $ref.Value (eq (len $ref.Value.AllOf) 1) }}{{ $ref = index $ref.Value.AllOf 0 }}{{ end }} +{{- $target := $ref }} +{{- if and (not $ref.Ref) $ref.Value $ref.Value.Items }}{{ $target = $ref.Value.Items }}{{ $array = true }} +{{- else if and (not $ref.Ref) $ref.Value $ref.Value.AdditionalProperties.Schema }}{{ $target = $ref.Value.AdditionalProperties.Schema }}{{ $map = true }} +{{- end }} +{{- $tv := $target.Value }} +{{- if and $target.Ref (not $tv) }}{{ $tv = get $schemas (refName $target.Ref) }}{{ end }} +{{- with $tv }}{{ with .Type }} +{{- if .Is "string" }}{{ $yard = "String" }} +{{- else if .Is "integer" }}{{ $yard = "Integer" }} +{{- else if .Is "number" }}{{ $yard = "Numeric" }} +{{- else if .Is "boolean" }}{{ $yard = "Boolean" }} +{{- else if .Is "array" }}{{ $yard = "Array" }} +{{- else if .Is "object" }}{{ $yard = "Hash" }} +{{- end }} +{{- end }}{{ end }} +{{- if and $target.Ref $tv (not $tv.Enum) (or $tv.Properties $tv.AllOf (and $tv.Type ($tv.Type.Is "object"))) }} +{{- $type = refName $target.Ref }}{{ $yard = $type }} +{{- end }} +{{- if $array }}{{ $yard = printf "Array<%s>" $yard }}{{ else if $map }}{{ $yard = printf "Hash{Symbol => %s}" $yard }}{{ end }} +{{- end }} +{{- $reader := snakecase $prop }} +{{- if not (regexMatch "^[a-z_][a-z0-9_]*$" $reader) }} +{{- fail (printf "schema %s: property %q cannot name a Ruby reader; rename it in the specification" $name $prop) }} +{{- end }} + # @!attribute [r] {{ $reader }} + # @return [{{ $yard }}, nil]{{ with $p }}{{ with .Description }} {{ regexReplaceAll "[ \t]+\n" (wrapComment . 1000 " # ") "\n" }}{{ end }}{{ end }} + attribute :{{ $reader }} +{{- if $type }}, {{ printf "%q" $type }}{{ end }} +{{- if and $type $array }}, array: true{{ end }} +{{- if and $type $map }}, map: true{{ end }} +{{- if ne $reader $prop }}, key: {{ printf "%q" $prop }}{{ end }} +{{- end }} + end +{{- end }} +{{- end }} + end + end + end + end +end +{{ "" }} +{{- define "doc" -}} +{{- $text := index . 0 -}} +{{- $indent := index . 1 -}} +{{- if $text -}} +{{ $indent }}# {{ regexReplaceAll "[ \t]+\n" (wrapComment $text 1000 (printf "%s# " $indent)) "\n" }} +{{ end -}} +{{- end -}} diff --git a/templates/resources.rb.tmpl b/templates/resources.rb.tmpl new file mode 100644 index 0000000..8da8d91 --- /dev/null +++ b/templates/resources.rb.tmpl @@ -0,0 +1,198 @@ +{{- $ops := .Operations -}} +{{- $module := .Var "module" "Platform" -}} +{{- /* Names a generated method or keyword cannot take: Ruby keywords, the + methods every object has, and the per-call options of the transport. */ -}} +{{- $keywords := list "alias" "and" "begin" "break" "case" "class" "def" "defined" "do" "else" "elsif" "end" "ensure" "false" "for" "if" "in" "module" "next" "nil" "not" "or" "redo" "rescue" "retry" "return" "self" "super" "then" "true" "undef" "unless" "until" "when" "while" "yield" -}} +{{- $objectMethods := list "class" "clone" "display" "dup" "freeze" "hash" "initialize" "inspect" "method" "methods" "send" "tap" "then" "to_s" -}} +{{- $callOptions := list "body" "options" "headers" "base_url" "timeout" -}} +{{- range $op := $ops }} +{{- if not $op.Operation.Tags }} +{{- fail (printf "%s %s has no tag, so no generated class can expose it" $op.Method $op.Path) }} +{{- end }} +{{- $method := snakecase $op.Operation.OperationID }} +{{- if or (not (regexMatch "^[a-z_][a-z0-9_]*$" $method)) (has $method $keywords) (has $method $objectMethods) }} +{{- fail (printf "operation %q cannot name a Ruby method; rename it in the specification" $op.Operation.OperationID) }} +{{- end }} +{{- range $p := concat (pathParameters $op) (queryParameters $op) }} +{{- if or (not (regexMatch "^[a-z_][a-z0-9_]*$" $p.Name)) (has $p.Name $keywords) (has $p.Name $callOptions) }} +{{- fail (printf "%s %s: parameter %q cannot name a Ruby keyword argument; rename it in the specification" $op.Method $op.Path $p.Name) }} +{{- end }} +{{- end }} +{{- range $p := concat $op.Operation.Parameters $op.PathItem.Parameters }}{{ with $p.Value }} +{{- if or (eq .In "header") (eq .In "cookie") }} +{{- fail (printf "%s %s: %s parameter %q is not supported by the templates" $op.Method $op.Path .In .Name) }} +{{- end }} +{{- end }}{{ end }} +{{- end -}} +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. +# +# Loads every generated client of the {{ $module }} API. + +require_relative "models.gen" +{{- range $tag := uniqueTags $ops }} +require_relative "{{ snakecase $tag }}.gen" +{{- end }} +{{- /* A blank line before each marker ends the previous file with a newline. */ -}} +{{- range $tag := uniqueTags $ops }} + +--- {{ snakecase $tag }}.gen.rb +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class {{ $module }} + # Low-level "plumbing" client for the `{{ $tag }}` resource of the + # {{ $module }} API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class {{ pascalcase $tag }}Api + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end +{{- range $op := $ops }} +{{- if has $tag $op.Operation.Tags }} +{{ template "method" $op }} +{{- end }} +{{- end }} + end + end + end + end +end +{{- end }}{{ "\n" }} +{{- define "yard_param_type" -}} +{{- $t := "Object" -}} +{{- with .Schema }}{{ with .Value }}{{ with .Type }} +{{- if .Is "string" }}{{ $t = "String" }} +{{- else if .Is "integer" }}{{ $t = "Integer" }} +{{- else if .Is "number" }}{{ $t = "Numeric" }} +{{- else if .Is "boolean" }}{{ $t = "Boolean" }} +{{- else if .Is "array" }}{{ $t = "Array" }} +{{- end }} +{{- end }}{{ end }}{{ end -}} +{{- if and (eq $t "Object") .Schema .Schema.Value .Schema.Value.Enum }}{{ $t = "String" }}{{ end -}} +{{ $t }} +{{- end -}} +{{- define "method" -}} +{{- $po := . -}} +{{- $op := .Operation -}} +{{- $path := .Path -}} +{{- range pathParameters $po }} +{{- $path = replace (printf "{%s}" .Name) (printf "#{Core::URL.escape_segment(%s)}" .Name) $path }} +{{- end -}} +{{- /* What the success response is: JSON, an event stream, or raw bytes. */ -}} +{{- $sse := false -}} +{{- $oct := false -}} +{{- $ret := responseJSONSchema $op -}} +{{- range $entry := sortedResponseCodes $op.Responses -}} +{{- if or (hasPrefix "2" $entry.Code) (eq $entry.Code "default") -}} +{{- with $entry.Ref }}{{ with .Value }} +{{- with index .Content "text/event-stream" }}{{ if not $sse }}{{ $sse = .Schema }}{{ end }}{{ end -}} +{{- with index .Content "application/octet-stream" }}{{ $oct = true }}{{ end -}} +{{- end }}{{ end -}} +{{- end -}} +{{- end -}} +{{- if $ret }}{{ $sse = false }}{{ $oct = false }}{{ else if $sse }}{{ $ret = $sse }}{{ $oct = false }}{{ end -}} +{{- /* A model to wrap the result in, when the schema names one. */ -}} +{{- $model := "" -}} +{{- if and $ret $ret.Ref $ret.Value (not $ret.Value.Enum) (or $ret.Value.Properties $ret.Value.AllOf (and $ret.Value.Type ($ret.Value.Type.Is "object"))) -}} +{{- $model = printf "Models::%s" (refName $ret.Ref) -}} +{{- end -}} +{{- $body := requestJSONSchema $op -}} +{{- $bodyReq := requestBodyRequired $op -}} +{{- /* GET and HEAD bodies are dropped: the transport refuses them, and the + spec exposes the same filters as repeatable query parameters. See + CONTRIBUTING.md. */ -}} +{{- if or (eq $po.Method "GET") (eq $po.Method "HEAD") }}{{ $body = false }}{{ $bodyReq = false }}{{ end -}} +{{- $query := queryParameters $po -}} +{{- /* The keyword arguments, in one list for the signature and the + enumerator of an event stream. */ -}} +{{- /* Required keywords come first, as Ruby style asks. */ -}} +{{- $args := list -}} +{{- $optional := list -}} +{{- range pathParameters $po }}{{ $args = append $args (printf "%s:" .Name) }}{{ end -}} +{{- range $query }}{{ if .Required }}{{ $args = append $args (printf "%s:" .Name) }}{{ else }}{{ $optional = append $optional (printf "%s: nil" .Name) }}{{ end }}{{ end -}} +{{- if $body }}{{ if $bodyReq }}{{ $args = append $args "body:" }}{{ else }}{{ $optional = append $optional "body: nil" }}{{ end }}{{ end -}} +{{- $args = concat $args $optional -}} +{{- $fwd := list -}} +{{- range pathParameters $po }}{{ $fwd = append $fwd (printf "%s:" .Name) }}{{ end -}} +{{- range $query }}{{ $fwd = append $fwd (printf "%s:" .Name) }}{{ end -}} +{{- if $body }}{{ $fwd = append $fwd "body:" }}{{ end }} +{{- $summary := $op.Summary -}} +{{- if not $summary }}{{ $summary = $op.Description }}{{ end }} + # {{ regexReplaceAll "[ \t]+\n" (wrapComment (default (printf "Call `%s`." $op.OperationID) $summary) 1000 " # ") "\n" }} + # + # `{{ $po.Method }} {{ $po.Path }}` + # +{{- range $p := pathParameters $po }} + # @param {{ $p.Name }} [{{ template "yard_param_type" $p }}]{{ with $p.Description }} {{ regexReplaceAll "[ \t]+\n" (wrapComment . 1000 " # ") "\n" }}{{ end }} +{{- end }} +{{- range $p := $query }} + # @param {{ $p.Name }} [{{ template "yard_param_type" $p }}{{ if not $p.Required }}, nil{{ end }}]{{ with $p.Description }} {{ regexReplaceAll "[ \t]+\n" (wrapComment . 1000 " # ") "\n" }}{{ end }} +{{- end }} +{{- if $body }} + # @param body [{{ if $body.Ref }}Models::{{ refName $body.Ref }}, {{ end }}Hash, Array{{ if not $bodyReq }}, nil{{ end }}] the request body +{{- end }} + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` +{{- if $sse }} + # @yieldparam event [{{ default "Hash" $model }}] each event, as it arrives + # @return [Enumerator, nil] an Enumerator when no block is given +{{- else if $oct }} + # @return [String] the response body, binary +{{- else }} + # @return [{{ default "Hash" $model }}, nil] the response envelope +{{- end }} + # @raise [Unikraft::Cloud::Error] + def {{ snakecase $op.OperationID }}({{ if $args }}{{ join ", " $args }}, {{ end }}**options{{ if $sse }}, &block{{ end }}) +{{- if $sse }} + return enum_for(__method__, {{ if $fwd }}{{ join ", " $fwd }}, {{ end }}**options) unless block + + @client.stream( +{{- else if $oct }} + @client.bytes( +{{- else if $model }} + res = @client.request( +{{- else }} + @client.request( +{{- end }} + method: "{{ $po.Method }}", + path: "{{ $path }}", +{{- if $query }} +{{- /* A list the spec does not explode travels as one comma-separated + value (`?tags=a,b`), not a repeated one. */ -}} +{{- $qs := list }} +{{- range $query }} +{{- if and (.Schema.Value.Type.Is "array") (not (.SerializationMethod).Explode) }} +{{- $qs = append $qs (printf "%s: %s&.join(\",\")" .Name .Name) }} +{{- else }} +{{- $qs = append $qs (printf "%s:" .Name) }} +{{- end }} +{{- end }} + query: { + {{ join ",\n " $qs }} + }, +{{- end }} +{{- if $body }} + body:, +{{- end }} + **options{{ if and $sse (not $model) }}, + &block{{ end }} + ){{ if and $sse $model }} { |event| yield {{ $model }}.from(event) }{{ end }} +{{- if and $model (not $sse) }} + {{ $model }}.from(res) +{{- end }} + end +{{- end -}} From 337ff7854759fa3f6ea696e1e21ae457cf2bdc87 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:55:09 -0800 Subject: [PATCH 13/30] feat(api): Generate the platform and control-plane plumbing Generate lib/unikraft/cloud/api/{platform,controlplane}/*.gen.rb from the prod-staging specs with make generate, and add the hand-written containers: API::Platform and API::ControlPlane hold one client per tag over a shared transport, and API holds both, as ukc.api will. Core::URL.escape_segment encodes path parameters. Signed-off-by: Alexander Jung --- .rubocop.yml | 20 +- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/api.rb | 45 + lib/unikraft/cloud/api/controlplane.rb | 49 + .../cloud/api/controlplane/auth.gen.rb | 83 + .../cloud/api/controlplane/images.gen.rb | 51 + .../cloud/api/controlplane/metros.gen.rb | 45 + .../cloud/api/controlplane/models.gen.rb | 865 +++ .../node_activation_service.gen.rb | 79 + .../api/controlplane/node_service.gen.rb | 276 + .../cloud/api/controlplane/resources.gen.rb | 12 + lib/unikraft/cloud/api/platform.rb | 64 + lib/unikraft/cloud/api/platform/audit.gen.rb | 55 + .../cloud/api/platform/autoscale.gen.rb | 231 + .../cloud/api/platform/certificates.gen.rb | 168 + lib/unikraft/cloud/api/platform/images.gen.rb | 109 + .../cloud/api/platform/instances.gen.rb | 873 +++ lib/unikraft/cloud/api/platform/models.gen.rb | 6456 +++++++++++++++++ lib/unikraft/cloud/api/platform/node.gen.rb | 45 + .../cloud/api/platform/resources.gen.rb | 16 + .../cloud/api/platform/services.gen.rb | 172 + lib/unikraft/cloud/api/platform/users.gen.rb | 134 + .../cloud/api/platform/volumes.gen.rb | 430 ++ lib/unikraft/cloud/core/url.rb | 11 + test/unit/api_test.rb | 138 + 25 files changed, 10425 insertions(+), 3 deletions(-) create mode 100644 lib/unikraft/cloud/api.rb create mode 100644 lib/unikraft/cloud/api/controlplane.rb create mode 100644 lib/unikraft/cloud/api/controlplane/auth.gen.rb create mode 100644 lib/unikraft/cloud/api/controlplane/images.gen.rb create mode 100644 lib/unikraft/cloud/api/controlplane/metros.gen.rb create mode 100644 lib/unikraft/cloud/api/controlplane/models.gen.rb create mode 100644 lib/unikraft/cloud/api/controlplane/node_activation_service.gen.rb create mode 100644 lib/unikraft/cloud/api/controlplane/node_service.gen.rb create mode 100644 lib/unikraft/cloud/api/controlplane/resources.gen.rb create mode 100644 lib/unikraft/cloud/api/platform.rb create mode 100644 lib/unikraft/cloud/api/platform/audit.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/autoscale.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/certificates.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/images.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/instances.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/models.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/node.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/resources.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/services.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/users.gen.rb create mode 100644 lib/unikraft/cloud/api/platform/volumes.gen.rb create mode 100644 test/unit/api_test.rb diff --git a/.rubocop.yml b/.rubocop.yml index 2f4051d..5cc4270 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -16,9 +16,6 @@ Style/StringLiterals: Style/StringLiteralsInInterpolation: EnforcedStyle: double_quotes -Layout/LineLength: - Max: 100 - Style/Documentation: Exclude: - "test/**/*" @@ -45,6 +42,7 @@ Metrics/ClassLength: Max: 200 Exclude: - "test/**/*" + - "lib/**/*.gen.rb" Metrics/BlockLength: Exclude: @@ -57,3 +55,19 @@ Metrics/ParameterLists: Minitest/MultipleAssertions: Max: 8 + +# Generated plumbing: doc comments carry the spec's text verbatim, a class +# holds every operation of its tag, and a named **options keeps the +# YARD @param readable. +Layout/LineLength: + Max: 100 + Exclude: + - "lib/**/*.gen.rb" + +Metrics/ModuleLength: + Exclude: + - "lib/**/*.gen.rb" + +Style/ArgumentsForwarding: + Exclude: + - "lib/**/*.gen.rb" diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index f219b15..d2525dd 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -10,3 +10,4 @@ require_relative "cloud/core/http" require_relative "cloud/core/ready" require_relative "cloud/model" +require_relative "cloud/api" diff --git a/lib/unikraft/cloud/api.rb b/lib/unikraft/cloud/api.rb new file mode 100644 index 0000000..f46a087 --- /dev/null +++ b/lib/unikraft/cloud/api.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# The raw ("plumbing") layer of every Unikraft Cloud API, in one place. +# Everything here mirrors the OpenAPI specification: operations are named +# after their operationId, and responses come back as the untouched envelope. + +require_relative "api/platform" +require_relative "api/controlplane" + +module Unikraft + module Cloud + # Both raw API surfaces, as exposed by `ukc.api`. + # + # @example + # api = Unikraft::Cloud::API.new( + # platform: { base_url: "https://api.fra.unikraft.cloud", token: token }, + # controlplane: { base_url: "https://api.unikraft.cloud", token: token } + # ) + # api.platform.instances.get_instances(count: 10) + # api.controlplane.metros.list_metros + class API + # @return [Platform] the metro-scoped platform API + attr_reader :platform + # @return [ControlPlane] the global control-plane API + attr_reader :controlplane + + # @param platform [Hash, #request] {Core::ApiClient} keywords, or a + # transport to use as is + # @param controlplane [Hash, #request] likewise, for the control plane + def initialize(platform:, controlplane:) + @platform = build(Platform, platform) + @controlplane = build(ControlPlane, controlplane) + end + + private + + def build(klass, config) + config.is_a?(Hash) ? klass.new(**config) : klass.new(config) + end + end + end +end diff --git a/lib/unikraft/cloud/api/controlplane.rb b/lib/unikraft/cloud/api/controlplane.rb new file mode 100644 index 0000000..a82198e --- /dev/null +++ b/lib/unikraft/cloud/api/controlplane.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "../core/http" +require_relative "controlplane/resources.gen" + +module Unikraft + module Cloud + class API + # Every control-plane API resource, raw. The control plane is global: + # it lists metros, checks credentials and manages nodes. + # + # @example + # api = Unikraft::Cloud::API::ControlPlane.new( + # base_url: "https://api.unikraft.cloud", token: ENV["UKC_TOKEN"] + # ) + # api.metros.list_metros.data.metros + class ControlPlane + # @return [#request, #bytes, #stream] the shared transport + attr_reader :client + # @return [AuthApi] authorization checks and sign-in + attr_reader :auth + # @return [ImagesApi] the global image registry + attr_reader :images + # @return [MetrosApi] the metros the account can reach + attr_reader :metros + # @return [NodeServiceApi] nodes + attr_reader :nodes + # @return [NodeActivationServiceApi] node activation and renewal + attr_reader :node_activation + + # @param client [#request, #bytes, #stream, nil] a transport to share; + # when nil, one is built from `config` + # @param config [Hash] {Core::ApiClient#initialize} keywords, e.g. + # `base_url:` and `token:` + def initialize(client = nil, **config) + @client = client || Core::ApiClient.new(**config) + @auth = AuthApi.new(@client) + @images = ImagesApi.new(@client) + @metros = MetrosApi.new(@client) + @nodes = NodeServiceApi.new(@client) + @node_activation = NodeActivationServiceApi.new(@client) + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/controlplane/auth.gen.rb b/lib/unikraft/cloud/api/controlplane/auth.gen.rb new file mode 100644 index 0000000..bfcd01c --- /dev/null +++ b/lib/unikraft/cloud/api/controlplane/auth.gen.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class ControlPlane + # Low-level "plumbing" client for the `Auth` resource of the + # ControlPlane API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class AuthApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Check Authorization of Sign-In Request + # + # `POST /v1/auth/check` + # + # @param body [Models::CheckAuthorizationRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @yieldparam event [Models::CheckAuthorizationResponse] each event, as it arrives + # @return [Enumerator, nil] an Enumerator when no block is given + # @raise [Unikraft::Cloud::Error] + def check_authorization(body:, **options, &block) + return enum_for(__method__, body:, **options) unless block + + @client.stream( + method: "POST", + path: "/v1/auth/check", + body:, + **options + ) { |event| yield Models::CheckAuthorizationResponse.from(event) } + end + + # Get Authorization Status + # + # `GET /v1/auth` + # + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetAuthorizationResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_authorization(**options) + res = @client.request( + method: "GET", + path: "/v1/auth", + **options + ) + Models::GetAuthorizationResponse.from(res) + end + + # Request Sign-In + # + # `POST /v1/auth/signin` + # + # @param body [Models::RequestSigninRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::RequestSigninResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def request_signin(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/auth/signin", + body:, + **options + ) + Models::RequestSigninResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/controlplane/images.gen.rb b/lib/unikraft/cloud/api/controlplane/images.gen.rb new file mode 100644 index 0000000..1ed7e55 --- /dev/null +++ b/lib/unikraft/cloud/api/controlplane/images.gen.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class ControlPlane + # Low-level "plumbing" client for the `Images` resource of the + # ControlPlane API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class ImagesApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # List Images + # + # `GET /v1/images` + # + # @param details [Boolean, nil] Whether to include image tag details. + # @param namespace [Array, nil] Optional namespaces to filter images by. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::ListImagesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def list_images(details: nil, namespace: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/images", + query: { + details:, + namespace: + }, + **options + ) + Models::ListImagesResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/controlplane/metros.gen.rb b/lib/unikraft/cloud/api/controlplane/metros.gen.rb new file mode 100644 index 0000000..93a837b --- /dev/null +++ b/lib/unikraft/cloud/api/controlplane/metros.gen.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class ControlPlane + # Low-level "plumbing" client for the `Metros` resource of the + # ControlPlane API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class MetrosApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Get Metros + # + # `GET /v1/metros` + # + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::ListMetroResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def list_metros(**options) + res = @client.request( + method: "GET", + path: "/v1/metros", + **options + ) + Models::ListMetroResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/controlplane/models.gen.rb b/lib/unikraft/cloud/api/controlplane/models.gen.rb new file mode 100644 index 0000000..69c92d2 --- /dev/null +++ b/lib/unikraft/cloud/api/controlplane/models.gen.rb @@ -0,0 +1,865 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../model" + +module Unikraft + module Cloud + class API + class ControlPlane + # The models of the ControlPlane API, mirroring the wire format. + module Models + # AWSConfig contains AWS-specific configuration for node provisioning. + class AWSConfig < Unikraft::Cloud::Model + # @!attribute [r] vpc_id + # @return [String, nil] The VPC ID where the instance will be launched. If not specified, the + # default VPC for the region will be used. + attribute :vpc_id + # @!attribute [r] subnet_id + # @return [String, nil] The subnet ID where the instance will be launched. If not specified, + # a subnet will be selected from the VPC. + attribute :subnet_id + # @!attribute [r] security_group_ids + # @return [Array, nil] Security group IDs to attach to the instance. If not specified, the + # default security group for the VPC will be used. + attribute :security_group_ids + # @!attribute [r] iam_instance_profile + # @return [String, nil] The IAM instance profile ARN or name to attach to the instance. + attribute :iam_instance_profile + # @!attribute [r] root_volume + # @return [AWSEBSConfig, nil] Root EBS volume configuration. If not specified, provider defaults + # will be used. + attribute :root_volume, "AWSEBSConfig" + # @!attribute [r] additional_volumes + # @return [Array, nil] Additional EBS volumes to attach to the instance. + attribute :additional_volumes, "AWSEBSConfig", array: true + # @!attribute [r] dedicated_host + # @return [Boolean, nil] Whether to use a dedicated host. Dedicated hosts provide visibility and + # control over how instances are placed on physical servers. + attribute :dedicated_host + # @!attribute [r] placement_group + # @return [String, nil] Placement group name for the instance. Placement groups influence how + # instances are placed on underlying hardware. + attribute :placement_group + # @!attribute [r] region + # @return [String, nil] The AWS region where the machine is located. + attribute :region + # @!attribute [r] machine_type + # @return [String, nil] The AWS machine type. This determines the compute resources + # (CPU, memory, etc.) available on the machine. The valid values depend + # on the chosen provider. + attribute :machine_type + end + + # AWSEBSConfig defines the configuration for an AWS EBS volume. + class AWSEBSConfig < Unikraft::Cloud::Model + # @!attribute [r] device_name + # @return [String, nil] The device name (e.g., "/dev/sda1", "/dev/xvdf"). Required for + # additional volumes. + attribute :device_name + # @!attribute [r] size_gib + # @return [Integer, nil] Size of the volume in GiB. + attribute :size_gib + # @!attribute [r] volume_type + # @return [String, nil] The volume type (gp3, gp2, io1, io2, st1, sc1, standard). + attribute :volume_type + # @!attribute [r] iops + # @return [Integer, nil] The number of IOPS. Only valid for io1, io2, and gp3 volumes. + attribute :iops + # @!attribute [r] throughput_mibps + # @return [Integer, nil] The throughput in MiB/s. Only valid for gp3 volumes. + attribute :throughput_mibps + # @!attribute [r] encrypted + # @return [Boolean, nil] Whether the volume should be encrypted. + attribute :encrypted + # @!attribute [r] kms_key_id + # @return [String, nil] The KMS key ID for encryption. If encrypted is true and this is not + # specified, the default EBS encryption key will be used. + attribute :kms_key_id + # @!attribute [r] delete_on_termination + # @return [Boolean, nil] Whether to delete the volume when the instance is terminated. + attribute :delete_on_termination + end + + # The request message for checking authorization given a request ID. + class CheckAuthorizationRequest < Unikraft::Cloud::Model + # @!attribute [r] request_id + # @return [String, nil] The request ID is a unique identifier for the request. This is used to + # track the request in the system and should be provided by the client. + attribute :request_id + end + + # The response message for checking authorization. + class CheckAuthorizationResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [CheckAuthorizationResponseData, nil] The response data for this request. + attribute :data, "CheckAuthorizationResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. This is the time it took to process + # the request and generate the response. + attribute :op_time_us + end + + # The `CheckAuthorizationResponseData` model. + class CheckAuthorizationResponseData < Unikraft::Cloud::Model + # @!attribute [r] token + # @return [String, nil] The authorization token which can be used to authenticate requests. + attribute :token + # @!attribute [r] organization_name + # @return [String, nil] The organization name the token is associated with. + attribute :organization_name + # @!attribute [r] organization_display_name + # @return [String, nil] The display name of the organization the token is associated with. + attribute :organization_display_name + # @!attribute [r] registry + # @return [String, nil] The global image registry. + attribute :registry + # @!attribute [r] organization_uuid + # @return [String, nil] The UUID of the organization the token is associated with. + attribute :organization_uuid + # @!attribute [r] user_uuid + # @return [String, nil] The UUID of the user who approved the login. + attribute :user_uuid + end + + # CloudProvider identifies the cloud infrastructure provider where nodes are + # provisioned. + module CloudProvider + MANUAL = "manual" + AWS = "aws" + + # Every value of this enumeration. + ALL = [MANUAL, AWS].freeze + end + + # CloudProviderConfig contains provider-specific configuration for node + # provisioning. + class CloudProviderConfig < Unikraft::Cloud::Model + # @!attribute [r] aws + # @return [AWSConfig, nil] AWS-specific configuration. + attribute :aws, "AWSConfig" + end + + # Response message for deleting nodes. + class DestroyNodeResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [DestroyNodeResponseData, nil] The response data for this request. + attribute :data, "DestroyNodeResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The `DestroyNodeResponseData` model. + class DestroyNodeResponseData < Unikraft::Cloud::Model + # @!attribute [r] nodes + # @return [Array, nil] The deleted nodes (with their final state before deletion). + attribute :nodes, "Node", array: true + end + + # The response message for getting authorization details. + class GetAuthorizationResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [GetAuthorizationResponseData, nil] The response data for this request. + attribute :data, "GetAuthorizationResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. This is the time it took to process + # the request and generate the response. + attribute :op_time_us + end + + # The `GetAuthorizationResponseData` model. + class GetAuthorizationResponseData < Unikraft::Cloud::Model + # @!attribute [r] organization_name + # @return [String, nil] The organization name the token is associated with. + attribute :organization_name + # @!attribute [r] organization_display_name + # @return [String, nil] The display name of the organization the token is associated with. + attribute :organization_display_name + # @!attribute [r] registry + # @return [String, nil] The global image registry. + attribute :registry + # @!attribute [r] organization_uuid + # @return [String, nil] The UUID of the organization the token is associated with. + attribute :organization_uuid + end + + # The `Image` model. + class Image < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The canonical name of the image. + attribute :name + # @!attribute [r] tags + # @return [Array, nil] The list of tags for the image. Only populated when details are requested. + attribute :tags, "ImageTag", array: true + end + + # The `ImageTag` model. + class ImageTag < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The tag name. + attribute :name + # @!attribute [r] digest + # @return [String, nil] The digest for the tag. + attribute :digest + # @!attribute [r] size + # @return [Integer, nil] The size of the image in bytes. + attribute :size + # @!attribute [r] push_time + # @return [String, nil] The push time of the image. + attribute :push_time + end + + # The `ListImagesResponse` model. + class ListImagesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [ListImagesResponseData, nil] The response data for this request. + attribute :data, "ListImagesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. This is the time it took to process + # the request and generate the response. + attribute :op_time_us + end + + # The `ListImagesResponseData` model. + class ListImagesResponseData < Unikraft::Cloud::Model + # @!attribute [r] images + # @return [Array, nil] The list of images. + attribute :images, "Image", array: true + end + + # Response message for listing machine types. + class ListMachineTypesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [ListMachineTypesResponseData, nil] The response data for this request. + attribute :data, "ListMachineTypesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The `ListMachineTypesResponseData` model. + class ListMachineTypesResponseData < Unikraft::Cloud::Model + # @!attribute [r] machine_types + # @return [Array, nil] The list of available machine types. + attribute :machine_types, "MachineType", array: true + end + + # The `ListMetroResponse` model. + class ListMetroResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [ListMetroResponseData, nil] The response data for this request. + attribute :data, "ListMetroResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. This is the time it took to process + # the request and generate the response. + attribute :op_time_us + end + + # The `ListMetroResponseData` model. + class ListMetroResponseData < Unikraft::Cloud::Model + # @!attribute [r] metros + # @return [Array, nil] The list of metros. + attribute :metros, "Metro", array: true + end + + # Response message for getting nodes. + class ListNodesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [ListNodesResponseData, nil] The response data for this request. + attribute :data, "ListNodesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The `ListNodesResponseData` model. + class ListNodesResponseData < Unikraft::Cloud::Model + # @!attribute [r] nodes + # @return [Array, nil] The list of nodes matching the request. + attribute :nodes, "Node", array: true + # @!attribute [r] total_count + # @return [Integer, nil] Total count of nodes matching the filters (for pagination). + attribute :total_count + end + + # Response message for listing regions. + class ListRegionsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [ListRegionsResponseData, nil] The response data for this request. + attribute :data, "ListRegionsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The `ListRegionsResponseData` model. + class ListRegionsResponseData < Unikraft::Cloud::Model + # @!attribute [r] regions + # @return [Array, nil] The list of available regions. + attribute :regions, "Region", array: true + end + + # Information about an available machine type. + class MachineType < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The machine type identifier (e.g., "m5.xlarge", "n2-standard-4"). + attribute :name + # @!attribute [r] description + # @return [String, nil] Human-readable description. + attribute :description + # @!attribute [r] vcpus + # @return [Integer, nil] Number of vCPUs. + attribute :vcpus + # @!attribute [r] memory_mib + # @return [Integer, nil] Memory in MiB. + attribute :memory_mib + # @!attribute [r] category + # @return [String, nil] Machine category (e.g., "general-purpose", "compute-optimized", + # "memory-optimized"). + attribute :category + # @!attribute [r] available_regions + # @return [Array, nil] Regions where this machine type is available. + attribute :available_regions + # @!attribute [r] nested_virtualization + # @return [Boolean, nil] Whether this machine type supports nested virtualization. + attribute :nested_virtualization + end + + # The `Metro` model. + class Metro < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the metro. + attribute :uuid + # @!attribute [r] endpoint + # @return [String, nil] The API endpoint for the metro. + attribute :endpoint + # @!attribute [r] name + # @return [String, nil] The name of the metro. + attribute :name + # @!attribute [r] iata_code + # @return [String, nil] The IATA code of the metro. + attribute :iata_code + # @!attribute [r] country + # @return [String, nil] The country where the metro is located. + attribute :country + end + + # The operations available on a node's mutable properties. + module MutableNodeOperation + SET = "set" + ADD = "add" + DEL = "del" + + # Every value of this enumeration. + ALL = [SET, ADD, DEL].freeze + end + + # The mutable properties of a node which can be updated. + module MutableNodeProperty + TAGS = "tags" + DELETE_LOCK = "delete_lock" + SSH_KEYS = "ssh_keys" + API_ENDPOINT = "api_endpoint" + + # Every value of this enumeration. + ALL = [TAGS, DELETE_LOCK, SSH_KEYS, API_ENDPOINT].freeze + end + + # An identifier for a resource. Either a name or a UUID. + class NameOrUUID < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + end + + # Node represents a physical or virtual compute node provisioned on a + # cloud provider for use as part of the Unikraft Cloud infrastructure. + # + # Node nodes are the underlying compute resources where Unikraft Cloud + # instances run. They are provisioned on-demand across multiple cloud + # providers and managed through a unified API. + class Node < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the machine. + # + # This is a unique identifier for the machine that is generated when the + # machine is created. The UUID is used to reference the machine in API calls and + # can be used to identify the machine in all API calls that require a machine + # identifier. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the machine. + # + # This is a human-readable name that can be used to identify the machine. + # The name must be unique within the context of your account. The name can + # also be used to identify the machine in API calls. + attribute :name + # @!attribute [r] created_at + # @return [String, nil] The time the machine was created. + attribute :created_at + # @!attribute [r] updated_at + # @return [String, nil] The time the machine was last updated. + attribute :updated_at + # @!attribute [r] state + # @return [String, nil] The current state of the machine. + attribute :state + # @!attribute [r] state_message + # @return [String, nil] An optional message providing additional information about the current + # state, particularly useful for error states. + attribute :state_message + # @!attribute [r] cloudprovider + # @return [String, nil] The cloud provider where this machine is provisioned. + attribute :cloudprovider + # @!attribute [r] vcpus + # @return [Integer, nil] The number of vCPUs available on this machine. + attribute :vcpus + # @!attribute [r] memory_mib + # @return [Integer, nil] The amount of memory in MiB available on this machine. + attribute :memory_mib + # @!attribute [r] ssh_keys + # @return [Array, nil] The SSH keys configured for access to this machine. + attribute :ssh_keys, "SSHKey", array: true + # @!attribute [r] public_ipv4 + # @return [String, nil] The public IPv4 address of the machine, if assigned. + attribute :public_ipv4 + # @!attribute [r] public_ipv6 + # @return [String, nil] The public IPv6 address of the machine, if assigned. + attribute :public_ipv6 + # @!attribute [r] private_ipv4 + # @return [String, nil] The private IPv4 address of the machine within the provider's network. + attribute :private_ipv4 + # @!attribute [r] metro + # @return [String, nil] The Unikraft Cloud metro this machine is associated with. + attribute :metro + # @!attribute [r] provider_instance_id + # @return [String, nil] The provider-specific instance ID or resource identifier. + attribute :provider_instance_id + # @!attribute [r] provider_config + # @return [CloudProviderConfig, nil] Provider-specific configuration that was used to provision this node. + attribute :provider_config, "CloudProviderConfig" + # @!attribute [r] tags + # @return [Hash{Symbol => String}, nil] User-defined tags for organizing and filtering nodes. + attribute :tags + # @!attribute [r] ready_at + # @return [String, nil] The time when the machine became ready (entered READY state). + attribute :ready_at + # @!attribute [r] uptime_seconds + # @return [Integer, nil] The total uptime of the machine in seconds since it became ready. + attribute :uptime_seconds + # @!attribute [r] delete_lock + # @return [Boolean, nil] Whether the machine is protected from deletion. When true, delete operations + # will fail until this is set to false. + attribute :delete_lock + # @!attribute [r] api_endpoint + # @return [String, nil] The API endpoint for the node, used to connect to the node's platform SDK. + attribute :api_endpoint + end + + # The request message for certificate activation. + class NodeActivateRequest < Unikraft::Cloud::Model + # @!attribute [r] csr + # @return [String, nil] The certificate signing request (CSR) for the license which is base64 + # encoded. + attribute :csr + # @!attribute [r] secret + # @return [String, nil] An opaque secret for first-time activation. On renewal (where the node's + # public key is already known), this field is omitted and the CSR + # self-signature is used as proof of key possession. + attribute :secret + # @!attribute [r] serial + # @return [String, nil] The serial number of the last issued certificate. + attribute :serial + end + + # The response message for certificate activation. + class NodeActivateResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] / An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [NodeActivateResponseData, nil] The response data for this request. + attribute :data, "NodeActivateResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The `NodeActivateResponseData` model. + class NodeActivateResponseData < Unikraft::Cloud::Model + # @!attribute [r] license + # @return [String, nil] The issued license certificate in base64 URL encoded PEM format. + attribute :license + end + + # The request message for license deactivation. The caller is identified by + # an HTTP message signature (RFC 9421) made with the node's stable private + # key, the same mechanism used by the private node-facing APIs (e.g. + # NodeHeartbeat) -- not by any field in this message. + class NodeDeactivateRequest < Unikraft::Cloud::Model + # @!attribute [r] serial + # @return [String, nil] The serial number of the last issued certificate. + attribute :serial + end + + # The response message for license deactivation. + class NodeDeactivateResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # NodeState defines the provisioning lifecycle state of a machine which will + # run the Unikraft Cloud Platform. + module NodeState + UNSPECIFIED = "unspecified" + PENDING = "pending" + PROVISIONING = "provisioning" + CONFIGURING = "configuring" + READY = "ready" + DEPROVISIONING = "deprovisioning" + DEPROVISIONED = "deprovisioned" + ERROR = "error" + MAINTENANCE = "maintenance" + + # Every value of this enumeration. + ALL = [UNSPECIFIED, PENDING, PROVISIONING, CONFIGURING, READY, DEPROVISIONING, DEPROVISIONED, ERROR, MAINTENANCE].freeze + end + + # Request message for creating a new node. + class ProvisionNodeRequest < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] Optional name for the node. If not provided, a name will be + # auto-generated. + attribute :name + # @!attribute [r] cloudprovider + # @return [String, nil] The cloud provider where the machine should be provisioned. + attribute :cloudprovider + # @!attribute [r] ssh_keys + # @return [Array, nil] SSH keys for accessing the node. At least one key is required. + attribute :ssh_keys, "SSHKey", array: true + # @!attribute [r] tags + # @return [Hash{Symbol => String}, nil] Optional user-defined tags. + attribute :tags + # @!attribute [r] cloudprovider_config + # @return [CloudProviderConfig, nil] Optional provider-specific configuration for advanced customization. + attribute :cloudprovider_config, "CloudProviderConfig" + # @!attribute [r] metro + # @return [String, nil] The Unikraft Cloud metro to associate this machine with. + attribute :metro + # @!attribute [r] platform_config + # @return [Hash{Symbol => String}, nil] Optional user overrides for platform configuration. Keys should be + # kebab-case (e.g., "vm-user-min-memory"). + attribute :platform_config + # @!attribute [r] image_pulls + # @return [Array, nil] Optional image references to pre-pull on the provisioned machine. + attribute :image_pulls + # @!attribute [r] net_count + # @return [Integer, nil] Optional network count override. If not specified, defaults to 1000. + attribute :net_count + end + + # Response message for creating a node. + class ProvisionNodeResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [ProvisionNodeResponseData, nil] The response data for this request. + attribute :data, "ProvisionNodeResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The `ProvisionNodeResponseData` model. + class ProvisionNodeResponseData < Unikraft::Cloud::Model + # @!attribute [r] node + # @return [Node, nil] The created node. + attribute :node, "Node" + end + + # Information about an available region. + class Region < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The region identifier (e.g., "us-east-1", "us-central1"). + attribute :name + # @!attribute [r] iata + # @return [String, nil] The IATA code for the region. + attribute :iata + end + + # The request message for a sign-in request. + class RequestSigninRequest < Unikraft::Cloud::Model + # @!attribute [r] hostname + # @return [String, nil] The hostname is the name of the machine making the request. This is + # mandatory as it consitutes a unique identifier for the machine. + attribute :hostname + # @!attribute [r] os + # @return [String, nil] The operating system of the machine making the request. + attribute :os + # @!attribute [r] os_version + # @return [String, nil] The version of the operating system of the machine making the request, if + # available. + # + # For Android, it's like "10", "11", "12", etc. For iOS and macOS it's like + # "15.6.1" or "12.4.0". For Windows it's like "10.0.19044.1889". For FreeBSD + # it's like "12.3-STABLE". For Linux, this is simply the kernel version on + # Linux, like "5.10.0-17-amd64". + attribute :os_version + # @!attribute [r] container + # @return [Boolean, nil] A best-effort whether the client is running in a container. + attribute :container + # @!attribute [r] distro + # @return [String, nil] The OS distribution, if known. E.g. "debian", "ubuntu", "nixos", ... + attribute :distro + # @!attribute [r] distro_version + # @return [String, nil] The OS distribution version if known. E.g. "20.04", ... + attribute :distro_version + # @!attribute [r] distro_codename + # @return [String, nil] TThe OS distribution codename if known. E.g. "jammy", "bullseye", ... + attribute :distro_codename + # @!attribute [r] cli_version + # @return [String, nil] The CLI version is the version of the Unikraft CLI that is making the + # request. + attribute :cli_version + # @!attribute [r] goarch + # @return [String, nil] If available, the GOARCH value (of the built binary). + attribute :goarch + # @!attribute [r] goos + # @return [String, nil] If available, the GOOS value (of the built binary) + attribute :goos + # @!attribute [r] go_version + # @return [String, nil] if available, the Go version binary was built with. + attribute :go_version + end + + # The response message for a sign-in request. + class RequestSigninResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [RequestSigninResponseData, nil] The response data for this request. + attribute :data, "RequestSigninResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. This is the time it took to process + # the request and generate the response. + attribute :op_time_us + end + + # The `RequestSigninResponseData` model. + class RequestSigninResponseData < Unikraft::Cloud::Model + # @!attribute [r] authorization_url + # @return [String, nil] The full URL which can be used to remotely confirm the signin. + attribute :authorization_url + # @!attribute [r] request_id + # @return [String, nil] A unique identifier for the request. This can be used to track the + # request in the system. + attribute :request_id + end + + # The error response message for an API request. + class ResponseError < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [Integer, nil] The HTTP status code of the error. + attribute :status + end + + # The response status of an API request. + module ResponseStatus + SUCCESS = "success" + ERROR = "error" + PARTIAL_SUCCESS = "partial_success" + + # Every value of this enumeration. + ALL = [SUCCESS, ERROR, PARTIAL_SUCCESS].freeze + end + + # SSHKey represents an SSH public key for authentication. + class SSHKey < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] A name or label for this SSH key. + attribute :name + # @!attribute [r] public_key + # @return [String, nil] The SSH public key in OpenSSH format (e.g., "ssh-rsa AAAA... user@host" + # or "ssh-ed25519 AAAA... user@host"). + attribute :public_key + end + + # UpdateNodePayload contains the changes to apply to a node. + class UpdateNodePayload < Unikraft::Cloud::Model + # @!attribute [r] property + # @return [String, nil] The property to update. + attribute :property + # @!attribute [r] operation + # @return [String, nil] The operation to perform on the property. + attribute :operation + # @!attribute [r] value + # @return [String, nil] The value for the update operation. The type depends on the property: + # - TAGS: google.protobuf.Struct with key-value pairs + # - DELETE_LOCK: google.protobuf.Value with boolean + # - SSH_KEYS: google.protobuf.ListValue with SSHKey objects + # - API_ENDPOINT: the URL as plain text + attribute :value + end + + # Response message for updating nodes. + class UpdateNodesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [UpdateNodesResponseData, nil] The response data for this request. + attribute :data, "UpdateNodesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The `UpdateNodesResponseData` model. + class UpdateNodesResponseData < Unikraft::Cloud::Model + # @!attribute [r] nodes + # @return [Array, nil] The updated nodes. + attribute :nodes, "Node", array: true + end + + # Response message for wait operations. + class WaitNodesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the response. + attribute :message + # @!attribute [r] data + # @return [WaitNodesResponseData, nil] The response data for this request. + attribute :data, "WaitNodesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The `WaitNodesResponseData` model. + class WaitNodesResponseData < Unikraft::Cloud::Model + # @!attribute [r] nodes + # @return [Array, nil] The nodes after reaching the desired state. + attribute :nodes, "Node", array: true + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/controlplane/node_activation_service.gen.rb b/lib/unikraft/cloud/api/controlplane/node_activation_service.gen.rb new file mode 100644 index 0000000..284332e --- /dev/null +++ b/lib/unikraft/cloud/api/controlplane/node_activation_service.gen.rb @@ -0,0 +1,79 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class ControlPlane + # Low-level "plumbing" client for the `NodeActivationService` resource of the + # ControlPlane API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class NodeActivationServiceApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Activates a new node, or renews an existing node's license. For first-time + # activation, a secret must be provided. For renewal, the CSR self-signature + # is used as proof of key possession and the secret is omitted. + # + # A renewal request may optionally also carry an HTTP message signature + # (RFC 9421) made with the node's current stable private key. When present + # and valid, it authorizes the CSR's public key to become the node's new + # stable identity even if it differs from the current one -- i.e. key + # rotation: prove who you are with the old key, then switch to the new one + # named in the CSR. + # + # `POST /v1/nodes/activate` + # + # @param body [Models::NodeActivateRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::NodeActivateResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def node_activate(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/nodes/activate", + body:, + **options + ) + Models::NodeActivateResponse.from(res) + end + + # Deactivates a node's license so it can no longer renew. The node's + # issued certificate remains valid until it naturally expires -- this + # only prevents renewal. The request must carry an HTTP message signature + # (RFC 9421) made with the node's stable private key; the node is + # identified by the signature, the same mechanism used by the private + # node-facing APIs (e.g. NodeHeartbeat). + # + # `POST /v1/nodes/deactivate` + # + # @param body [Models::NodeDeactivateRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::NodeDeactivateResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def node_deactivate(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/nodes/deactivate", + body:, + **options + ) + Models::NodeDeactivateResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/controlplane/node_service.gen.rb b/lib/unikraft/cloud/api/controlplane/node_service.gen.rb new file mode 100644 index 0000000..a51e22a --- /dev/null +++ b/lib/unikraft/cloud/api/controlplane/node_service.gen.rb @@ -0,0 +1,276 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class ControlPlane + # Low-level "plumbing" client for the `NodeService` resource of the + # ControlPlane API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class NodeServiceApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Delete Node Nodes + # + # `DELETE /v1/nodes` + # + # @param force [Boolean, nil] Force deletion even if nodes are in use. + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DestroyNodeResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def destroy_node(body:, force: nil, **options) + res = @client.request( + method: "DELETE", + path: "/v1/nodes", + query: { + force: + }, + body:, + **options + ) + Models::DestroyNodeResponse.from(res) + end + + # Delete Node Node by UUID + # + # `DELETE /v1/nodes/{uuid}` + # + # @param uuid [String] The UUID of the node to delete. + # @param force [Boolean, nil] Force deletion even if the node is in use. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DestroyNodeResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def destroy_node_by_uuid(uuid:, force: nil, **options) + res = @client.request( + method: "DELETE", + path: "/v1/nodes/#{Core::URL.escape_segment(uuid)}", + query: { + force: + }, + **options + ) + Models::DestroyNodeResponse.from(res) + end + + # Get Node Node by UUID + # + # `GET /v1/nodes/{uuid}` + # + # @param uuid [String] The UUID of the node to retrieve. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::ListNodesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_node_by_uuid(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/nodes/#{Core::URL.escape_segment(uuid)}", + **options + ) + Models::ListNodesResponse.from(res) + end + + # List Machine Types + # + # `GET /v1/nodes/providers/{cloudprovider}/types` + # + # @param cloudprovider [String] The cloud provider to list machine types for. + # @param region [String, nil] Optional region filter. Some providers have region-specific availability. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::ListMachineTypesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def list_machine_types(cloudprovider:, region: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/nodes/providers/#{Core::URL.escape_segment(cloudprovider)}/types", + query: { + region: + }, + **options + ) + Models::ListMachineTypesResponse.from(res) + end + + # List Node Nodes + # + # `GET /v1/nodes` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param cloudprovider [String, nil] Optional filter by cloud provider. + # @param state [String, nil] Optional filter by state. + # @param metro [String, nil] Optional filter by metro. + # @param limit [Integer, nil] Maximum number of results to return. + # @param offset [Integer, nil] Offset for pagination. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::ListNodesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def list_nodes(uuid: nil, name: nil, cloudprovider: nil, state: nil, metro: nil, limit: nil, offset: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/nodes", + query: { + uuid:, + name:, + cloudprovider:, + state:, + metro:, + limit:, + offset: + }, + **options + ) + Models::ListNodesResponse.from(res) + end + + # List Regions + # + # `GET /v1/nodes/providers/{cloudprovider}/regions` + # + # @param cloudprovider [String] The cloud provider to list regions for. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::ListRegionsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def list_regions(cloudprovider:, **options) + res = @client.request( + method: "GET", + path: "/v1/nodes/providers/#{Core::URL.escape_segment(cloudprovider)}/regions", + **options + ) + Models::ListRegionsResponse.from(res) + end + + # Create Node Node + # + # `POST /v1/nodes` + # + # @param body [Models::ProvisionNodeRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::ProvisionNodeResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def provision_node(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/nodes", + body:, + **options + ) + Models::ProvisionNodeResponse.from(res) + end + + # Update Node Node by UUID + # + # `PATCH /v1/nodes/{uuid}` + # + # @param uuid [String] The UUID of the node to update. + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateNodesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_node_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/nodes/#{Core::URL.escape_segment(uuid)}", + body:, + **options + ) + Models::UpdateNodesResponse.from(res) + end + + # Update Node Nodes + # + # `PATCH /v1/nodes` + # + # @param property [Array, nil] The property to update. + # @param operation [Array, nil] The operation to perform on the property. + # @param value [Array, nil] The value for the update operation. The type depends on the property: + # - TAGS: google.protobuf.Struct with key-value pairs + # - DELETE_LOCK: google.protobuf.Value with boolean + # - SSH_KEYS: google.protobuf.ListValue with SSHKey objects + # - API_ENDPOINT: the URL as plain text + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateNodesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_nodes(body:, property: nil, operation: nil, value: nil, **options) + res = @client.request( + method: "PATCH", + path: "/v1/nodes", + query: { + property:, + operation:, + value: + }, + body:, + **options + ) + Models::UpdateNodesResponse.from(res) + end + + # Wait for Node Node State by UUID + # + # `GET /v1/nodes/{uuid}/wait` + # + # @param uuid [String] The UUID of the node to wait for. + # @param states [Array, nil] The desired state(s) to wait for. The request completes when any of + # these states is reached. + # @param timeout_ms [Integer, nil] Timeout in milliseconds. Use -1 for infinite wait. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::WaitNodesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def wait_node_by_uuid(uuid:, states: nil, timeout_ms: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/nodes/#{Core::URL.escape_segment(uuid)}/wait", + query: { + states:, + timeout_ms: + }, + **options + ) + Models::WaitNodesResponse.from(res) + end + + # Wait for Node Nodes States + # + # `GET /v1/nodes/wait` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param states [Array, nil] The desired state(s) to wait for. + # @param timeout_ms [Integer, nil] Timeout in milliseconds. Use -1 for infinite wait. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::WaitNodesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def wait_nodes(uuid: nil, name: nil, states: nil, timeout_ms: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/nodes/wait", + query: { + uuid:, + name:, + states:, + timeout_ms: + }, + **options + ) + Models::WaitNodesResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/controlplane/resources.gen.rb b/lib/unikraft/cloud/api/controlplane/resources.gen.rb new file mode 100644 index 0000000..bdbb075 --- /dev/null +++ b/lib/unikraft/cloud/api/controlplane/resources.gen.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. +# +# Loads every generated client of the ControlPlane API. + +require_relative "models.gen" +require_relative "auth.gen" +require_relative "images.gen" +require_relative "metros.gen" +require_relative "node_activation_service.gen" +require_relative "node_service.gen" diff --git a/lib/unikraft/cloud/api/platform.rb b/lib/unikraft/cloud/api/platform.rb new file mode 100644 index 0000000..aaf5928 --- /dev/null +++ b/lib/unikraft/cloud/api/platform.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "../core/http" +require_relative "platform/resources.gen" + +module Unikraft + module Cloud + class API + # Every platform API resource, raw. The platform API is metro-scoped: + # these clients talk to the one metro their `base_url` names, and a + # single call can be redirected with `base_url:`. Fanning out across + # metros is the porcelain's job. + # + # @example + # api = Unikraft::Cloud::API::Platform.new( + # base_url: "https://api.fra.unikraft.cloud", token: ENV["UKC_TOKEN"] + # ) + # res = api.instances.get_instances(count: 10, details: true) + # res.data.instances + class Platform + # @return [#request, #bytes, #stream] the shared transport + attr_reader :client + # @return [AuditApi] the audit event stream + attr_reader :audit + # @return [AutoscaleApi] autoscale configurations and policies + attr_reader :autoscale + # @return [CertificatesApi] TLS certificates + attr_reader :certificates + # @return [ImagesApi] the image registry (metro-scoped view) + attr_reader :images + # @return [InstancesApi] instances (microVMs) + attr_reader :instances + # @return [NodeApi] metro node information + attr_reader :node + # @return [ServicesApi] service groups (load-balanced networking) + attr_reader :services + # @return [UsersApi] users and quotas + attr_reader :users + # @return [VolumesApi] persistent volumes + attr_reader :volumes + + # @param client [#request, #bytes, #stream, nil] a transport to share; + # when nil, one is built from `config` + # @param config [Hash] {Core::ApiClient#initialize} keywords, e.g. + # `base_url:` and `token:` + def initialize(client = nil, **config) + @client = client || Core::ApiClient.new(**config) + @audit = AuditApi.new(@client) + @autoscale = AutoscaleApi.new(@client) + @certificates = CertificatesApi.new(@client) + @images = ImagesApi.new(@client) + @instances = InstancesApi.new(@client) + @node = NodeApi.new(@client) + @services = ServicesApi.new(@client) + @users = UsersApi.new(@client) + @volumes = VolumesApi.new(@client) + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/audit.gen.rb b/lib/unikraft/cloud/api/platform/audit.gen.rb new file mode 100644 index 0000000..c031ab8 --- /dev/null +++ b/lib/unikraft/cloud/api/platform/audit.gen.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class Platform + # Low-level "plumbing" client for the `audit` resource of the + # Platform API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class AuditApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Subscribe to Audit Events + # + # `GET /v1/audit` + # + # @param events [Array, nil] Deliver only these event types. + # @param uuid [Array, nil] Deliver only events about these object UUIDs. + # @param tags [Array, nil] Deliver only events about objects carrying all of these tags. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @yieldparam event [Models::AuditEvent] each event, as it arrives + # @return [Enumerator, nil] an Enumerator when no block is given + # @raise [Unikraft::Cloud::Error] + def subscribe_audit_events(events: nil, uuid: nil, tags: nil, **options, &block) + return enum_for(__method__, events:, uuid:, tags:, **options) unless block + + @client.stream( + method: "GET", + path: "/v1/audit", + query: { + events: events&.join(","), + uuid: uuid&.join(","), + tags: tags&.join(",") + }, + **options + ) { |event| yield Models::AuditEvent.from(event) } + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/autoscale.gen.rb b/lib/unikraft/cloud/api/platform/autoscale.gen.rb new file mode 100644 index 0000000..899cff6 --- /dev/null +++ b/lib/unikraft/cloud/api/platform/autoscale.gen.rb @@ -0,0 +1,231 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class Platform + # Low-level "plumbing" client for the `autoscale` resource of the + # Platform API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class AutoscaleApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Create Autoscale Configuration by Service Group UUID + # + # `POST /v1/services/{uuid}/autoscale` + # + # @param uuid [String] + # @param body [Models::CreateAutoscaleConfigurationByServiceGroupUUIDRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateAutoscaleConfigurationsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_autoscale_configuration_by_service_group_uuid(uuid:, body:, **options) + res = @client.request( + method: "POST", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}/autoscale", + body:, + **options + ) + Models::CreateAutoscaleConfigurationsResponse.from(res) + end + + # Create Autoscale Configuration Policy + # + # `POST /v1/services/{uuid}/autoscale/policies` + # + # @param uuid [String] + # @param body [Models::CreateAutoscaleConfigurationPolicyRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateAutoscaleConfigurationPolicyResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_autoscale_configuration_policy(uuid:, body:, **options) + res = @client.request( + method: "POST", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}/autoscale/policies", + body:, + **options + ) + Models::CreateAutoscaleConfigurationPolicyResponse.from(res) + end + + # Create Autoscale Configurations + # + # `POST /v1/services/autoscale` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateAutoscaleConfigurationsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_autoscale_configurations(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/services/autoscale", + body:, + **options + ) + Models::CreateAutoscaleConfigurationsResponse.from(res) + end + + # Delete Autoscale Configuration Policies + # + # `DELETE /v1/services/{uuid}/autoscale/policies` + # + # @param uuid [String] + # @param body [Models::DeletePolicyRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteAutoscaleConfigurationPolicyResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_autoscale_configuration_policies(uuid:, body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}/autoscale/policies", + body:, + **options + ) + Models::DeleteAutoscaleConfigurationPolicyResponse.from(res) + end + + # Delete Autoscale Configuration Policy by Name + # + # `DELETE /v1/services/{uuid}/autoscale/policies/{name}` + # + # @param uuid [String] + # @param name [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteAutoscaleConfigurationPolicyResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_autoscale_configuration_policy_by_name(uuid:, name:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}/autoscale/policies/#{Core::URL.escape_segment(name)}", + **options + ) + Models::DeleteAutoscaleConfigurationPolicyResponse.from(res) + end + + # Delete Autoscale Configurations + # + # `DELETE /v1/services/autoscale` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteAutoscaleConfigurationsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_autoscale_configurations(body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/services/autoscale", + body:, + **options + ) + Models::DeleteAutoscaleConfigurationsResponse.from(res) + end + + # Delete Autoscale Configurations by Service Group UUID + # + # `DELETE /v1/services/{uuid}/autoscale` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteAutoscaleConfigurationsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_autoscale_configurations_by_service_group_uuid(uuid:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}/autoscale", + **options + ) + Models::DeleteAutoscaleConfigurationsResponse.from(res) + end + + # List Autoscale Configuration Policies + # + # `GET /v1/services/{uuid}/autoscale/policies` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetAutoscaleConfigurationPolicyResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_autoscale_configuration_policies(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}/autoscale/policies", + **options + ) + Models::GetAutoscaleConfigurationPolicyResponse.from(res) + end + + # Get Autoscale Configuration Policy by Name + # + # `GET /v1/services/{uuid}/autoscale/policies/{name}` + # + # @param uuid [String] + # @param name [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetAutoscaleConfigurationPolicyResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_autoscale_configuration_policy_by_name(uuid:, name:, **options) + res = @client.request( + method: "GET", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}/autoscale/policies/#{Core::URL.escape_segment(name)}", + **options + ) + Models::GetAutoscaleConfigurationPolicyResponse.from(res) + end + + # List Autoscale Configurations + # + # `GET /v1/services/autoscale` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetAutoscaleConfigurationsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_autoscale_configurations(uuid: nil, name: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/services/autoscale", + query: { + uuid:, + name: + }, + **options + ) + Models::GetAutoscaleConfigurationsResponse.from(res) + end + + # Get Autoscale Configurations by Service Group UUID + # + # `GET /v1/services/{uuid}/autoscale` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetAutoscaleConfigurationsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_autoscale_configurations_by_service_group_uuid(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}/autoscale", + **options + ) + Models::GetAutoscaleConfigurationsResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/certificates.gen.rb b/lib/unikraft/cloud/api/platform/certificates.gen.rb new file mode 100644 index 0000000..0554297 --- /dev/null +++ b/lib/unikraft/cloud/api/platform/certificates.gen.rb @@ -0,0 +1,168 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class Platform + # Low-level "plumbing" client for the `certificates` resource of the + # Platform API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class CertificatesApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Create Certificate + # + # `POST /v1/certificates` + # + # @param body [Models::CreateCertificateRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateCertificateResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_certificate(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/certificates", + body:, + **options + ) + Models::CreateCertificateResponse.from(res) + end + + # Delete Certificate by UUID + # + # `DELETE /v1/certificates/{uuid}` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteCertificatesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_certificate_by_uuid(uuid:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/certificates/#{Core::URL.escape_segment(uuid)}", + **options + ) + Models::DeleteCertificatesResponse.from(res) + end + + # Delete Certificates + # + # `DELETE /v1/certificates` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteCertificatesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_certificates(body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/certificates", + body:, + **options + ) + Models::DeleteCertificatesResponse.from(res) + end + + # Get Certificate by UUID + # + # `GET /v1/certificates/{uuid}` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetCertificatesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_certificate_by_uuid(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/certificates/#{Core::URL.escape_segment(uuid)}", + **options + ) + Models::GetCertificatesResponse.from(res) + end + + # List Certificates + # + # `GET /v1/certificates` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param details [Boolean, nil] + # @param count [Integer, nil] + # @param from [String, nil] + # @param order [String, nil] + # @param sortby [String, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetCertificatesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_certificates(uuid: nil, name: nil, details: nil, count: nil, from: nil, order: nil, sortby: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/certificates", + query: { + uuid:, + name:, + details:, + count:, + from:, + order:, + sortby: + }, + **options + ) + Models::GetCertificatesResponse.from(res) + end + + # Update Certificate by UUID + # + # `PUT /v1/certificates/{uuid}` + # + # @param uuid [String] + # @param body [Models::UpdateCertificateByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateCertificatesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_certificate_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/certificates/#{Core::URL.escape_segment(uuid)}", + body:, + **options + ) + Models::UpdateCertificatesResponse.from(res) + end + + # Update Certificates + # + # `PUT /v1/certificates` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateCertificatesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_certificates(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/certificates", + body:, + **options + ) + Models::UpdateCertificatesResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/images.gen.rb b/lib/unikraft/cloud/api/platform/images.gen.rb new file mode 100644 index 0000000..d811810 --- /dev/null +++ b/lib/unikraft/cloud/api/platform/images.gen.rb @@ -0,0 +1,109 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class Platform + # Low-level "plumbing" client for the `images` resource of the + # Platform API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class ImagesApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Get Images in Store + # + # `GET /v1/image-store` + # + # @param digest [String, nil] + # @param tag [String, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetImagesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_image_store(digest: nil, tag: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/image-store", + query: { + digest:, + tag: + }, + **options + ) + Models::GetImagesResponse.from(res) + end + + # Get Images + # + # `GET /v1/images` + # + # @param digest [String, nil] + # @param tag [String, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetImagesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_images(digest: nil, tag: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/images", + query: { + digest:, + tag: + }, + **options + ) + Models::GetImagesResponse.from(res) + end + + # Pin Images + # + # `POST /v1/images` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::PinImagesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def pin_images(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/images", + body:, + **options + ) + Models::PinImagesResponse.from(res) + end + + # Unpin Images + # + # `DELETE /v1/images` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UnpinImagesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def unpin_images(body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/images", + body:, + **options + ) + Models::UnpinImagesResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/instances.gen.rb b/lib/unikraft/cloud/api/platform/instances.gen.rb new file mode 100644 index 0000000..dd6cb60 --- /dev/null +++ b/lib/unikraft/cloud/api/platform/instances.gen.rb @@ -0,0 +1,873 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class Platform + # Low-level "plumbing" client for the `instances` resource of the + # Platform API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class InstancesApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Abort Instance Migration by UUID + # + # `PUT /v1/instances/{uuid}/migrate/abort` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::AbortInstanceMigrationsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def abort_instance_migration_by_uuid(uuid:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}/migrate/abort", + **options + ) + Models::AbortInstanceMigrationsResponse.from(res) + end + + # Abort Instance Migrations + # + # `PUT /v1/instances/migrate/abort` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::AbortInstanceMigrationsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def abort_instance_migrations(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/migrate/abort", + body:, + **options + ) + Models::AbortInstanceMigrationsResponse.from(res) + end + + # Accept Instance Migrations + # + # `PUT /v1/instances/migrate/accept` + # + # @param body [Hash, Array, nil] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::AcceptInstanceMigrationsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def accept_instance_migrations(body: nil, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/migrate/accept", + body:, + **options + ) + Models::AcceptInstanceMigrationsResponse.from(res) + end + + # Create Checkpoint Instances + # + # `POST /v1/instances/checkpoints` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateCheckpointInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_checkpoint_instances(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/instances/checkpoints", + body:, + **options + ) + Models::CreateCheckpointInstancesResponse.from(res) + end + + # Create Instance + # + # `POST /v1/instances` + # + # @param body [Models::CreateInstanceRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateInstanceResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_instance(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/instances", + body:, + **options + ) + Models::CreateInstanceResponse.from(res) + end + + # Create template instances from Instances + # + # `POST /v1/instances/templates` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateTemplateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_template_instances(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/instances/templates", + body:, + **options + ) + Models::CreateTemplateInstancesResponse.from(res) + end + + # Delete Checkpoint Instance by UUID + # + # `DELETE /v1/instances/checkpoints/{uuid}` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteCheckpointInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_checkpoint_instance_by_uuid(uuid:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/instances/checkpoints/#{Core::URL.escape_segment(uuid)}", + **options + ) + Models::DeleteCheckpointInstancesResponse.from(res) + end + + # Delete Checkpoint Instances + # + # `DELETE /v1/instances/checkpoints` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteCheckpointInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_checkpoint_instances(body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/instances/checkpoints", + body:, + **options + ) + Models::DeleteCheckpointInstancesResponse.from(res) + end + + # Delete Instance by UUID + # + # `DELETE /v1/instances/{uuid}` + # + # @param uuid [String] + # @param body [Models::DeleteInstanceByUUIDRequestBody, Hash, Array, nil] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_instance_by_uuid(uuid:, body: nil, **options) + res = @client.request( + method: "DELETE", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}", + body:, + **options + ) + Models::DeleteInstancesResponse.from(res) + end + + # Delete Instances + # + # `DELETE /v1/instances` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_instances(body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/instances", + body:, + **options + ) + Models::DeleteInstancesResponse.from(res) + end + + # Delete template instance by UUID + # + # `DELETE /v1/instances/templates/{uuid}` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteTemplateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_template_instance_by_uuid(uuid:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/instances/templates/#{Core::URL.escape_segment(uuid)}", + **options + ) + Models::DeleteTemplateInstancesResponse.from(res) + end + + # Delete template instances + # + # `DELETE /v1/instances/templates` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteTemplateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_template_instances(body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/instances/templates", + body:, + **options + ) + Models::DeleteTemplateInstancesResponse.from(res) + end + + # Get Checkpoint History + # + # `GET /v1/instances/checkpoints/history` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetCheckpointHistoryResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_checkpoint_history(uuid: nil, name: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/checkpoints/history", + query: { + uuid:, + name: + }, + **options + ) + Models::GetCheckpointHistoryResponse.from(res) + end + + # Get Checkpoint History by UUID + # + # `GET /v1/instances/checkpoints/{uuid}/history` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetCheckpointHistoryResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_checkpoint_history_by_uuid(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/checkpoints/#{Core::URL.escape_segment(uuid)}/history", + **options + ) + Models::GetCheckpointHistoryResponse.from(res) + end + + # Get Checkpoint Instance by UUID + # + # `GET /v1/instances/checkpoints/{uuid}` + # + # @param uuid [String] + # @param details [Boolean, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetCheckpointInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_checkpoint_instance_by_uuid(uuid:, details: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/checkpoints/#{Core::URL.escape_segment(uuid)}", + query: { + details: + }, + **options + ) + Models::GetCheckpointInstancesResponse.from(res) + end + + # List Checkpoint Instances + # + # `GET /v1/instances/checkpoints` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param details [Boolean, nil] + # @param count [Integer, nil] + # @param from [String, nil] + # @param order [String, nil] + # @param sortby [String, nil] + # @param tags [Array, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetCheckpointInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_checkpoint_instances(uuid: nil, name: nil, details: nil, count: nil, from: nil, order: nil, sortby: nil, tags: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/checkpoints", + query: { + uuid:, + name:, + details:, + count:, + from:, + order:, + sortby:, + tags: tags&.join(",") + }, + **options + ) + Models::GetCheckpointInstancesResponse.from(res) + end + + # Get Instance by UUID + # + # `GET /v1/instances/{uuid}` + # + # @param uuid [String] + # @param details [Boolean, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_instance_by_uuid(uuid:, details: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}", + query: { + details: + }, + **options + ) + Models::GetInstancesResponse.from(res) + end + + # Get Instances Checkpoint History + # + # `GET /v1/instances/history` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetCheckpointHistoryResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_instance_history(uuid: nil, name: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/history", + query: { + uuid:, + name: + }, + **options + ) + Models::GetCheckpointHistoryResponse.from(res) + end + + # Get Instance Checkpoint History by UUID + # + # `GET /v1/instances/{uuid}/history` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetCheckpointHistoryResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_instance_history_by_uuid(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}/history", + **options + ) + Models::GetCheckpointHistoryResponse.from(res) + end + + # Get Instances Logs + # + # `GET /v1/instances/log` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param offset [Array, nil] The byte offset of the log output to receive. A negative sign makes the + # offset relative to the end of the log. + # @param limit [Array, nil] The amount of bytes to return at most. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetInstancesLogsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_instance_logs(uuid: nil, name: nil, offset: nil, limit: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/log", + query: { + uuid:, + name:, + offset:, + limit: + }, + **options + ) + Models::GetInstancesLogsResponse.from(res) + end + + # Get Instance Logs by UUID + # + # `GET /v1/instances/{uuid}/log` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetInstancesLogsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_instance_logs_by_uuid(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}/log", + **options + ) + Models::GetInstancesLogsResponse.from(res) + end + + # Get Instances Metrics + # + # `GET /v1/instances/metrics` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetInstancesMetricsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_instance_metrics(uuid: nil, name: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/metrics", + query: { + uuid:, + name: + }, + **options + ) + Models::GetInstancesMetricsResponse.from(res) + end + + # Get Instance Metrics by UUID + # + # `GET /v1/instances/{uuid}/metrics` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetInstancesMetricsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_instance_metrics_by_uuid(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}/metrics", + **options + ) + Models::GetInstancesMetricsResponse.from(res) + end + + # List Instances + # + # `GET /v1/instances` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param details [Boolean, nil] + # @param count [Integer, nil] + # @param from [String, nil] + # @param order [String, nil] + # @param sortby [String, nil] + # @param tags [Array, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_instances(uuid: nil, name: nil, details: nil, count: nil, from: nil, order: nil, sortby: nil, tags: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances", + query: { + uuid:, + name:, + details:, + count:, + from:, + order:, + sortby:, + tags: tags&.join(",") + }, + **options + ) + Models::GetInstancesResponse.from(res) + end + + # Get template instance by UUID + # + # `GET /v1/instances/templates/{uuid}` + # + # @param uuid [String] + # @param details [Boolean, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetTemplateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_template_instance_by_uuid(uuid:, details: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/templates/#{Core::URL.escape_segment(uuid)}", + query: { + details: + }, + **options + ) + Models::GetTemplateInstancesResponse.from(res) + end + + # List template instances + # + # `GET /v1/instances/templates` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param details [Boolean, nil] + # @param count [Integer, nil] + # @param from [String, nil] + # @param order [String, nil] + # @param sortby [String, nil] + # @param tags [Array, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetTemplateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_template_instances(uuid: nil, name: nil, details: nil, count: nil, from: nil, order: nil, sortby: nil, tags: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/templates", + query: { + uuid:, + name:, + details:, + count:, + from:, + order:, + sortby:, + tags: tags&.join(",") + }, + **options + ) + Models::GetTemplateInstancesResponse.from(res) + end + + # Migrate Instance by UUID + # + # `PUT /v1/instances/{uuid}/migrate` + # + # @param uuid [String] + # @param body [Models::MigrateInstanceByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::MigrateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def migrate_instance_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}/migrate", + body:, + **options + ) + Models::MigrateInstancesResponse.from(res) + end + + # Migrate Instances + # + # `PUT /v1/instances/migrate` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::MigrateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def migrate_instances(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/migrate", + body:, + **options + ) + Models::MigrateInstancesResponse.from(res) + end + + # Start Instance by UUID + # + # `PUT /v1/instances/{uuid}/start` + # + # @param uuid [String] + # @param body [Models::StartInstanceByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::StartInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def start_instance_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}/start", + body:, + **options + ) + Models::StartInstancesResponse.from(res) + end + + # Start Instances + # + # `PUT /v1/instances/start` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::StartInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def start_instances(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/start", + body:, + **options + ) + Models::StartInstancesResponse.from(res) + end + + # Stop Instance by UUID + # + # `PUT /v1/instances/{uuid}/stop` + # + # @param uuid [String] + # @param body [Models::StopInstanceByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::StopInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def stop_instance_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}/stop", + body:, + **options + ) + Models::StopInstancesResponse.from(res) + end + + # Stop Instances + # + # `PUT /v1/instances/stop` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::StopInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def stop_instances(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/stop", + body:, + **options + ) + Models::StopInstancesResponse.from(res) + end + + # Suspend Instance by UUID + # + # `PUT /v1/instances/{uuid}/suspend` + # + # @param uuid [String] + # @param body [Models::SuspendInstanceByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::SuspendInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def suspend_instance_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}/suspend", + body:, + **options + ) + Models::SuspendInstancesResponse.from(res) + end + + # Suspend Instances + # + # `PUT /v1/instances/suspend` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::SuspendInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def suspend_instances(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/instances/suspend", + body:, + **options + ) + Models::SuspendInstancesResponse.from(res) + end + + # Update Checkpoint Instance by UUID + # + # `PATCH /v1/instances/checkpoints/{uuid}` + # + # @param uuid [String] + # @param body [Models::UpdateCheckpointInstanceByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateCheckpointInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_checkpoint_instance_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/instances/checkpoints/#{Core::URL.escape_segment(uuid)}", + body:, + **options + ) + Models::UpdateCheckpointInstancesResponse.from(res) + end + + # Update Checkpoint Instances + # + # `PATCH /v1/instances/checkpoints` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateCheckpointInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_checkpoint_instances(body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/instances/checkpoints", + body:, + **options + ) + Models::UpdateCheckpointInstancesResponse.from(res) + end + + # Update Instance by UUID + # + # `PATCH /v1/instances/{uuid}` + # + # @param uuid [String] + # @param body [Models::UpdateInstanceByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_instance_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}", + body:, + **options + ) + Models::UpdateInstancesResponse.from(res) + end + + # Update Instances + # + # `PATCH /v1/instances` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_instances(body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/instances", + body:, + **options + ) + Models::UpdateInstancesResponse.from(res) + end + + # Update template instance by UUID + # + # `PATCH /v1/instances/templates/{uuid}` + # + # @param uuid [String] + # @param body [Models::UpdateTemplateInstanceByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateTemplateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_template_instance_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/instances/templates/#{Core::URL.escape_segment(uuid)}", + body:, + **options + ) + Models::UpdateTemplateInstancesResponse.from(res) + end + + # Update template instances + # + # `PATCH /v1/instances/templates` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateTemplateInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_template_instances(body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/instances/templates", + body:, + **options + ) + Models::UpdateTemplateInstancesResponse.from(res) + end + + # Wait for Instance State by UUID + # + # `GET /v1/instances/{uuid}/wait` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::WaitInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def wait_instance_by_uuid(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/#{Core::URL.escape_segment(uuid)}/wait", + **options + ) + Models::WaitInstancesResponse.from(res) + end + + # Wait for Instances States + # + # `GET /v1/instances/wait` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param state [Array, nil] The desired state to wait for. Default is `running`. + # @param timeout_ms [Array, nil] + # @param timeout_s [Array, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::WaitInstancesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def wait_instances(uuid: nil, name: nil, state: nil, timeout_ms: nil, timeout_s: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/instances/wait", + query: { + uuid:, + name:, + state:, + timeout_ms:, + timeout_s: + }, + **options + ) + Models::WaitInstancesResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/models.gen.rb b/lib/unikraft/cloud/api/platform/models.gen.rb new file mode 100644 index 0000000..8a7cebd --- /dev/null +++ b/lib/unikraft/cloud/api/platform/models.gen.rb @@ -0,0 +1,6456 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../model" + +module Unikraft + module Cloud + class API + class Platform + # The models of the Platform API, mirroring the wire format. + module Models + # The operation an event belongs to. + # + # Events sharing an `operation` describe one overarching action, which is what + # makes a state transition attributable to the thing that caused it rather than + # only observable after the fact. + class AuditAttribution < Unikraft::Cloud::Model + # @!attribute [r] operation + # @return [String, nil] UUID shared by every event belonging to the same operation. + attribute :operation + # @!attribute [r] kind + # @return [Object, nil] What was performed on the object. + attribute :kind + # @!attribute [r] trigger + # @return [String, nil] Whether this event was raised by the operation or observed after it. + attribute :trigger + # @!attribute [r] origin + # @return [String, nil] What caused the operation. + attribute :origin + # @!attribute [r] user + # @return [String, nil] The user that caused the operation, when one did. + attribute :user + end + + # One audit event. + class AuditEvent < Unikraft::Cloud::Model + # @!attribute [r] type + # @return [String, nil] The type of event. + attribute :type + # @!attribute [r] timestamp + # @return [String, nil] When the event was raised. + attribute :timestamp + # @!attribute [r] object + # @return [AuditObject, nil] The object the event is about. Absent on `gap`, which names no object. + attribute :object, "AuditObject" + # @!attribute [r] attribution + # @return [AuditAttribution, nil] The operation the event belongs to. + attribute :attribution, "AuditAttribution" + # @!attribute [r] data + # @return [AuditEventData, nil] The event payload. Its fields depend on `type`. + attribute :data, "AuditEventData" + # @!attribute [r] dropped + # @return [Integer, nil] How many events were lost. Only on `gap`. + attribute :dropped + end + + # The payload of an audit event. + # + # Which fields are present depends on the event type: + # + # - `vm.state_change` + # - `vm.start_failed` + class AuditEventData < Unikraft::Cloud::Model + # @!attribute [r] prev + # @return [String, nil] The state before the transition. + attribute :prev + # @!attribute [r] new + # @return [String, nil] The state after the transition. + attribute :new + # @!attribute [r] state + # @return [String, nil] The state the instance was left in after a failed start. + attribute :state + # @!attribute [r] error + # @return [String, nil] The error that failed the start, as an errno name such as `EDQUOT`. + attribute :error + # @!attribute [r] stop + # @return [AuditStop, nil] Why the instance stopped. + attribute :stop, "AuditStop" + end + + # The type of an audit event. + # + # An enum rather than an open union because this is also a query parameter, and + # an open union generates as an interface that a client cannot serialise into a + # filter. Further event types are added here; a Go client decodes one it does + # not know as its plain string value rather than failing. + module AuditEventType + VM_STATE_CHANGE = "vm.state_change" + VM_START_FAILED = "vm.start_failed" + GAP = "gap" + + # Every value of this enumeration. + ALL = [VM_STATE_CHANGE, VM_START_FAILED, GAP].freeze + end + + # The object an audit event is about. + class AuditObject < Unikraft::Cloud::Model + # @!attribute [r] type + # @return [Object, nil] The kind of object. + attribute :type + # @!attribute [r] uuid + # @return [String, nil] The object's UUID. + attribute :uuid + # @!attribute [r] owner + # @return [String, nil] The UUID of the user the object belongs to. + attribute :owner + # @!attribute [r] tags + # @return [Array, nil] The tags set on the object. + attribute :tags + end + + # The kind of object an audit event is about. + # + # Open: the controller emits the ukpd object prefixes, and events for further + # object kinds are added without a breaking change. + module AuditObjectType + I = "i" + V = "v" + + # Every value of this enumeration. + ALL = [I, V].freeze + end + + # What an operation was performed on the object. + # + # Open: the set depends on the object type, and instances carry + # `start`, `stop`, `drain`, `suspend` and `restart`. + module AuditOperationKind + START = "start" + STOP = "stop" + DRAIN = "drain" + SUSPEND = "suspend" + RESTART = "restart" + + # Every value of this enumeration. + ALL = [START, STOP, DRAIN, SUSPEND, RESTART].freeze + end + + # What caused the operation. + module AuditOrigin + UNKNOWN = "unknown" + API = "api" + GUEST = "guest" + PROXY = "proxy" + AUTOSCALE = "autoscale" + SCALE_TO_ZERO = "scale-to-zero" + SCHEDULED_OP = "scheduled-op" + RESTART = "restart" + UPDATE = "update" + SYSTEM = "system" + NETWORK = "network" + AUTOKILL = "autokill" + MTSS = "mtss" + + # Every value of this enumeration. + ALL = [UNKNOWN, API, GUEST, PROXY, AUTOSCALE, SCALE_TO_ZERO, SCHEDULED_OP, RESTART, UPDATE, SYSTEM, NETWORK, AUTOKILL, MTSS].freeze + end + + # Why an instance stopped. + class AuditStop < Unikraft::Cloud::Model + # @!attribute [r] reason + # @return [Array, nil] The origins that contributed to the stop. + attribute :reason + # @!attribute [r] code + # @return [Integer, nil] The kernel stop code. + attribute :code + # @!attribute [r] cause + # @return [String, nil] The stop cause. + attribute :cause + end + + # Whether the event was raised by the operation or observed as a result of it. + module AuditTrigger + REQUESTED = "requested" + OBSERVED = "observed" + + # Every value of this enumeration. + ALL = [REQUESTED, OBSERVED].freeze + end + + # AdjustmentType defines the type of adjustment to be made in an autoscaling + # step policy. + module AdjustmentType + CHANGE = "change" + EXACT = "exact" + PERCENTAGE = "percentage" + + # Every value of this enumeration. + ALL = [CHANGE, EXACT, PERCENTAGE].freeze + end + + # AutoscalePolicy defines the autoscale policy for a service. Right now it + # contains fields from both the `ondemand` and `step` policies. They are + # marked both as optional, so only one of them should be set at a time. This + # is a current limitation of the API design. + class AutoscalePolicy < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the policy. + attribute :name + # @!attribute [r] enabled + # @return [Boolean, nil] Whether the policy is enabled. + attribute :enabled + # @!attribute [r] metric + # @return [String, nil] Metric to use for the step policy (only for step policies). + attribute :metric + # @!attribute [r] adjustment_type + # @return [String, nil] The type of adjustment to be made in the step policy (only for step policies). + attribute :adjustment_type + # @!attribute [r] steps + # @return [Array, nil] The steps for the step policy. Each step defines an adjustment value and + # optional bounds. + attribute :steps, "AutoscalePolicyStep", array: true + end + + # A single step in a step autoscaling policy. + class AutoscalePolicyStep < Unikraft::Cloud::Model + # @!attribute [r] adjustment + # @return [Integer, nil] The adjustment value for the step. + attribute :adjustment + # @!attribute [r] lower_bound + # @return [Integer, nil] Lower bound for the step. + attribute :lower_bound + # @!attribute [r] upper_bound + # @return [Integer, nil] Upper bound for the step. + attribute :upper_bound + end + + # The `ConfigurationInstanceCreateArgs` model. + class ConfigurationInstanceCreateArgs < Unikraft::Cloud::Model + # @!attribute [r] roms + # @return [InstanceCreateArgsInstanceCreateRequestRoms, nil] The ROM to use for the autoscale configuration. + attribute :roms, "InstanceCreateArgsInstanceCreateRequestRoms" + # @!attribute [r] template + # @return [NameOrUUID, nil] The template to use for the autoscale configuration. + attribute :template, "NameOrUUID" + end + + # The request message to create an autoscale configuration for a service group + # based on its UUID. + class CreateAutoscaleConfigurationByServiceGroupUUIDRequest < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the service to create a configuration for. + attribute :uuid + # @!attribute [r] min_size + # @return [Integer, nil] The minimum number of instances to keep running. + attribute :min_size + # @!attribute [r] max_size + # @return [Integer, nil] The maximum number of instances to keep running. + attribute :max_size + # @!attribute [r] warmup_time_ms + # @return [Integer, nil] The warmup time in milliseconds for new instances. + attribute :warmup_time_ms + # @!attribute [r] cooldown_time_ms + # @return [Integer, nil] The cooldown time in milliseconds for the autoscale configuration. + attribute :cooldown_time_ms + # @!attribute [r] create_args + # @return [CreateAutoscaleConfigurationByServiceGroupUUIDRequestInstanceCreateArgs, nil] The arguments to use when creating instances. + attribute :create_args, "CreateAutoscaleConfigurationByServiceGroupUUIDRequestInstanceCreateArgs" + # @!attribute [r] policies + # @return [Array, nil] The policies to apply to the autoscale configuration. + attribute :policies, "AutoscalePolicy", array: true + end + + # The `CreateAutoscaleConfigurationByServiceGroupUUIDRequestInstanceCreateArgs` model. + class CreateAutoscaleConfigurationByServiceGroupUUIDRequestInstanceCreateArgs < Unikraft::Cloud::Model + # @!attribute [r] roms + # @return [InstanceCreateArgsInstanceCreateRequestRoms, nil] The ROM to use for the autoscale configuration. + attribute :roms, "InstanceCreateArgsInstanceCreateRequestRoms" + # @!attribute [r] template + # @return [NameOrUUID, nil] The template to use for the autoscale configuration. + attribute :template, "NameOrUUID" + end + + # The request message to create an autoscale configuration policy for a + # service. + class CreateAutoscaleConfigurationPolicyRequest < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the policy. + attribute :name + # @!attribute [r] type + # @return [AutoscalePolicy, nil] The policy type to add to the autoscale configuration. + attribute :type, "AutoscalePolicy" + end + + # The `CreateAutoscaleConfigurationPolicyResponse` model. + class CreateAutoscaleConfigurationPolicyResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CreateAutoscaleConfigurationPolicyResponseData, nil] The response data for this request. + attribute :data, "CreateAutoscaleConfigurationPolicyResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class CreateAutoscaleConfigurationPolicyResponseData < Unikraft::Cloud::Model + # @!attribute [r] policies + # @return [Array, nil] + attribute :policies, "CreateAutoscaleConfigurationPolicyResponsePolicy", array: true + end + + # Per-item result for a create autoscale configuration policy operation. + class CreateAutoscaleConfigurationPolicyResponsePolicy < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code providing additional information about the status. + attribute :error + end + + # The `CreateAutoscaleConfigurationsRequestConfiguration` model. + class CreateAutoscaleConfigurationsRequestConfiguration < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] min_size + # @return [Integer, nil] The minimum number of instances to keep running. + attribute :min_size + # @!attribute [r] max_size + # @return [Integer, nil] The maximum number of instances to keep running. + attribute :max_size + # @!attribute [r] warmup_time_ms + # @return [Integer, nil] The warmup time in milliseconds for new instances. + attribute :warmup_time_ms + # @!attribute [r] cooldown_time_ms + # @return [Integer, nil] The cooldown time in milliseconds for the autoscale configuration. + attribute :cooldown_time_ms + # @!attribute [r] create_args + # @return [ConfigurationInstanceCreateArgs, nil] The arguments to use when creating instances. + attribute :create_args, "ConfigurationInstanceCreateArgs" + # @!attribute [r] policies + # @return [Array, nil] The policies to apply to the autoscale configuration. + attribute :policies, "AutoscalePolicy", array: true + end + + # The response to a CreateAutoscaleConfigurationRequest. + class CreateAutoscaleConfigurationsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CreateAutoscaleConfigurationsResponseData, nil] The response data for this request. + attribute :data, "CreateAutoscaleConfigurationsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # Per-item result for a create autoscale configurations operation. + class CreateAutoscaleConfigurationsResponseConfigurationsResponse < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code providing additional information about the status. + attribute :error + end + + # The response data for this request. + class CreateAutoscaleConfigurationsResponseData < Unikraft::Cloud::Model + # @!attribute [r] service_groups + # @return [Array, nil] + attribute :service_groups, "CreateAutoscaleConfigurationsResponseConfigurationsResponse", array: true + end + + # The `DeleteAutoscaleConfigurationPolicyResponse` model. + class DeleteAutoscaleConfigurationPolicyResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DeleteAutoscaleConfigurationPolicyResponseData, nil] The response data for this request. + attribute :data, "DeleteAutoscaleConfigurationPolicyResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class DeleteAutoscaleConfigurationPolicyResponseData < Unikraft::Cloud::Model + # @!attribute [r] policies + # @return [Array, nil] + attribute :policies, "DeleteAutoscaleConfigurationPolicyResponsePoliciesResponse", array: true + end + + # Per-item result for a delete autoscale configuration policy operation. + class DeleteAutoscaleConfigurationPolicyResponsePoliciesResponse < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the deleted policy. + attribute :name + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code providing additional information about the status. + attribute :error + end + + # The `DeleteAutoscaleConfigurationsResponse` model. + class DeleteAutoscaleConfigurationsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DeleteAutoscaleConfigurationsResponseData, nil] The response data for this request. + attribute :data, "DeleteAutoscaleConfigurationsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class DeleteAutoscaleConfigurationsResponseData < Unikraft::Cloud::Model + # @!attribute [r] service_groups + # @return [Array, nil] + attribute :service_groups, "DeleteAutoscaleConfigurationsResponseServiceGroup", array: true + end + + # Per-item result for a delete autoscale configurations operation. + class DeleteAutoscaleConfigurationsResponseServiceGroup < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code providing additional information about the status. + attribute :error + end + + # The request message to delete an autoscale configuration policy by name. + class DeletePolicyRequest < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the policy to delete. + attribute :name + end + + # The request message to get an autoscale configuration policy by name. + class GetAutoscaleConfigurationPolicyRequest < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The Name of the policy to get. + attribute :name + end + + # The `GetAutoscaleConfigurationPolicyResponse` model. + class GetAutoscaleConfigurationPolicyResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetAutoscaleConfigurationPolicyResponseData, nil] The response data for this request. + attribute :data, "GetAutoscaleConfigurationPolicyResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetAutoscaleConfigurationPolicyResponseData < Unikraft::Cloud::Model + # @!attribute [r] policies + # @return [Array, nil] + attribute :policies, "GetAutoscaleConfigurationPolicyResponsePolicyResponse", array: true + end + + # Per-item result for a get autoscale configuration policy operation. + class GetAutoscaleConfigurationPolicyResponsePolicyResponse < Unikraft::Cloud::Model + # @!attribute [r] policy + # @return [AutoscalePolicy, nil] The policy which was retrieved by the request. + attribute :policy, "AutoscalePolicy" + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code providing additional information about the status. + attribute :error + end + + # The response message for a GetAutoscaleConfigurationsRequest. + class GetAutoscaleConfigurationsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetAutoscaleConfigurationsResponseData, nil] The response data for this request. + attribute :data, "GetAutoscaleConfigurationsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetAutoscaleConfigurationsResponseData < Unikraft::Cloud::Model + # @!attribute [r] service_groups + # @return [Array, nil] + attribute :service_groups, "GetAutoscaleConfigurationsResponseServiceGroup", array: true + end + + # Per-item result for a get autoscale configurations operation. + class GetAutoscaleConfigurationsResponseServiceGroup < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] enabled + # @return [Boolean, nil] If the autoscale configuration is enabled. + attribute :enabled + # @!attribute [r] min_size + # @return [Integer, nil] The minimum number of instances to keep running. Only if enabled is true. + attribute :min_size + # @!attribute [r] max_size + # @return [Integer, nil] The maximum number of instances to keep running. Only if enabled is true. + attribute :max_size + # @!attribute [r] warmup_time_ms + # @return [Integer, nil] The warmup time in seconds for new instances. Only if enabled is true. + attribute :warmup_time_ms + # @!attribute [r] cooldown_time_ms + # @return [Integer, nil] The cooldown time in seconds for the autoscale configuration. Only if + # enabled is true. + attribute :cooldown_time_ms + # @!attribute [r] template + # @return [ServiceGroupTemplate, nil] The instance template used for the autoscale configuration. Only if + # enabled is true. + attribute :template, "ServiceGroupTemplate" + # @!attribute [r] policies + # @return [Array, nil] The policies applied to the autoscale configuration. + attribute :policies, "AutoscalePolicy", array: true + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code providing additional information about the status. + attribute :error + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + end + + # The status of the response. + module GetAutoscaleConfigurationsResponseStatus + SUCCESS = "success" + ERROR = "error" + UNCONFIGURED = "unconfigured" + + # Every value of this enumeration. + ALL = [SUCCESS, ERROR, UNCONFIGURED].freeze + end + + # A ROM to use for an autoscale instance create configuration. + class InstanceCreateArgsInstanceCreateRequestRoms < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the ROM. + attribute :name + # @!attribute [r] image + # @return [Object, nil] The image of the ROM to use for the autoscale configuration. Mutually + # exclusive with `files`. Accepts either a plain image reference string + # (`"nginx:latest"`) or an object carrying additional pull configuration + # (`{"url": "nginx:latest", "pull_policy": "always"}`). + attribute :image + # @!attribute [r] files + # @return [Array, nil] Inline files to use as the ROM content. When specified, the platform + # creates an EROFS image from the provided files. Mutually exclusive with + # `image`. + attribute :files, "InlineFile", array: true + end + + # The instance template used for an autoscale configuration. + class ServiceGroupTemplate < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the template used for the autoscale configuration. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the template used for the autoscale configuration. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # The step policy is a type of autoscaling policy that scales the number of + # instances in a service by a fixed number of instances at each step. It uses + # a metric to determine when to scale up or down. + module StepPolicyMetric + CPU = "cpu" + + # Every value of this enumeration. + ALL = [CPU].freeze + end + + # Certificate with per-item response envelope fields merged in. + class Certificate < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] created_at + # @return [String, nil] The time the certificate was created. + attribute :created_at + # @!attribute [r] common_name + # @return [String, nil] The common name (CN) field from the certificate's subject. + # + # This is typically the primary domain name that the certificate is issued + # for. It represents the main identity that the certificate validates. + attribute :common_name + # @!attribute [r] subject + # @return [String, nil] The complete subject distinguished name (DN) of the certificate. + # + # This contains the full subject information from the certificate, including + # the common name, organization, organizational unit, locality, state, and + # country. The subject identifies the entity that the certificate is issued to. + # Only present when the certificate has been issued. + attribute :subject + # @!attribute [r] issuer + # @return [String, nil] The complete issuer distinguished name (DN) of the certificate. + # + # This identifies the Certificate Authority (CA) that issued the certificate. + # It contains information about the CA including its common name, organization, + # and country. + # Only present when the certificate has been issued. + attribute :issuer + # @!attribute [r] serial_number + # @return [String, nil] The unique serial number assigned to the certificate by the issuing CA. + # + # This is a unique identifier within the scope of the issuing CA that can be + # used to identify and track the certificate. Serial numbers are typically + # represented as hexadecimal strings. + # Only present when the certificate has been issued. + attribute :serial_number + # @!attribute [r] not_before + # @return [String, nil] The date and time when the certificate becomes valid. + # + # The certificate should not be trusted before this date. This timestamp + # marks the beginning of the certificate's validity period. + # Only present when the certificate has been issued. + attribute :not_before + # @!attribute [r] not_after + # @return [String, nil] The date and time when the certificate expires. + # + # The certificate should not be trusted after this date. This timestamp + # marks the end of the certificate's validity period. Certificates should + # be renewed before this date to maintain service availability. + # Only present when the certificate has been issued. + attribute :not_after + # @!attribute [r] state + # @return [String, nil] The current state of the certificate. + # + # This indicates whether the certificate is pending issuance, valid and + # ready for use, or in an error state. See CertificateState enum for + # detailed state descriptions. + attribute :state + # @!attribute [r] validation + # @return [CertificateValidation, nil] Validation status when state is pending. + attribute :validation, "CertificateValidation" + # @!attribute [r] service_groups + # @return [Array, nil] Service groups using this certificate. + attribute :service_groups, "ResourceID", array: true + end + + # The current state of a certificate. + # + # The certificate can be in one of the following states: + # + # | State | Description | + # |-----------|-------------| + # | `pending` | The certificate request is pending while the certificate is being requested from the certification authority. During this phase any service using this certificate is not available if this is not a renewal. | + # | `valid` | The certificate is valid and can be used by your services. | + # | `error` | The certificate request failed after multiple attempts. This can happen, for example, if your DNS configuration is not correct, you run into Let's Encrypt™ quota limits, or the domain validation process failed for some other reason. There won't be any further automatic attempts. | + module CertificateState + PENDING = "pending" + VALID = "valid" + ERROR = "error" + + # Every value of this enumeration. + ALL = [PENDING, VALID, ERROR].freeze + end + + # Validation status for a pending certificate. + class CertificateValidation < Unikraft::Cloud::Model + # @!attribute [r] attempt + # @return [Integer, nil] The current validation attempt number. + attribute :attempt + # @!attribute [r] next + # @return [String, nil] The next validation attempt time. + attribute :next + end + + # The request message for creating/uploading a new certificate. + class CreateCertificateRequest < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the resource. If not provided, a random name is generated. + # The name must be unique within the context of your account. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node to place the resource on. If not provided, the + # platform picks one. Only accepted on metros that span multiple nodes. + attribute :node + # @!attribute [r] cn + # @return [String, nil] The common name (CN) of the certificate. + # + # Deprecated: Use `common_name` instead. + attribute :cn + # @!attribute [r] common_name + # @return [String, nil] The common name (CN) of the certificate. + # + # This must be a fully-qualified domain name (FQDN). Exactly one of `cn` + # or `common_name` must be specified. + attribute :common_name + # @!attribute [r] chain + # @return [String, nil] The certificate chain in PEM format. Required for user-uploaded certificates. + attribute :chain + # @!attribute [r] pkey + # @return [String, nil] The private key in PEM format. Required for user-uploaded certificates. + attribute :pkey + end + + # The response message for creating a new certificate. + class CreateCertificateResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CreateCertificateResponseData, nil] The response data for this request. + attribute :data, "CreateCertificateResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class CreateCertificateResponseData < Unikraft::Cloud::Model + # @!attribute [r] certificates + # @return [Array, nil] + attribute :certificates, "Certificate", array: true + end + + # The response message for deleting of one or more certificate(s) given their + # UUID(s) or name(s). + class DeleteCertificatesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DeleteCertificatesResponseData, nil] The response data for this request. + attribute :data, "DeleteCertificatesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class DeleteCertificatesResponseData < Unikraft::Cloud::Model + # @!attribute [r] certificates + # @return [Array, nil] + attribute :certificates, "DeleteCertificatesResponseDeletedCertificate", array: true + end + + # Per-item result for a delete certificates operation. + class DeleteCertificatesResponseDeletedCertificate < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # The response message for getting one or more certificate(s) given their + # UUID(s) or name(s). + class GetCertificatesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetCertificatesResponseData, nil] The response data for this request. + attribute :data, "GetCertificatesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetCertificatesResponseData < Unikraft::Cloud::Model + # @!attribute [r] certificates + # @return [Array, nil] + attribute :certificates, "Certificate", array: true + end + + # The request body for updating a certificate by its UUID or name. + class UpdateCertificateByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] chain + # @return [String, nil] The new certificate chain. This is the public chain of the certificate in + # PEM format. The chain should include the certificate and any intermediate + # certificates. + attribute :chain + # @!attribute [r] pkey + # @return [String, nil] The new private key. This is the private key of the certificate in PEM + # format. The private key must match the public key in the certificate + # chain. + attribute :pkey + end + + # A single update operation to be applied to a certificate. + class UpdateCertificatesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] chain + # @return [String, nil] The new certificate chain. This is the public chain of the certificate in + # PEM format. The chain should include the certificate and any intermediate + # certificates. + attribute :chain + # @!attribute [r] pkey + # @return [String, nil] The new private key. This is the private key of the certificate in PEM + # format. The private key must match the public key in the certificate + # chain. + attribute :pkey + end + + # The response message for updating one or more certificate(s) given their + # UUID(s) or name(s). + class UpdateCertificatesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [UpdateCertificatesResponseData, nil] The response data for this request. + attribute :data, "UpdateCertificatesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class UpdateCertificatesResponseData < Unikraft::Cloud::Model + # @!attribute [r] certificates + # @return [Array, nil] + attribute :certificates, "Certificate", array: true + end + + # Encoding type for inline file data. + module InlineDataEncoding + TEXT = "text" + BASE64 = "base64" + + # Every value of this enumeration. + ALL = [TEXT, BASE64].freeze + end + + # An inline file entry represents a single file within an image. + class InlineFile < Unikraft::Cloud::Model + # @!attribute [r] path + # @return [String, nil] The file path within the image. + attribute :path + # @!attribute [r] encoding + # @return [String, nil] The encoding of the data field. Defaults to "text". + attribute :encoding + # @!attribute [r] data + # @return [String, nil] The file data, encoded according to the encoding field. + attribute :data + end + + # An identifier for a resource — either a name or a UUID, but not both. + class NameOrUUID < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + end + + # The sort order used by list endpoints. + module PaginationOrder + ASC = "asc" + DESC = "desc" + + # Every value of this enumeration. + ALL = [ASC, DESC].freeze + end + + # The sort field used by list endpoints. + module PaginationSortBy + CREATE_TIME = "create_time" + + # Every value of this enumeration. + ALL = [CREATE_TIME].freeze + end + + # Identity fields for a resource, including the node it is placed on. + class ResourceID < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # The error response message for an API request. + class ResponseError < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [Integer, nil] The HTTP status code of the error. + attribute :status + end + + # The response status of an API request. + module ResponseStatus + SUCCESS = "success" + ERROR = "error" + PARTIAL_SUCCESS = "partial_success" + + # Every value of this enumeration. + ALL = [SUCCESS, ERROR, PARTIAL_SUCCESS].freeze + end + + # SchedPriority defines the scheduling priority for an instance. + # User requires the `override_vm_priority` permission to change it. + # + # The list of available scheduling priorities: + # + # | Priority | Description | + # |----------|-------------| + # | `normal` | Default scheduling priority. | + # | `medium` | Medium scheduling priority. | + # | `high` | High scheduling priority. | + # | `admin` | Admin scheduling priority. | + module SchedPriority + NORMAL = "normal" + MEDIUM = "medium" + HIGH = "high" + ADMIN = "admin" + + # Every value of this enumeration. + ALL = [NORMAL, MEDIUM, HIGH, ADMIN].freeze + end + + # The `GetImagesRequestTagOrDigest` model. + class GetImagesRequestTagOrDigest < Unikraft::Cloud::Model + # @!attribute [r] digest + # @return [String, nil] + attribute :digest + # @!attribute [r] tag + # @return [String, nil] + attribute :tag + end + + # The response message for getting one or more image(s). + class GetImagesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetImagesResponseData, nil] The response data for this request. + attribute :data, "GetImagesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetImagesResponseData < Unikraft::Cloud::Model + # @!attribute [r] images + # @return [Array, nil] + attribute :images, "Image", array: true + end + + # An image representing a VM which can be deployed on Unikraft Cloud. + class Image < Unikraft::Cloud::Model + # @!attribute [r] url + # @return [String, nil] The image URL. + attribute :url + # @!attribute [r] created_at + # @return [String, nil] The time the image was created. + attribute :created_at + # @!attribute [r] initrd_or_rom + # @return [Boolean, nil] Whether the image is an initrd or ROM. + attribute :initrd_or_rom + # @!attribute [r] size_in_bytes + # @return [Integer, nil] The size of the image in bytes. + attribute :size_in_bytes + # @!attribute [r] args + # @return [Array, nil] Command-line arguments for the image. + attribute :args + # @!attribute [r] env + # @return [Hash{Symbol => String}, nil] Environment variables for the image. + attribute :env + # @!attribute [r] tags + # @return [Array, nil] Tags associated with the image. + attribute :tags + # @!attribute [r] users + # @return [Array, nil] Users associated with the image. + attribute :users + # @!attribute [r] persistent + # @return [Boolean, nil] Whether the image is pinned and exempt from cache eviction. Only + # populated (and only ever `true`) for callers with image manager + # permissions; omitted otherwise, including when the image is not pinned. + attribute :persistent + end + + # The request item for pinning a single image. + class PinImageRequestItem < Unikraft::Cloud::Model + # @!attribute [r] url + # @return [String, nil] The image URL to pull and pin. + attribute :url + # @!attribute [r] credentials + # @return [String, nil] Optional credentials for authenticating to an OCI registry. + # Only valid for OCI registry URLs; the platform rejects this + # field for non-OCI schemes. + attribute :credentials + # @!attribute [r] headers + # @return [Hash{Symbol => String}, nil] Optional HTTP headers to send when fetching the image. + attribute :headers + # @!attribute [r] pull_policy + # @return [String, nil] Controls when the image is pulled relative to what is already cached on + # the node. If unset, this is inferred from the URL. + attribute :pull_policy + # @!attribute [r] timeout_s + # @return [Integer, nil] Number of seconds to wait for the pull to complete. Required and must + # be non-zero; `-1` waits up to the platform's maximum timeout. + attribute :timeout_s + # @!attribute [r] merge_requests + # @return [Boolean, nil] Avoid duplicate pulls by merging with any in-flight request for the + # same image. Defaults to `true`. + attribute :merge_requests + # @!attribute [r] autokill + # @return [PinImageRequestItemAutokill, nil] Automatically unpin the image after a period of inactivity. + attribute :autokill, "PinImageRequestItemAutokill" + end + + # Automatically unpin the image after a period of inactivity. + class PinImageRequestItemAutokill < Unikraft::Cloud::Model + # @!attribute [r] time_ms + # @return [Integer, nil] Automatically unpin the image after this many milliseconds of + # inactivity. `0` (the default) disables this. + attribute :time_ms + end + + # The response message for pinning one or more images. + class PinImagesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [PinImagesResponseData, nil] The response data for this request. + attribute :data, "PinImagesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class PinImagesResponseData < Unikraft::Cloud::Model + # @!attribute [r] images + # @return [Array, nil] The result of pinning each requested image. + attribute :images, "PinImagesResponseImage", array: true + end + + # The result of pinning a single image. On success, `uuid` through `tags` + # are set; on failure, only `message` and `error` are set (the image + # being pulled is not otherwise identified in the response). + class PinImagesResponseImage < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the image. Only set on success. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the image. Only set on success. + attribute :name + # @!attribute [r] created_at + # @return [String, nil] The time the image was created. Only set on success. + attribute :created_at + # @!attribute [r] state + # @return [String, nil] The current state of the image (e.g. `ready`). Only set on success. + attribute :state + # @!attribute [r] url + # @return [String, nil] The image URL. Only set on success. + attribute :url + # @!attribute [r] persistent + # @return [Boolean, nil] Whether the image is pinned and exempt from cache eviction. Only set + # on success, where it is always `true`. + attribute :persistent + # @!attribute [r] tags + # @return [Array, nil] The tags associated with the image. Only set on success. + attribute :tags + end + + # The request item for unpinning a single image. + class UnpinImageRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the image to unpin. Only UUID is supported; name, URL, + # tag, and digest are not. + attribute :uuid + end + + # The response message for unpinning one or more images. + class UnpinImagesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [UnpinImagesResponseData, nil] The response data for this request. + attribute :data, "UnpinImagesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class UnpinImagesResponseData < Unikraft::Cloud::Model + # @!attribute [r] images + # @return [Array, nil] The result of unpinning each requested image. + attribute :images, "UnpinImagesResponseImage", array: true + end + + # The result of unpinning a single image. + class UnpinImagesResponseImage < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the image. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the image. Only set on success, and only if the image + # has a name. + attribute :name + end + + # The response message for aborting the migration of one or more + # instance(s) given their UUID(s) or name(s). + class AbortInstanceMigrationsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [AbortInstanceMigrationsResponseData, nil] The response data for this request. + attribute :data, "AbortInstanceMigrationsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class AbortInstanceMigrationsResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "AbortInstanceMigrationsResponseItem", array: true + end + + # Per-item result for an abort migrations operation. + class AbortInstanceMigrationsResponseItem < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + end + + # Parameters for accepting a migration on the destination node. + class AcceptInstanceMigrationsRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the instance the token is valid for. If omitted, the token + # is valid for any instance. + attribute :uuid + # @!attribute [r] ttl_s + # @return [Integer, nil] The lifetime of the token until its first use in seconds, at most 3600. + # Uses the default of the node if 0 or omitted. + attribute :ttl_s + end + + # The response message for accepting migrations. + class AcceptInstanceMigrationsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [AcceptInstanceMigrationsResponseData, nil] The response data for this request. + attribute :data, "AcceptInstanceMigrationsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class AcceptInstanceMigrationsResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "AcceptInstanceMigrationsResponseItem", array: true + end + + # Per-item result for an accept migrations operation. + class AcceptInstanceMigrationsResponseItem < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the instance the token is valid for, if one was given. + attribute :uuid + # @!attribute [r] url + # @return [String, nil] The migration URL of this node, to pass to the migrate request. + attribute :url + # @!attribute [r] token + # @return [String, nil] The token for the migration, to pass to the migrate request. + attribute :token + # @!attribute [r] ttl_s + # @return [Integer, nil] The lifetime of the token until its first use in seconds. + attribute :ttl_s + end + + # Automatic delete-on-idle configuration for the checkpoint instance. + class CheckpointAutokill < Unikraft::Cloud::Model + # @!attribute [r] time_ms + # @return [Integer, nil] Time in milliseconds after the checkpoint was last used for restoring + # before it is deleted. A value of 0 disables checkpoint autokill. + attribute :time_ms + end + + # A checkpoint history entry, representing a single checkpoint in the history of an instance. + class CheckpointHistoryEntry < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the checkpoint. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the checkpoint. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] created_at + # @return [String, nil] The time the checkpoint was created. + attribute :created_at + end + + # A single checkpoint creation request. + class CreateCheckpointInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] from + # @return [NameOrUUID, nil] The source instance to create a checkpoint from (by name or UUID). + attribute :from, "NameOrUUID" + # @!attribute [r] name + # @return [String, nil] The name of the checkpoint. If not provided, a name will be generated. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node to place the checkpoint on. Must be the node of the + # source instance. Only accepted on metros that span multiple nodes. + attribute :node + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the checkpoint to be created. + # No wait performed for a value of 0. + attribute :timeout_s + # @!attribute [r] tags + # @return [Array, nil] Tags to associate with the checkpoint. + attribute :tags + # @!attribute [r] autokill + # @return [CheckpointAutokill, nil] Automatic delete-on-idle configuration for the new checkpoint. + attribute :autokill, "CheckpointAutokill" + end + + # The response message for creating one or more checkpoint(s) from existing + # instance(s). + class CreateCheckpointInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CreateCheckpointInstancesResponseData, nil] The response data for this request. + attribute :data, "CreateCheckpointInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # Per-item result for a create checkpoint instances operation. + class CreateCheckpointInstancesResponseCheckpointInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The current state of the checkpoint. + attribute :state + end + + # The response data for this request. + class CreateCheckpointInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] List of checkpoint instances that were created during the operation. + attribute :instances, "CreateCheckpointInstancesResponseCheckpointInstance", array: true + end + + # The request message for creating a new instance. + class CreateInstanceRequest < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the resource. If not provided, a random name is generated. + # The name must be unique within the context of your account. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node to place the resource on. If not provided, the + # platform picks one. Only accepted on metros that span multiple nodes. + attribute :node + # @!attribute [r] image + # @return [Object, nil] The image to use for the instance. + # + # Either an image or a template must be specified. Accepts either a plain + # image reference string (`"nginx:latest"`) or an object carrying additional + # pull configuration (`{"url": "nginx:latest", "pull_policy": "always"}`). + attribute :image + # @!attribute [r] args + # @return [Array, nil] The arguments to pass to the instance when it starts. + attribute :args + # @!attribute [r] env + # @return [Hash{Symbol => String}, nil] Environment variables to set for the instance. + attribute :env + # @!attribute [r] memory_mb + # @return [Integer, nil] Memory in MB to allocate for the instance. Default is 128. + attribute :memory_mb + # @!attribute [r] min_memory_mb + # @return [Integer, nil] Lower bound in MB for memory vertical scaling. Setting this or + # `max_memory_mb` enables memory vertical scaling, which is only supported + # by microVM instances. The instance boots with this amount of memory, and + # `memory_mb` selects the initial allocation within the bounds, defaulting + # to `min_memory_mb`. Must be lower than `max_memory_mb`, and within the + # user's memory limits. Cannot be used with templates that have a + # snapshot, `branch_from` or `checkpoint`. + attribute :min_memory_mb + # @!attribute [r] max_memory_mb + # @return [Integer, nil] Upper bound in MB for memory vertical scaling. Setting this or + # `min_memory_mb` enables memory vertical scaling. Defaults to the user's + # maximum memory limit. Must be higher than `min_memory_mb` by at least + # the platform's memory block size. Cannot be used with templates that + # have a snapshot, `branch_from` or `checkpoint`. + attribute :max_memory_mb + # @!attribute [r] service_group + # @return [CreateInstanceRequestServiceGroup, nil] The service group configuration when creating an instance. + # + # When creating an instance, either a previously created (persistent) + # service group can be referenced (either through its name or UUID), or a + # new (ephemeral) service group can be created for the instance by + # specifying the list of services it should expose and optionally the + # domains it should use. Not used by template instances. + attribute :service_group, "CreateInstanceRequestServiceGroup" + # @!attribute [r] volumes + # @return [Array, nil] Volumes to attach to the instance. + # + # This list can contain both existing and new volumes to create as part of + # the instance creation. Existing volumes can be referenced by their name or + # UUID. New volumes can be created by specifying a name, size in MiB, and + # mount point in the instance. The mount point is the directory in the + # instance where the volume will be mounted. + attribute :volumes, "CreateInstanceRequestVolume", array: true + # @!attribute [r] autostart + # @return [Boolean, nil] Whether the instance should start automatically on creation. + # Must be set to true when `timeout_s` is specified. + attribute :autostart + # @!attribute [r] replicas + # @return [Integer, nil] Number of additional replicas to create. The total number of instances + # created is `replicas + 1`. Defaults to 0. + attribute :replicas + # @!attribute [r] restart_policy + # @return [String, nil] Restart policy for the instance. This defines how the instance + # should behave when it stops or crashes. Cannot be combined with + # the `delete-on-stop` feature. + attribute :restart_policy + # @!attribute [r] scale_to_zero + # @return [CreateInstanceScaleToZero, nil] Scale-to-zero configuration for the instance. Requires + # `service_group` to be set. Cannot be combined with the + # `delete-on-stop` feature. + attribute :scale_to_zero, "CreateInstanceScaleToZero" + # @!attribute [r] vcpus + # @return [Integer, nil] Number of vCPUs to allocate for the instance. Defaults to 1. + attribute :vcpus + # @!attribute [r] min_vcpus + # @return [Integer, nil] Lower bound for vCPU vertical scaling. Setting this or `max_vcpus` + # enables vCPU vertical scaling, which is only supported by microVM + # instances. The instance boots with this number of vCPUs, and `vcpus` + # selects the initial allocation within the bounds, defaulting to + # `min_vcpus`. Must be lower than `max_vcpus`, and within the user's vCPU + # limits. Cannot be used with templates that have a snapshot, + # `branch_from` or `checkpoint`. + attribute :min_vcpus + # @!attribute [r] max_vcpus + # @return [Integer, nil] Upper bound for vCPU vertical scaling. Setting this or `min_vcpus` + # enables vCPU vertical scaling. Defaults to the user's maximum vCPU + # limit. Must be higher than `min_vcpus`. Cannot be used with templates + # that have a snapshot, `branch_from` or `checkpoint`. + attribute :max_vcpus + # @!attribute [r] wait_timeout_ms + # @return [Integer, nil] Deprecated: Use `timeout_s` instead. Timeout in milliseconds to + # wait for all new instances to reach running state. Requires + # `autostart` to be set. If `timeout_s` is not set, this value is + # converted by rounding up to the next full second. No wait + # performed for a value of 0. + attribute :wait_timeout_ms + # @!attribute [r] features + # @return [Array, nil] Features to enable for the instance. Features are specific + # configurations or capabilities that can be enabled for the + # instance. The `scale-to-zero` and `delete-on-stop` features are + # mutually exclusive. + attribute :features + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for all new instances to reach running + # state. Requires `autostart` to be set. If you autostart your + # new instance, you can wait for it to finish starting with a + # blocking API call if you specify a wait timeout greater than + # zero. No wait performed for a value of 0. + attribute :timeout_s + # @!attribute [r] roms + # @return [Array, nil] Read-Only Memory (ROM) blobs to attach to the instance. + # Unikraft Cloud supports the ability to attach Read-Only Memory (ROM) blobs + # to instances. It allows you to create a general-purpose base image and + # then customize individual instances by attaching code or data as separate + # ROM blobs. + attribute :roms, "CreateInstanceRequestRom", array: true + # @!attribute [r] plugins + # @return [Array, nil] Plugins to attach to the instance. Plugins let you attach small helper + # programs to an instance and reach each one over a direct, authenticated + # HTTP endpoint. Each plugin loads from its own ROM image, mounts at + # `/uk/plugins/`, and is reachable at + # `.../v1/instances//plugins//`. At most 8 plugins + # may be attached to an instance. + attribute :plugins, "CreateInstanceRequestPlugin", array: true + # @!attribute [r] tags + # @return [Array, nil] Tags to associate with the instance. + attribute :tags + # @!attribute [r] annotations + # @return [Hash{Symbol => String}, nil] Annotations to associate with the instance. + # + # Unlike tags, annotations also reach the guest: they are included in the + # instance's startdata, and selected keys can be injected into the console + # log output. + # + # Keys follow the Kubernetes annotation key syntax, `[/]`: + # the optional prefix is a non-wildcard DNS subdomain of at most 253 + # characters, and the name is at most 63 characters of `[-_.a-zA-Z0-9]` + # starting and ending with an alphanumeric. Values are unconstrained apart + # from ASCII control characters. An instance holds at most 256 annotations. + # + # When the instance inherits annotations from a template, branch, or + # checkpoint, the given annotations are merged into them rather than + # replacing them. On a key clash the value given here wins. + attribute :annotations + # @!attribute [r] template + # @return [CreateInstanceRequestTemplate, nil] Template instances. + # An existing instance can be saved as a template. This template is then + # used to create new instances that inherit the exact configuration and + # state the original instance had when the template was created. + attribute :template, "CreateInstanceRequestTemplate" + # @!attribute [r] sched_priority + # @return [String, nil] The scheduling priority for the instance. Only settable by + # users with scheduling priority override permissions. + attribute :sched_priority + # @!attribute [r] schedules + # @return [Array, nil] Schedules for the instance. Scheduled operations let you automatically + # start, stop, delete, or exec a command in the instance on a calendar- + # based schedule. For `exec` schedules, set the `args` field to the command + # and its arguments. Each instance stores its own schedules, and cloning + # preserves them. + attribute :schedules, "Schedule", array: true + # @!attribute [r] autokill + # @return [CreateInstanceRequestAutokill, nil] Automatic delete-on-idle/request-limit configuration. Not used for + # template instances. + attribute :autokill, "CreateInstanceRequestAutokill" + # @!attribute [r] hostname + # @return [String, nil] The hostname of the instance. + # + # If not provided, the hostname will be set to the instance name. The + # hostname must be a valid DNS label (e.g., "my-instance") and is used for + # internal DNS resolution within the Unikraft Cloud network. + attribute :hostname + # @!attribute [r] dependencies + # @return [Array, nil] Dependencies of the instance. + # + # A list of instance identifiers (name or UUID) that this instance depends + # on. Dependencies define startup ordering and can be used to ensure that + # prerequisite instances are running before this instance starts. + attribute :dependencies, "NameOrUUID", array: true + # @!attribute [r] branch_from + # @return [NameOrUUID, nil] Reference to an existing instance to branch from. The instance can be + # running or stopped. If the source instance is running, a snapshot will be + # taken asynchronously and the new instance will wait for it to complete + # before starting. Mutually exclusive with `image` and `template`. + attribute :branch_from, "NameOrUUID" + # @!attribute [r] checkpoint + # @return [NameOrUUID, nil] Reference to an existing checkpoint to create the instance from. The + # checkpoint must be in the `checkpoint` state. The new instance will be + # created with the same configuration and state as the checkpoint. Mutually + # exclusive with `image`, `template`, and `branch_from`. + attribute :checkpoint, "NameOrUUID" + # @!attribute [r] gateway + # @return [String, nil] The default gateway to configure inside the guest. + attribute :gateway + # @!attribute [r] nameserver + # @return [String, nil] The DNS resolver to configure inside the guest. + attribute :nameserver + # @!attribute [r] network_interfaces + # @return [Array, nil] Network interfaces to attach to the instance. + attribute :network_interfaces, "CreateInstanceRequestNetworkInterface", array: true + # @!attribute [r] type + # @return [String, nil] The type of virtual machine to use for the instance. Defaults to `micro`, + # which runs on Firecracker. `full` runs on QEMU instead and is required + # for GPU passthrough (see `gpus`) and, in the future, Windows VMs. QEMU- + # backed instances currently do not support scale-to-zero, templates, + # branching, or checkpointing, and only support block-based volumes (no + # virtiofs). Requires a plan with full VM support and cannot be combined + # with `template`, `branch_from`, or `checkpoint`. + attribute :type + # @!attribute [r] gpus + # @return [Integer, nil] Number of GPUs to attach to the instance. Currently restricted to at most + # 1. Requires `type` to be `full` and a plan with GPU support. A GPU stays + # assigned to the instance, even while stopped, until the instance is + # deleted. Cannot be combined with `template`, `branch_from`, or + # `checkpoint`. + attribute :gpus + end + + # Automatic delete-on-idle/request-limit configuration for non-template instances. + class CreateInstanceRequestAutokill < Unikraft::Cloud::Model + # @!attribute [r] time_ms + # @return [Integer, nil] Time in milliseconds after the instance was stopped before it is deleted. + # A value of 0 disables time-based autokill. + attribute :time_ms + # @!attribute [r] num_requests + # @return [Integer, nil] Maximum number of requests/connections the instance serves before it is + # deleted. A value of 0 disables request-based autokill. + attribute :num_requests + end + + # The domain configuration for the service group. A domain defines a publicly + # accessible domain name for the instance. If the domain name ends with a + # period `.`, it must be a valid Fully Qualified Domain Name (FQDN), otherwise + # it will become a subdomain of the target metro. The domain can be associated + # with an existing certificate by specifying the certificate's name or UUID. + # If no certificate is specified and a FQDN is provided, Unikraft Cloud will + # automatically generate a new certificate for the domain based on Let's + # Encrypt and seek to accomplish a DNS-01 challenge. + class CreateInstanceRequestDomain < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] Publicly accessible domain name. + # + # If this name ends in a period `.` it must be a valid Full Qualified + # Domain Name (FQDN), e.g. `example.com.`; otherwise it will become a + # subdomain of the target metro, e.g. `example` becomes + # `example.fra0.unikraft.app`. + attribute :name + # @!attribute [r] certificate + # @return [NameOrUUID, nil] A reference to an existing certificate which can be used for the + # specified domain. If unspecified, Unikraft Cloud will + # automatically generate a new certificate for the domain based on Let's + # Encrypt and seek to accomplish a DNS-01 challenge. + attribute :certificate, "NameOrUUID" + end + + # Network interface configuration for a new instance. + class CreateInstanceRequestNetworkInterface < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The interface name. If omitted, Unikraft Cloud generates one as + # -ethX, falling back to eth- when the + # instance name is too long. + attribute :name + # @!attribute [r] tap_name + # @return [String, nil] The TAP device to attach the interface to. Provide it together + # with ip. + attribute :tap_name + # @!attribute [r] ip + # @return [String, nil] The interface IP address in CIDR notation. Provide it together + # with tap_name to bring your own interface. + attribute :ip + # @!attribute [r] mac + # @return [String, nil] The interface MAC address. Provide it together with tap_name. Must be + # a unicast address outside the platform's address pool. + attribute :mac + # @!attribute [r] autoconfig + # @return [Boolean, nil] Whether the guest configures the interface itself. Defaults to true. + attribute :autoconfig + # @!attribute [r] relay + # @return [NetworkInterfaceRelay, nil] Relay configuration for this interface. + attribute :relay, "NetworkInterfaceRelay" + end + + # A helper program attached to the instance and reachable over a direct, + # authenticated HTTP endpoint. A plugin runs inside the instance next to + # the main application, loads from its own ROM image, and answers requests + # that the Unikraft Cloud API forwards to it. + class CreateInstanceRequestPlugin < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The plugin name. It becomes the `` segment in the plugin + # endpoint (`.../plugins//`). A plugin name has a + # maximum length of 63 characters and contains only letters (`a`-`z`, + # `A`-`Z`), digits (`0`-`9`), hyphen (`-`), and underscore (`_`). + attribute :name + # @!attribute [r] image + # @return [Object, nil] The plugin's image. The platform loads the image, mounts it at + # `/uk/plugins/`, and runs its `init` program when the plugin + # starts. Accepts either a plain image reference string + # (`"user/myplugin:latest"`) or an object carrying additional pull + # configuration (`{"url": "user/myplugin:latest", "pull_policy": "always"}`). + # Exactly one of `image` and `rom` must be set. + attribute :image + # @!attribute [r] rom + # @return [Object, nil] The plugin's image, under its former name. The platform still accepts + # it and adds a deprecation warning to the response. Exactly one of + # `image` and `rom` must be set. + # + # Deprecated: Use `image` instead. + attribute :rom + # @!attribute [r] config + # @return [Object, nil] Arbitrary JSON configuration that the platform passes to the plugin's + # `init` program on `STDIN`. Any JSON value works, including a string, a + # number, or an object. + attribute :config + # @!attribute [r] authorization + # @return [PluginAuthorization, nil] How requests to the plugin endpoint are authenticated. Without it, the + # platform API token of a user with access to the instance (`userdb`) is + # required. The platform checks the token and strips it before forwarding + # the request to the plugin. + attribute :authorization, "PluginAuthorization" + end + + # A ROM to attach when creating an instance. + class CreateInstanceRequestRom < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the ROM to use for the instance configuration. + attribute :name + # @!attribute [r] image + # @return [Object, nil] The image of the ROM to use for the instance configuration. Mutually + # exclusive with `files`. Accepts either a plain image reference string + # (`"nginx:latest"`) or an object carrying additional pull configuration + # (`{"url": "nginx:latest", "pull_policy": "always"}`). + attribute :image + # @!attribute [r] at + # @return [String, nil] The path at which the ROM should be automatically mounted inside the + # instance. When set, the platform mounts the ROM device at the specified + # path so the guest does not need to mount it manually. When omitted, the + # ROM is exposed as a raw block device and the guest is responsible for + # mounting it. + attribute :at + # @!attribute [r] files + # @return [Array, nil] Inline files to use as the ROM content. When specified, the platform + # creates an EROFS image from the provided files. Mutually exclusive with + # `image`. + attribute :files, "InlineFile", array: true + end + + # The service group configuration when creating an instance. If no existing + # (persistent) service group is specified via its identifier, a new + # (ephemeral) service group can be created by specifying the services it + # should expose. A service defines the configuration settings of an exposed + # port by the instance. A service is a combination of a public port, an + # internal port, and a set of handlers that define how the service will handle + # incoming connections. + class CreateInstanceRequestServiceGroup < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] domains + # @return [Array, nil] + attribute :domains, "CreateInstanceRequestDomain", array: true + # @!attribute [r] services + # @return [Array, nil] + attribute :services, "Service", array: true + # @!attribute [r] soft_limit + # @return [Integer, nil] + attribute :soft_limit + # @!attribute [r] hard_limit + # @return [Integer, nil] + attribute :hard_limit + end + + # Template configuration when creating an instance. + class CreateInstanceRequestTemplate < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] prepare + # @return [Boolean, nil] Whether the instance needs to run in order to reach template state + attribute :prepare + # @!attribute [r] create_args + # @return [Instance, nil] Configuration parameters to apply when building the new instance from the + # source template. + attribute :create_args, "Instance" + # @!attribute [r] prepare_timeout_s + # @return [Integer, nil] Timeout in seconds for preparing the template before the preparation is + # aborted. Only applies when `prepare` is set. A value of 0 means no + # timeout. + attribute :prepare_timeout_s + # @!attribute [r] autokill + # @return [TemplateAutokill, nil] Automatic delete-on-idle configuration for the template. Only applies + # when `prepare` is set. + attribute :autokill, "TemplateAutokill" + end + + # A volume defines a storage volume that can be attached to the instance. + class CreateInstanceRequestVolume < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] size_mb + # @return [Integer, nil] + attribute :size_mb + # @!attribute [r] host_path + # @return [String, nil] + attribute :host_path + # @!attribute [r] at + # @return [String, nil] + attribute :at + # @!attribute [r] readonly + # @return [Boolean, nil] + attribute :readonly + # @!attribute [r] quota_policy + # @return [String, nil] + attribute :quota_policy + # @!attribute [r] filesystem + # @return [String, nil] + attribute :filesystem + # @!attribute [r] tags + # @return [Array, nil] + attribute :tags + # @!attribute [r] uid + # @return [Integer, nil] + attribute :uid + # @!attribute [r] gid + # @return [Integer, nil] + attribute :gid + # @!attribute [r] access_mode + # @return [String, nil] + attribute :access_mode + # @!attribute [r] args + # @return [Hash{Symbol => String}, nil] + attribute :args + end + + # The response message for creating a new instance. + class CreateInstanceResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CreateInstanceResponseData, nil] The response data for this request. + attribute :data, "CreateInstanceResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class CreateInstanceResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "Instance", array: true + end + + # Scale-to-zero configuration when creating an instance. + class CreateInstanceScaleToZero < Unikraft::Cloud::Model + # @!attribute [r] policy + # @return [String, nil] The specific policy to use for scaling the instance to zero. + attribute :policy + # @!attribute [r] stateful + # @return [Boolean, nil] Whether the instance should be stateful when scaled to zero. If set to + # true, the instance will retain its state (e.g., RAM contents) when scaled + # to zero. This is useful for instances that need to maintain their state + # across scale-to-zero operations. If set to false, the instance will lose + # its state when scaled to zero, and it will be restarted from scratch when + # scaled back up. + attribute :stateful + # @!attribute [r] cooldown_time_ms + # @return [Integer, nil] The cooldown time in milliseconds before the instance can be scaled to + # zero again. This is useful to prevent rapid scaling to zero and back up, + # which can lead to performance issues or resource exhaustion. + attribute :cooldown_time_ms + # @!attribute [r] notify_time_ms + # @return [Integer, nil] The notification time in milliseconds before the instance is scaled to + # zero. This allows the instance to perform any necessary cleanup or state + # saving before being scaled down. + attribute :notify_time_ms + end + + # A single template instance to be created. + class CreateTemplateInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the template instances to be created. + # A value of -1 means to wait indefinitely until the instance reaches the + # desired state. No wait performed for a value of 0. + attribute :timeout_s + # @!attribute [r] autokill + # @return [ItemAutokill, nil] Automatic delete-on-idle configuration for the new template. + attribute :autokill, "ItemAutokill" + end + + # The response message for converting one or more instance(s) to templates. + class CreateTemplateInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CreateTemplateInstancesResponseData, nil] The response data for this request. + attribute :data, "CreateTemplateInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class CreateTemplateInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "CreateTemplateInstancesResponseTemplateInstance", array: true + end + + # Per-item result for a create template instances operation. + class CreateTemplateInstancesResponseTemplateInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The current state of the instance. + attribute :state + end + + # The response message for deleting one or more checkpoint instance(s) given + # their UUID(s) or name(s). + class DeleteCheckpointInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DeleteCheckpointInstancesResponseData, nil] The response data for this request. + attribute :data, "DeleteCheckpointInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # Per-item result for a delete checkpoint instances operation. + class DeleteCheckpointInstancesResponseCheckpointInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # The response data for this request. + class DeleteCheckpointInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] List of checkpoint instances that were processed during the delete operation. + attribute :instances, "DeleteCheckpointInstancesResponseCheckpointInstance", array: true + end + + # Parameters for deleting the instance by UUID. + class DeleteInstanceByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the instance to be deleted. No wait + # performed for a value of 0. + attribute :timeout_s + # @!attribute [r] dont_retain + # @return [Boolean, nil] Delete immediately without retention. If the instance is already + # being retained, this will force its deletion. Ignored if retention + # for instances is not configured. + attribute :dont_retain + end + + # The request item for deleting an instance by its UUID or name. + class DeleteInstanceRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the instance to be deleted. No wait + # performed for a value of 0. + attribute :timeout_s + # @!attribute [r] dont_retain + # @return [Boolean, nil] Delete immediately without retention. If the instance is already + # being retained, this will force its deletion. Ignored if retention + # for instances is not configured. + attribute :dont_retain + end + + # The response message for deleting one or more instance(s) given their + # UUID(s) or name(s). + class DeleteInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DeleteInstancesResponseData, nil] The response data for this request. + attribute :data, "DeleteInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class DeleteInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "DeleteInstancesResponseInstance", array: true + end + + # Per-item result for a delete instances operation. + class DeleteInstancesResponseInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] previous_state + # @return [String, nil] The previous state of the instance before it was deleted. + attribute :previous_state + end + + # The response message for deleting one or more template instance(s) given + # their UUID(s) or name(s). + class DeleteTemplateInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DeleteTemplateInstancesResponseData, nil] The response data for this request. + attribute :data, "DeleteTemplateInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class DeleteTemplateInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "DeleteTemplateInstancesResponseTemplateInstance", array: true + end + + # Per-item result for a delete template instances operation. + class DeleteTemplateInstancesResponseTemplateInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # The response message for getting the checkpoint history of one or more + # instance(s) given their UUID(s) or name(s). + class GetCheckpointHistoryResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetCheckpointHistoryResponseData, nil] The response data for this request. + attribute :data, "GetCheckpointHistoryResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetCheckpointHistoryResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] The checkpoint histories for the requested instances. + attribute :instances, "GetCheckpointHistoryResponseInstanceHistory", array: true + end + + # Per-item result for a get checkpoint/instance history operation. + class GetCheckpointHistoryResponseInstanceHistory < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] history + # @return [Array, nil] The checkpoint history entries. + attribute :history, "CheckpointHistoryEntry", array: true + end + + # The response message for getting one or more checkpoint instance(s) given + # their UUID(s) or name(s). + class GetCheckpointInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetCheckpointInstancesResponseData, nil] The response data for this request. + attribute :data, "GetCheckpointInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetCheckpointInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] List of checkpoint instances that were retrieved during the operation. + attribute :instances, "Instance", array: true + end + + # The `GetInstanceLogsByUUIDRequestBody` model. + class GetInstanceLogsByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] offset + # @return [Integer, nil] The byte offset of the log output to receive. A negative sign makes the + # offset relative to the end of the log. + attribute :offset + # @!attribute [r] limit + # @return [Integer, nil] The amount of bytes to return at most. + attribute :limit + end + + # A single request item to get an instance's logs. + class GetInstancesLogsRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] offset + # @return [Integer, nil] The byte offset of the log output to receive. A negative sign makes the + # offset relative to the end of the log. + attribute :offset + # @!attribute [r] limit + # @return [Integer, nil] The amount of bytes to return at most. + attribute :limit + end + + # The response message for getting the logs of one or more instance(s) by + # their UUID(s) or name(s). + class GetInstancesLogsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetInstancesLogsResponseData, nil] The response data for this request. + attribute :data, "GetInstancesLogsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # Per-item result for a get instances logs operation. + class GetInstancesLogsResponseAvailable < Unikraft::Cloud::Model + # @!attribute [r] start + # @return [Integer, nil] The first byte offset that can be retrieved. + attribute :start + # @!attribute [r] end + # @return [Integer, nil] The last byte offset that can be retrieved. + attribute :end + end + + # The response data for this request. + class GetInstancesLogsResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "GetInstancesLogsResponseLoggedInstance", array: true + end + + # Per-item result for a get instances logs operation. + class GetInstancesLogsResponseLoggedInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] output + # @return [String, nil] Base64 encoded log output of the instance. + attribute :output + # @!attribute [r] available + # @return [GetInstancesLogsResponseAvailable, nil] Description of the log availability. + attribute :available, "GetInstancesLogsResponseAvailable" + # @!attribute [r] range + # @return [GetInstancesLogsResponseRange, nil] Description of the range that was returned. Useful for requests with + # offset relative to end. + attribute :range, "GetInstancesLogsResponseRange" + # @!attribute [r] state + # @return [String, nil] State of the instance when the logs were retrieved. + attribute :state + end + + # The `GetInstancesLogsResponseRange` model. + class GetInstancesLogsResponseRange < Unikraft::Cloud::Model + # @!attribute [r] start + # @return [Integer, nil] The first retrieved byte. + attribute :start + # @!attribute [r] end + # @return [Integer, nil] The last retrieved byte. + attribute :end + end + + # The response message for getting the metrics of one or more instance(s) by + # their UUID(s) or name(s). + class GetInstancesMetricsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetInstancesMetricsResponseData, nil] The response data for this request. + attribute :data, "GetInstancesMetricsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetInstancesMetricsResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "GetInstancesMetricsResponseInstanceMetrics", array: true + end + + # Per-item result for a get instances metrics operation. + class GetInstancesMetricsResponseInstanceMetrics < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] rss_bytes + # @return [Integer, nil] Resident set size of the VMM in bytes. + # + # The resident set size (RSS) specifies the amount of physical memory that + # has been touched by the instance and is currently reserved for the + # instance on the Unikraft Cloud server. The RSS grows until the instance + # has touched all memory assigned to it via the memory_mb setting and may + # also exceed this value as supporting services running outside the + # instance acquire memory. The RSS is different from the current amount of + # memory allocated by the application, which is likely to fluctuate over + # the lifetime of the application. The RSS is not a cumulative metric. + # When the instance is stopped rss goes down to 0. + attribute :rss_bytes + # @!attribute [r] cpu_time_ms + # @return [Integer, nil] Consumed CPU time in milliseconds. + attribute :cpu_time_ms + # @!attribute [r] boot_time_us + # @return [Integer, nil] The boot time of the instance in microseconds. We take a pragmatic + # approach is to define the boot time. We calculate this as the difference + # in time between the moment the virtualization toolstack is invoked to + # respond to a VM boot request and the moment the OS starts executing user + # code (i.e., the end of the guest OS boot process). This is essentially the + # time that a user would experience in a deployment, minus the application + # initialization time, which we leave out since it is independent from the + # OS. + attribute :boot_time_us + # @!attribute [r] net_time_us + # @return [Integer, nil] This is the time it took for the user-level application to start listening + # on a non-localhost port measured in microseconds. This is the time from + # when the instance started until it reasonably ready to start responding to + # network requests. This is useful for measuring the time it takes for the + # instance to become operationally ready. + attribute :net_time_us + # @!attribute [r] rx_bytes + # @return [Integer, nil] Total amount of bytes received from network. + attribute :rx_bytes + # @!attribute [r] rx_packets + # @return [Integer, nil] Total count of packets received from network. + attribute :rx_packets + # @!attribute [r] tx_bytes + # @return [Integer, nil] Total amount of bytes transmitted over network. + attribute :tx_bytes + # @!attribute [r] tx_packets + # @return [Integer, nil] Total count of packets transmitted over network. + attribute :tx_packets + # @!attribute [r] nconns + # @return [Integer, nil] Number of currently established inbound connections (non-HTTP). + attribute :nconns + # @!attribute [r] nreqs + # @return [Integer, nil] Number of in-flight HTTP requests. + attribute :nreqs + # @!attribute [r] nqueued + # @return [Integer, nil] Number of queued inbound connections and HTTP requests. + attribute :nqueued + # @!attribute [r] ntotal + # @return [Integer, nil] Total number of inbound connections and HTTP requests handled. + attribute :ntotal + end + + # The response message for getting one or more instance(s) given their + # UUID(s) or name(s). + class GetInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetInstancesResponseData, nil] The response data for this request. + attribute :data, "GetInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "Instance", array: true + end + + # The response message for getting one or more template instance(s) given + # their UUID(s) or name(s). + class GetTemplateInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetTemplateInstancesResponseData, nil] The response data for this request. + attribute :data, "GetTemplateInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetTemplateInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "Instance", array: true + end + + # ImageSpec describes an image to use for an instance. + class ImageSpec < Unikraft::Cloud::Model + # @!attribute [r] url + # @return [String, nil] The image URL + attribute :url + # @!attribute [r] credentials + # @return [String, nil] Optional credentials for authenticating to an OCI registry. + # Only valid for OCI registry URLs; the platform rejects this + # field for non-OCI schemes. + attribute :credentials + # @!attribute [r] headers + # @return [Hash{Symbol => String}, nil] Optional HTTP headers to send when fetching the image. + attribute :headers + # @!attribute [r] pull_policy + # @return [String, nil] Controls when the image is pulled relative to what is already cached on + # the node. + attribute :pull_policy + end + + # Instance with per-item response envelope fields merged in. + class Instance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] created_at + # @return [String, nil] The time the instance was created. + attribute :created_at + # @!attribute [r] state + # @return [String, nil] The state of the instance. This indicates the current state of the + # instance, such as whether it is running, stopped, or in an error state. + attribute :state + # @!attribute [r] private_fqdn + # @return [String, nil] The internal hostname of the instance. This address can be used privately + # within the Unikraft Cloud network to access the instance. It is not + # accessible from the public Internet. + attribute :private_fqdn + # @!attribute [r] image + # @return [String, nil] The image used to create the instance. This is a reference to the + # Unikraft image that was used to create the instance. + attribute :image + # @!attribute [r] memory_mb + # @return [Integer, nil] The amount of memory in megabytes allocated for the instance. This is the + # total amount of memory that is available to the instance for its + # operations. + attribute :memory_mb + # @!attribute [r] boot_memory_mb + # @return [Integer, nil] The amount of memory in megabytes the instance boots with. Only present + # if memory vertical scaling is enabled for the instance. + attribute :boot_memory_mb + # @!attribute [r] min_memory_mb + # @return [Integer, nil] The lower bound of memory vertical scaling in megabytes. Only present if + # memory vertical scaling is enabled for the instance. + attribute :min_memory_mb + # @!attribute [r] max_memory_mb + # @return [Integer, nil] The upper bound of memory vertical scaling in megabytes. Only present if + # memory vertical scaling is enabled for the instance. + attribute :max_memory_mb + # @!attribute [r] vcpus + # @return [Integer, nil] The number of vCPUs allocated for the instance. This is the total + # number of virtual CPUs that are available to the instance for its + # operations. + attribute :vcpus + # @!attribute [r] boot_vcpus + # @return [Integer, nil] The number of vCPUs the instance boots with. Only present if vCPU + # vertical scaling is enabled for the instance. + attribute :boot_vcpus + # @!attribute [r] min_vcpus + # @return [Integer, nil] The lower bound of vCPU vertical scaling. Only present if vCPU vertical + # scaling is enabled for the instance. + attribute :min_vcpus + # @!attribute [r] max_vcpus + # @return [Integer, nil] The upper bound of vCPU vertical scaling. Only present if vCPU vertical + # scaling is enabled for the instance. + attribute :max_vcpus + # @!attribute [r] args + # @return [Array, nil] The arguments passed to the instance when it was started. This is a + # list of command-line arguments that were provided to the instance at + # startup. These arguments can be used to configure the behavior of the + # instance and its applications. + attribute :args + # @!attribute [r] env + # @return [Hash{Symbol => String}, nil] Environment variables set for the instance. + attribute :env + # @!attribute [r] start_count + # @return [Integer, nil] The total number of times the instance has been started. This is a counter + # that increments each time the instance is started, regardless of whether it + # was manually stopped or restarted. This can be useful for tracking the + # usage of the instance over time and/or for debugging purposes. + # + # Not used for template instances. + attribute :start_count + # @!attribute [r] restart_count + # @return [Integer, nil] The total number of times the instance has been restarted. This is a counter + # that increments each time the instance has been restarted. This can be + # useful for tracking the usage of the instance over time and/or for + # debugging purposes. + # Not used for template instances. + attribute :restart_count + # @!attribute [r] started_at + # @return [String, nil] The time the instance was started. This is the timestamp when the + # instance was last started. + # Not used for template instances. + attribute :started_at + # @!attribute [r] stopped_at + # @return [String, nil] The time the instance was stopped. This is the timestamp when the + # instance was last stopped. If the instance is currently running, this + # field will be empty. + # Not used for template instances. + attribute :stopped_at + # @!attribute [r] uptime_ms + # @return [Integer, nil] The total amount of time the instance has been running in milliseconds. + # Not used for template instances. + attribute :uptime_ms + # @!attribute [r] retained_until + # @return [String, nil] Time when the instance will be permanently deleted (for deleted instances). + attribute :retained_until + # @!attribute [r] start_prereq_time_us + # @return [Integer, nil] The time taken for the start prerequisites to be fulfilled, measured in + # microseconds from when the instance start was requested. Prerequisites + # are the resources the instance needs before its VM can be launched: the + # kernel and image being available locally, volumes being mounted, and a + # template being ready to resume from. + # Not used for template instances. + attribute :start_prereq_time_us + # @!attribute [r] vmm_prestart_time_us + # @return [Integer, nil] (Developer-only). The time taken between the start being requested and + # the moment the VMM (Virtual Machine Monitor) process is spawned, measured + # in microseconds. This field is primarily used for debugging and + # performance analysis purposes. + # Not used for template instances. + attribute :vmm_prestart_time_us + # @!attribute [r] vmm_start_time_us + # @return [Integer, nil] (Developer-only). The time taken between the main controller and the + # beginning of execution of the VMM (Virtual Machine Monitor) measured in + # microseconds. This field is primarily used for debugging and performance + # analysis purposes. + # Not used for template instances. + attribute :vmm_start_time_us + # @!attribute [r] vmm_load_time_us + # @return [Integer, nil] (Developer-only). The time it took the VMM (Virtual Machine Monitor) to + # load the instance's kernel and initramfs into VM memory measured in + # microseconds. This field is primarily used for debugging and performance + # analysis purposes. + # Not used for template instances. + attribute :vmm_load_time_us + # @!attribute [r] vmm_ready_time_us + # @return [Integer, nil] (Developer-only). The time taken for the VMM (Virtual Machine Monitor) to + # become ready to execute the instance measured in microseconds. This is the + # time from when the VMM started until it was ready to execute the instance's + # code. This field is primarily used for debugging and performance analysis + # purposes. + # Not used for template instances. + attribute :vmm_ready_time_us + # @!attribute [r] boot_time_us + # @return [Integer, nil] The boot time of the instance in microseconds. We take a pragmatic + # approach is to define the boot time. We calculate this as the difference + # in time between the moment the virtualization toolstack is invoked to + # respond to a VM boot request and the moment the OS starts executing user + # code (i.e., the end of the guest OS boot process). This is essentially the + # time that a user would experience in a deployment, minus the application + # initialization time, which we leave out since it is independent from the + # OS. + # Not used for template instances. + attribute :boot_time_us + # @!attribute [r] net_time_us + # @return [Integer, nil] This is the time it took for the user-level application to start listening + # on a non-localhost port measured in microseconds. This is the time from + # when the instance started until it reasonably ready to start responding to + # network requests. This is useful for measuring the time it takes for the + # instance to become operationally ready. + # Not used for template instances. + attribute :net_time_us + # @!attribute [r] template_time_us + # @return [Integer, nil] The time taken for the instance to reach the template state, measured in + # microseconds from when the template was requested. + # Only used for template instances. + attribute :template_time_us + # @!attribute [r] checkpoint_time_us + # @return [Integer, nil] The time taken for the instance to reach the checkpoint state, measured + # in microseconds from when the checkpoint was requested. + # Only used for checkpoint instances. + attribute :checkpoint_time_us + # @!attribute [r] stop_reason + # @return [Integer, nil] The instance stop reason. + # + # Provides reason as to why an instance is stopped or in the process of + # shutting down. The stop reason is a bitmask that tells you the origin of + # the shutdown: + # + # | Bit | 4 | 3 | 2 | 1 | 0 (LSB) | + # |---------|------------|------------|------------|------------|--------------| + # | Purpose | [F]orced | [U]ser | [P]latform | [A]pp | [K]ernel | + # + # - **Forced**: This was a force stop. A forced stop does not give the + # instance a chance to perform a clean shutdown. Bits 0 + # (Kernel) and 1 (App) can thus never be set for forced + # shutdowns. Consequently, there won't be an `exit_code` or + # `stop_code`. + # - **User**: Stop initiated by user, e.g. via an API call. + # - **Platform**: Stop initiated by platform, e.g. an autoscale policy. + # - **App**: The Application exited. The `exit_code` field will be set. + # - **Kernel**: The kernel exited. The `stop_code` field will be set. + # + # For example, the stop reason will contain the following values in the given + # scenarios: + # + # | Value | Bitmask | Aliases | Scenario | + # |-------|---------|---------|----------| + # | 28 | `11100` | `FUP--` | Forced user-initiated shutdown. | + # | 15 | `01111` | `-UPAK` | Regular user-initiated shutdown. The application and kernel have exited. The exit_code and stop_code indicate if the application and kernel shut down cleanly. | + # | 13 | `01101` | `-UP-K` | The user initiated a shutdown but the application was forcefully killed by the kernel during shutdown. This can be the case if the image does not support a clean application exit or the application crashed after receiving a termination signal. The exit_code won’t be present in this scenario. | + # | 7 | `00111` | `--PAK` | Unikraft Cloud initiated the shutdown, for example, due to scale-to-zero. The application and kernel have exited. The exit_code and stop_code indicate if the application and kernel shut down cleanly. | + # | 3 | `00011` | `---AK` | The application exited. The exit_code and stop_code indicate if the application and kernel shut down cleanly. | + # | 1 | `00001` | `----K` | The instance likely expierenced a fatal crash and the stop_code contains more information about the cause of the crash. | + # | 0 | `00000` | `-----` | The stop reason is unknown. | + # Not used for template instances. + attribute :stop_reason + # @!attribute [r] exit_code + # @return [Integer, nil] The application exit code. + # + # This is the code which the application returns upon leaving its main entry + # point. The encoding of the exit code is application specific. See the + # documentation of the application for more details. Usually, an exit code + # of `0` indicates success / no failure. + # Not used for template instances. + attribute :exit_code + # @!attribute [r] stop_code + # @return [Integer, nil] The kernel stop code. + # + # This value encodes multiple details about the stop irrespective of the + # application. + # + # ``` + # MSB LSB + # ┌──────────────┬──────────┬──────────┬───────────┬────────┐ + # │ 31 ────── 24 │ 23 ── 16 │ 15 │ 14 ──── 8 │ 7 ── 0 │ + # ├──────────────┼──────────┼──────────┼───────────┼────────┤ + # │ reserved[^1] │ errno │ shutdown │ initlevel │ reason │ + # └──────────────┴──────────┴──────────┴───────────┴────────┘ + # ``` + # + # - **errno**: The application errno, using Linux's errno.h values. + # (Optional, can be 0.) + # - **shutdown**: Whether the shutdown originated from the inittable (0) or + # from the termtable (1). + # - **initlevel**: The initlevel at the time of the stop. + # - **reason**: The reason for the stop. See `StopCodeReason`. + # + # [^1]: Reserved for future use. + # Not used for template instances. + attribute :stop_code + # @!attribute [r] restart_policy + # @return [String, nil] The restart configuration for the instance. + # + # When an instance stops either because the application exits or the instance + # crashes, Unikraft Cloud can auto-restart your instance. Auto-restarts are + # performed according to the restart policy configured for a particular + # instance. + # + # The policy can have the following values: + # + # | Policy | Description | + # |--------------|-------------| + # | `never` | Never restart the instance (default). | + # | `always` | Always restart the instance when the stop is initiated from within the instance (i.e., the application exits or the instance crashes). | + # | `on-failure` | Only restart the instance if it crashes. | + # + # When an instance stops, the stop reason and the configured restart policy + # are evaluated to decide if a restart should be performed. Unikraft Cloud + # uses an exponential back-off delay (immediate, 5s, 10s, 20s, 40s, ..., 5m) + # to slow down restarts in tight crash loops. If an instance runs without + # problems for 10s the back-off delay is reset and the restart sequence ends. + # + # The `restart.attempt` attribute reported in counts the number of restarts + # performed in the current sequence. The `restart.next_at` field indicates + # when the next restart will take place if a back-off delay is in effect. + # + # A manual start or stop of the instance aborts the restart sequence and + # resets the back-off delay. + attribute :restart_policy + # @!attribute [r] scale_to_zero + # @return [InstanceScaleToZero, nil] The scale-to-zero configuration for the instance. + # + # With conventional cloud platforms you need to keep at least one instance + # running at all times to be able to respond to incoming requests. Performing + # a just-in-time cold boot is simply too time-consuming and would create a + # response latency of multiple seconds. This is not the case with Unikraft + # Cloud. Instances on Unikraft Cloud are able to cold boot within + # milliseconds, which allows us to perform low-latency scale-to-zero. + # + # To enable scale-to-zero for an instance it is sufficient to add a + # `scale_to_zero` configuration block. Unikraft Cloud will then put the + # instance into standby if there is no traffic to your service within the + # window of a cooldown period. When there is new traffic coming in, it is + # automatically started again. + # + # If you have a heavyweight application that takes long to cold boot or has + # bad first request latency (e.g., with JIT compilation) consider to enable + # stateful scale-to-zero. + attribute :scale_to_zero, "InstanceScaleToZero" + # @!attribute [r] service_group + # @return [InstanceServiceGroup, nil] The service group configuration for the instance. + attribute :service_group, "InstanceServiceGroup" + # @!attribute [r] services + # @return [Array, nil] Services exposed by this instance (format: "protocol:port"). + attribute :services + # @!attribute [r] volumes + # @return [Array, nil] The list of volumes attached to the instance. + attribute :volumes, "InstanceVolume", array: true + # @!attribute [r] network_interfaces + # @return [Array, nil] The network interfaces of the instance. + # Not used for template instances. + attribute :network_interfaces, "InstanceNetworkInterface", array: true + # @!attribute [r] tags + # @return [Array, nil] The tags associated with the instance. + attribute :tags + # @!attribute [r] annotations + # @return [Hash{Symbol => String}, nil] The annotations associated with the instance. + # + # Keys follow the Kubernetes annotation key syntax, `[/]`: the + # optional prefix is a non-wildcard DNS subdomain of at most 253 characters, + # and the name is at most 63 characters of `[-_.a-zA-Z0-9]` starting and + # ending with an alphanumeric. Values are unconstrained apart from ASCII + # control characters, which are rejected because they would corrupt the + # console log output annotations can be forwarded to. + # + # An instance holds at most 256 annotations. + attribute :annotations + # @!attribute [r] snapshot + # @return [InstanceSnapshot, nil] The snapshot of the instance, if exists. + attribute :snapshot, "InstanceSnapshot" + # @!attribute [r] delete_lock + # @return [Boolean, nil] If set to true, the instance cannot be deleted until the lock is removed. + attribute :delete_lock + # @!attribute [r] features + # @return [Array, nil] + attribute :features + # @!attribute [r] restart + # @return [InstanceRestartAttempt, nil] The current restart attempt for the instance. + # Not used for template instances. + attribute :restart, "InstanceRestartAttempt" + # @!attribute [r] roms + # @return [Array, nil] Read-Only Memory (ROM) blobs to attach to the instance. + # Unikraft Cloud supports the ability to attach Read-Only Memory (ROM) blobs + # to instances. It allows you to create a general-purpose base image and + # then customize individual instances by attaching code or data as separate + # ROM blobs. + attribute :roms, "InstanceRom", array: true + # @!attribute [r] plugins + # @return [Array, nil] Plugins attached to the instance. Plugins let you attach small helper + # programs to an instance and reach each one over a direct, authenticated + # HTTP endpoint. Each plugin loads from its own ROM image, mounts at + # `/uk/plugins/`, and is reachable at + # `.../v1/instances//plugins//`. At most 8 + # plugins may be attached to an instance. + attribute :plugins, "InstancePlugin", array: true + # @!attribute [r] schedules + # @return [Array, nil] Scheduled operations for this instance. + # + # Each schedule defines a calendar expression and an action (`start`, + # `stop`, `delete`, or `exec`) to perform at matching times. When the + # action is `exec`, the `args` field of the schedule specifies the command + # to run inside the instance. + attribute :schedules, "Schedule", array: true + # @!attribute [r] migration + # @return [InstanceMigration, nil] The migration of the instance, if it migrates or waits to migrate. Only + # present for users with the `migration` permission. + attribute :migration, "InstanceMigration" + # @!attribute [r] autokill + # @return [InstanceAutokill, nil] Automatic delete-on-idle/request-limit configuration. + # Not used for template instances. + attribute :autokill, "InstanceAutokill" + # @!attribute [r] updates + # @return [Array, nil] Queued property changes awaiting application. + attribute :updates, "InstancePendingUpdate", array: true + # @!attribute [r] sched_priority + # @return [String, nil] The scheduling priority for the instance. Only present for + # users with scheduling priority override permissions. + attribute :sched_priority + # @!attribute [r] template_autokill + # @return [InstanceTemplateAutokill, nil] Template-specific automatic delete-on-idle configuration. + # Not used for non-template instances. + attribute :template_autokill, "InstanceTemplateAutokill" + # @!attribute [r] checkpoint_autokill + # @return [InstanceTemplateAutokill, nil] Checkpoint-specific automatic delete-on-idle configuration. + # Only used for checkpoint instances. + attribute :checkpoint_autokill, "InstanceTemplateAutokill" + # @!attribute [r] private_ip + # @return [String, nil] The private IP address of the instance. + attribute :private_ip + # @!attribute [r] gateway + # @return [String, nil] The default gateway configured inside the guest. + attribute :gateway + # @!attribute [r] nameserver + # @return [String, nil] The DNS resolver configured inside the guest. + attribute :nameserver + # @!attribute [r] type + # @return [String, nil] The type of virtual machine used to run the instance. + attribute :type + # @!attribute [r] clone_source + # @return [InstanceCloneSource, nil] The source this instance was cloned from, while the source exists. + attribute :clone_source, "InstanceCloneSource" + # @!attribute [r] gpus + # @return [Array, nil] GPUs attached to the instance. Only present for instances of type + # `full`. + attribute :gpus, "InstanceGpu", array: true + end + + # Automatic delete-on-idle/request-limit configuration for non-template + # instances. Not used for template instances. + class InstanceAutokill < Unikraft::Cloud::Model + # @!attribute [r] time_ms + # @return [Integer, nil] Time in milliseconds after the instance was stopped before it is deleted. + # A value of 0 disables time-based autokill. + attribute :time_ms + # @!attribute [r] num_requests + # @return [Integer, nil] Maximum number of requests/connections the instance serves before it is + # deleted. A value of 0 disables request-based autokill. + attribute :num_requests + end + + # The instance, template, or checkpoint that an instance was cloned from. + class InstanceCloneSource < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the source. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the source. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the source is placed on. + attribute :node + end + + # Features are specific configurations or capabilities that can be enabled for + # the instance. + # + # The list of available features to enable for the instance: + # + # | Feature | Description | + # |--------------------|-------------| + # | `delete-on-stop` | The instance will be deleted when it is stopped. This is useful for instances that are not needed after they are stopped, such as temporary or ephemeral instances. Cannot be combined with a `restart_policy` other than `never`. | + # | `nested-virt` | Expose virtualization extensions to the guest, so that it can run virtual machines of its own. Requires the `nested_virt` permission. | + module InstanceFeature + DELETE_ON_STOP = "delete-on-stop" + NESTED_VIRT = "nested-virt" + + # Every value of this enumeration. + ALL = [DELETE_ON_STOP, NESTED_VIRT].freeze + end + + # A GPU attached to the instance. + class InstanceGpu < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the GPU. + attribute :uuid + # @!attribute [r] model + # @return [String, nil] The GPU model, given as its PCI vendor and device ID in the form + # `:`. + attribute :model + end + + # The migration of an instance. + class InstanceMigration < Unikraft::Cloud::Model + # @!attribute [r] incoming + # @return [Boolean, nil] Whether the instance is the copy of an incoming migration. Only present + # on the destination node. + attribute :incoming + # @!attribute [r] destination + # @return [String, nil] The migration URL of the destination. Only present on the source node. + attribute :destination + # @!attribute [r] state + # @return [String, nil] The phase of the migration. + attribute :state + # @!attribute [r] total_bytes + # @return [Integer, nil] The size of the files the migration copies in bytes, including the holes + # of sparse files. Only present once the migration knows the files. + attribute :total_bytes + # @!attribute [r] copied_bytes + # @return [Integer, nil] The bytes of these files that have been copied. Only present together + # with total_bytes. + attribute :copied_bytes + end + + # The phase of the migration of an instance. + # + # | Phase | Description | + # |--------------|-------------| + # | `waiting` | The instance is starting, stopping or draining, and the migration waits until it has started or stopped. | + # | `queued` | The migration waits for a transfer slot on the source node. The instance can still be started, stopped and changed. | + # | `copying` | The instance and the files of its volumes are copied to the destination. | + # | `syncing` | The running instance is transferred to the destination. | + # | `committing` | The migration is being committed. | + # | `aborting` | The migration is being aborted. | + module InstanceMigrationState + WAITING = "waiting" + QUEUED = "queued" + COPYING = "copying" + SYNCING = "syncing" + COMMITTING = "committing" + ABORTING = "aborting" + + # Every value of this enumeration. + ALL = [WAITING, QUEUED, COPYING, SYNCING, COMMITTING, ABORTING].freeze + end + + # A network interface attached to an instance. + class InstanceNetworkInterface < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] + attribute :uuid + # @!attribute [r] node + # @return [String, nil] The name of the node the network interface is placed on. + attribute :node + # @!attribute [r] private_ip + # @return [String, nil] The private IP address of the network interface. This is the internal IP + # address that is used for communication between instances within the same + # network. + attribute :private_ip + # @!attribute [r] mac + # @return [String, nil] The MAC address of the network interface. + attribute :mac + # @!attribute [r] name + # @return [String, nil] The interface name. If omitted, Unikraft Cloud generates one as + # -ethX, falling back to eth- when the + # instance name is too long. + attribute :name + # @!attribute [r] tap_name + # @return [String, nil] The TAP device to attach the interface. Provide it together with ip. + attribute :tap_name + # @!attribute [r] autoconfig + # @return [Boolean, nil] Whether the interface is automatically configured inside the guest + # (IP address, routes, etc.). When absent or true, autoconfiguration + # is enabled. Present and false when the guest is expected to + # configure the interface manually. + attribute :autoconfig + # @!attribute [r] relay + # @return [InstanceNetworkInterfaceRelay, nil] Relay configuration for this interface. + attribute :relay, "InstanceNetworkInterfaceRelay" + end + + # An object that routes all traffic through another interface. + class InstanceNetworkInterfaceRelay < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] UUID of the relay interface. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] Name of the relay interface. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] instance + # @return [InstanceNetworkInterfaceRelayInstance, nil] The instance the relay interface is attached to. Omitted if the interface + # is not attached to an instance. + attribute :instance, "InstanceNetworkInterfaceRelayInstance" + # @!attribute [r] relay_dns + # @return [Boolean, nil] Whether DNS traffic is relayed through this interface. + # Defaults to true. + attribute :relay_dns + end + + # The instance that a relay interface is attached to. + class InstanceNetworkInterfaceRelayInstance < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] UUID of the instance the relay interface is attached to. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] Name of the instance the relay interface is attached to. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # A queued property change awaiting application on an instance. + class InstancePendingUpdate < Unikraft::Cloud::Model + # @!attribute [r] prop + # @return [String, nil] The property being updated. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The patch operation type. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The new value for the property. Type depends on the property being updated. + attribute :value + # @!attribute [r] status + # @return [String, nil] The status of this update. + attribute :status + # @!attribute [r] error + # @return [String, nil] Error message. Only present when status is "failed". + attribute :error + end + + # The status of this update. + module InstancePendingUpdateStatus + PENDING = "pending" + FAILED = "failed" + + # Every value of this enumeration. + ALL = [PENDING, FAILED].freeze + end + + # A helper program attached to the instance and reachable over a direct, + # authenticated HTTP endpoint. A plugin runs inside the instance next to + # the main application, loads from its own ROM image, and answers requests + # that the Unikraft Cloud API forwards to it. + class InstancePlugin < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The plugin name. It becomes the `` segment in the plugin + # endpoint (`.../plugins//`). A plugin name has a + # maximum length of 63 characters and contains only letters (`a`-`z`, + # `A`-`Z`), digits (`0`-`9`), hyphen (`-`), and underscore (`_`). + attribute :name + # @!attribute [r] image + # @return [String, nil] The plugin's image, given as an image reference string such as + # `user/myplugin:latest`. The platform loads the image, mounts it at + # `/uk/plugins/`, and runs its `init` program when the + # plugin starts. + attribute :image + # @!attribute [r] config + # @return [Object, nil] Arbitrary JSON configuration that the platform passes to the plugin's + # `init` program on `STDIN`. Any JSON value works, including a string, a + # number, or an object. + attribute :config + # @!attribute [r] api_port + # @return [Integer, nil] The port on the instance's address on which the plugin's API listens. + # The platform picks it when the plugin is applied, so it lets a caller + # that can reach the instance directly talk to the plugin without going + # through the platform API. + attribute :api_port + # @!attribute [r] authorization + # @return [InstancePluginAuthorization, nil] The plugin's authorization method. Only present when it is not the + # default (`userdb`). + attribute :authorization, "InstancePluginAuthorization" + end + + # The authorization method of a plugin, as reported in the instance status. + # The token is never returned. + class InstancePluginAuthorization < Unikraft::Cloud::Model + # @!attribute [r] type + # @return [String, nil] The authorization method. + attribute :type + end + + # Restart attempt information for an instance. + class InstanceRestartAttempt < Unikraft::Cloud::Model + # @!attribute [r] attempt + # @return [Integer, nil] Current restart attempt number. This is incremented each time the instance + # is restarted automatically by the platform. + attribute :attempt + # @!attribute [r] next_at + # @return [String, nil] Timestamp of the next scheduled restart attempt. + attribute :next_at + end + + # The restart policy of an instance. + # + # When an instance stops either because the application exits or the instance + # crashes, Unikraft Cloud can auto-restart your instance. Auto-restarts are + # performed according to the restart policy configured for a particular + # instance. The policy can have the following values: + # + # | Policy | Description | + # |--------------|-------------| + # | `never` | Never restart the instance (default). | + # | `always` | Always restart the instance when the stop is initiated from within the instance (i.e., the application exits or the instance crashes). | + # | `on-failure` | Only restart the instance if it crashes. | + # + # When an instance stops, the stop reason and the configured restart policy + # are evaluated to decide if a restart should be performed. Unikraft Cloud + # uses an exponential back-off delay (immediate, 5s, 10s, 20s, 40s, ..., 5m) + # to slow down restarts in tight crash loops. If an instance runs without + # problems for 10s the back-off delay is reset and the restart sequence ends. + # The `restart.attempt` attribute reported in counts the number of restarts + # performed in the current sequence. The `restart.next_at` field indicates + # when the next restart will take place if a back-off delay is in effect. A + # manual start or stop of the instance aborts the restart sequence and resets + # the back-off delay. + module InstanceRestartPolicy + NEVER = "never" + ALWAYS = "always" + ON_FAILURE = "on-failure" + + # Every value of this enumeration. + ALL = [NEVER, ALWAYS, ON_FAILURE].freeze + end + + # A ROM attached to an instance. + class InstanceRom < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the ROM to use for the instance configuration. + attribute :name + # @!attribute [r] image + # @return [String, nil] The image of the ROM to use for the instance configuration. Mutually + # exclusive with `files`. + attribute :image + # @!attribute [r] at + # @return [String, nil] The path at which the ROM should be automatically mounted inside the + # instance. When set, the platform mounts the ROM device at the specified + # path so the guest does not need to mount it manually. When omitted, the + # ROM is exposed as a raw block device and the guest is responsible for + # mounting it. + attribute :at + # @!attribute [r] files + # @return [Array, nil] Inline files to use as the ROM content. When specified, the platform + # creates an EROFS image from the provided files. Mutually exclusive with + # `image`. + attribute :files, "InlineFile", array: true + end + + # Scale-to-zero defines the configuration for scaling the instance to zero. + # When an instance is scaled-to-zero it can be either stopped (and fully + # shutdown) or paused wherein the state of the instance is preserved (e.g., + # RAM contents) and the instance can be resumed later without losing its + # state, i.e. "stateful". + class InstanceScaleToZero < Unikraft::Cloud::Model + # @!attribute [r] enabled + # @return [Boolean, nil] Indicates whether scale-to-zero is enabled for the instance. + attribute :enabled + # @!attribute [r] policy + # @return [String, nil] The specific policy to use for scaling the instance to zero. + attribute :policy + # @!attribute [r] stateful + # @return [Boolean, nil] Whether the instance should be stateful when scaled to zero. If set to + # true, the instance will retain its state (e.g., RAM contents) when scaled + # to zero. This is useful for instances that need to maintain their state + # across scale-to-zero operations. If set to false, the instance will lose + # its state when scaled to zero, and it will be restarted from scratch when + # scaled back up. + attribute :stateful + # @!attribute [r] cooldown_time_ms + # @return [Integer, nil] The cooldown time in milliseconds before the instance can be scaled to + # zero again. This is useful to prevent rapid scaling to zero and back up, + # which can lead to performance issues or resource exhaustion. + attribute :cooldown_time_ms + # @!attribute [r] notify_time_ms + # @return [Integer, nil] The notification time in milliseconds before the instance is scaled to + # zero. This allows the instance to perform any necessary cleanup or state + # saving before being scaled down. + attribute :notify_time_ms + end + + # Scale-to-zero policy types to use when creating an instance. + # + # The policy can be one of the following values: + # + # | Policy | Description | + # |--------|-------------| + # | `on` | The instance should be scaled-to-zero (when possible). | + # | `off` | The instance should never be scaled-to-zero. | + # | `idle` | The instance should be scaled-to-zero even with established but idle TCP connections. | + module InstanceScaleToZeroPolicy + OFF = "off" + ON = "on" + IDLE = "idle" + + # Every value of this enumeration. + ALL = [OFF, ON, IDLE].freeze + end + + # The service group configuration for the instance. This is a reference to the + # service group that the instance is part of. The service group defines the + # services (e.g. ports, connection handling) that the instance exposes and how + # they are configured. + class InstanceServiceGroup < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] domains + # @return [Array, nil] The domain configuration for the service group. + attribute :domains, "ServiceGroupInstanceDomain", array: true + end + + # A snapshot reference for an instance. + class InstanceSnapshot < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] + attribute :uuid + end + + # The current state of an instance. + module InstanceState + STOPPED = "stopped" + STARTING = "starting" + RUNNING = "running" + DRAINING = "draining" + STOPPING = "stopping" + TEMPLATE = "template" + STANDBY = "standby" + DELETED = "deleted" + CHECKPOINT = "checkpoint" + + # Every value of this enumeration. + ALL = [STOPPED, STARTING, RUNNING, DRAINING, STOPPING, TEMPLATE, STANDBY, DELETED, CHECKPOINT].freeze + end + + # Autokill configuration for a template instance. + class InstanceTemplateAutokill < Unikraft::Cloud::Model + # @!attribute [r] time_ms + # @return [Integer, nil] Time in milliseconds after the template was last used for cloning before + # it is deleted. A value of 0 disables template autokill. + attribute :time_ms + end + + # The type of virtual machine used to run an instance. + # + # | Type | Description | + # |---------|-------------| + # | `micro` | A lightweight microVM (default). Boots in milliseconds and is suitable for most workloads. | + # | `full` | A full virtual machine with broader hardware support, such as GPU passthrough. Requires a plan with full VM support. | + module InstanceType + MICRO = "micro" + FULL = "full" + + # Every value of this enumeration. + ALL = [MICRO, FULL].freeze + end + + # A volume defines a storage which can be attached to the instance. Volumes + # can be used to store persistent data which should remain available even if + # the instance is stopped or restarted. + class InstanceVolume < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] at + # @return [String, nil] The mount point of the volume in the instance. This is the directory in + # the instance where the volume will be mounted. + attribute :at + # @!attribute [r] readonly + # @return [Boolean, nil] Whether the volume is read-only or not. + attribute :readonly + end + + # Automatic delete-on-idle configuration for the template instance. + class ItemAutokill < Unikraft::Cloud::Model + # @!attribute [r] time_ms + # @return [Integer, nil] Time in milliseconds after the template was last used for cloning before + # it is deleted. A value of 0 disables template autokill. + attribute :time_ms + end + + # Parameters for migrating the instance to another node. + class MigrateInstanceByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] destination + # @return [MigrateInstanceDestination, nil] The destination, as returned by its accept request. + attribute :destination, "MigrateInstanceDestination" + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the migration to end. No wait if 0 + # (default). Use -1 for the largest possible value. + # + # A migration that waits in the queue or for the instance to start or + # stop has not ended. If the timeout expires first, the request fails + # with a timeout and the instance reports the state of its migration. + # The migration goes on. + attribute :timeout_s + end + + # The destination of a migration, as issued by its accept request. + class MigrateInstanceDestination < Unikraft::Cloud::Model + # @!attribute [r] url + # @return [String, nil] The migration URL that the destination returned. + attribute :url + # @!attribute [r] token + # @return [String, nil] The token that the destination returned. + attribute :token + end + + # A single request item to migrate an instance. + class MigrateInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] destination + # @return [MigrateInstanceDestination, nil] The destination, as returned by its accept request. + attribute :destination, "MigrateInstanceDestination" + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the migration to end. No wait if 0 + # (default). Use -1 for the largest possible value. + # + # A migration that waits in the queue or for the instance to start or + # stop has not ended. If the timeout expires first, the request fails + # with a timeout and the instance reports the state of its migration. + # The migration goes on. + attribute :timeout_s + end + + # The response message for migrating one or more instance(s) given their + # UUID(s) or name(s). + class MigrateInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [MigrateInstancesResponseData, nil] The response data for this request. + attribute :data, "MigrateInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class MigrateInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "MigrateInstancesResponseMigratedInstance", array: true + end + + # Per-item result for a migrate instances operation. + class MigrateInstancesResponseMigratedInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] migration + # @return [InstanceMigration, nil] The migration of the instance. Present if the request did not wait, + # or if the wait timed out. + attribute :migration, "InstanceMigration" + end + + # The operations available on a checkpoint instance's properties. + module MutableCheckpointInstanceOperation + SET = "set" + ADD = "add" + DEL = "del" + + # Every value of this enumeration. + ALL = [SET, ADD, DEL].freeze + end + + # The mutable properties of a checkpoint instance that can be updated. + module MutableCheckpointInstanceProperty + TAGS = "tags" + DELETE_LOCK = "delete_lock" + AUTOKILL = "autokill" + + # Every value of this enumeration. + ALL = [TAGS, DELETE_LOCK, AUTOKILL].freeze + end + + # Mutable instance operations. + module MutableInstanceOperation + SET = "set" + ADD = "add" + DEL = "del" + + # Every value of this enumeration. + ALL = [SET, ADD, DEL].freeze + end + + # The mutable properties of an instance that can be updated. + module MutableInstanceProperty + IMAGE = "image" + ARGS = "args" + ENV = "env" + MEMORY_MB = "memory_mb" + VCPUS = "vcpus" + SCALE_TO_ZERO = "scale_to_zero" + TAGS = "tags" + DELETE_LOCK = "delete_lock" + SCHEDULES = "schedules" + AUTOKILL = "autokill" + HOSTNAME = "hostname" + ROMS = "roms" + DEPENDENCIES = "dependencies" + SCHED_PRIORITY = "sched_priority" + PLUGINS = "plugins" + ANNOTATIONS = "annotations" + + # Every value of this enumeration. + ALL = [IMAGE, ARGS, ENV, MEMORY_MB, VCPUS, SCALE_TO_ZERO, TAGS, DELETE_LOCK, SCHEDULES, AUTOKILL, HOSTNAME, ROMS, DEPENDENCIES, SCHED_PRIORITY, PLUGINS, ANNOTATIONS].freeze + end + + # Mutable template instance operations. + module MutableTemplateInstanceOperation + SET = "set" + ADD = "add" + DEL = "del" + + # Every value of this enumeration. + ALL = [SET, ADD, DEL].freeze + end + + # The mutable properties of a template instance that can be updated. + # Setting `image`, `roms`, or `plugins` updates the template in place. + module MutableTemplateInstanceProperty + TAGS = "tags" + DELETE_LOCK = "delete_lock" + AUTOKILL = "autokill" + IMAGE = "image" + ROMS = "roms" + PLUGINS = "plugins" + + # Every value of this enumeration. + ALL = [TAGS, DELETE_LOCK, AUTOKILL, IMAGE, ROMS, PLUGINS].freeze + end + + # An object that routes all traffic through another interface. + class NetworkInterfaceRelay < Unikraft::Cloud::Model + # @!attribute [r] relay_dns + # @return [Boolean, nil] Whether the relay forwards DNS requests. Set to false + # to let the default DNS server handle them instead. + # Defaults to true. + attribute :relay_dns + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + end + + # Authorization for requests to a plugin endpoint. + class PluginAuthorization < Unikraft::Cloud::Model + # @!attribute [r] type + # @return [String, nil] The authorization method. + attribute :type + # @!attribute [r] token + # @return [String, nil] The token that requests must present as `Authorization: Bearer `. + # Required for, and only allowed with, the `bearer` type. + attribute :token + end + + # How requests to a plugin endpoint are authenticated. + module PluginAuthorizationType + USERDB = "userdb" + BEARER = "bearer" + + # Every value of this enumeration. + ALL = [USERDB, BEARER].freeze + end + + # PullPolicy defines when an image should be pulled. + module PullPolicy + ALWAYS = "always" + IF_NOT_PRESENT = "if_not_present" + NEVER = "never" + + # Every value of this enumeration. + ALL = [ALWAYS, IF_NOT_PRESENT, NEVER].freeze + end + + # A schedule defines when an action should be performed on an instance. + # + # Each schedule specifies a name, a calendar expression following systemd + # calendar event syntax, and an action (start, stop, delete, or exec). + # + # Calendar expressions format: + # + # [weekday] [[year-]month-day] [hour:minute[:second]] + # + # Supported syntax: + # + # - `*` - Any value + # - `5` - Exact value + # - `1..5` - Range + # - `1..5/2` - Range with step + # - `1,2,5` - Comma-separated list + # + # Example: `*-*-* 09:00:00` - Every day at 09:00 UTC + # Example: `Sat,Sun *-*-* 20:00:00` - Every Saturday and Sunday at 20:00 UTC + class Schedule < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the schedule. + # + # Must be unique within an instance. + attribute :name + # @!attribute [r] when + # @return [String, nil] The calendar expression specifying when the action should be performed. + # + # Uses systemd calendar event syntax. + # See https://www.man7.org/linux/man-pages/man7/systemd.time.7.html + attribute :when + # @!attribute [r] action + # @return [String, nil] The action to perform at the scheduled time. + attribute :action + # @!attribute [r] next_at + # @return [String, nil] The timestamp of when the next scheduled action will occur. + # + # This field is populated only in responses (not settable in requests). + # Omitted if no next execution is scheduled. + attribute :next_at + # @!attribute [r] args + # @return [Array, nil] The command to execute when the action is `exec`. + # + # Required when `action` is `SCHEDULE_ACTION_EXEC`, ignored otherwise. + # Each element is a separate argument; the first element is the executable. + attribute :args + end + + # The action to perform on a scheduled operation. + module ScheduleAction + START = "start" + STOP = "stop" + DELETE = "delete" + EXEC = "exec" + + # Every value of this enumeration. + ALL = [START, STOP, DELETE, EXEC].freeze + end + + # The domain configuration for the service group. Domain names are completely + # specified with all labels in the hierarchy of the DNS, having no parts + # omitted. The domain can be associated with an existing certificate by + # specifying the certificate's name or UUID. If no certificate is specified + # and a FQDN is provided, Unikraft Cloud will automatically generate a new + # certificate for the domain based on Let's Encrypt and seek to accomplish a + # DNS-01 challenge. + class ServiceGroupInstanceDomain < Unikraft::Cloud::Model + # @!attribute [r] fqdn + # @return [String, nil] Publicly accessible domain name. + # + # If this name ends in a period `.` it must be a valid Full Qualified + # Domain Name (FQDN), otherwise it will become a subdomain of the target + # metro. + attribute :fqdn + # @!attribute [r] certificate + # @return [NameOrUUID, nil] The certificate associated with the domain. + # + # The certificate is used to secure the domain with TLS/SSL. If no + # certificate is specified, Unikraft Cloud will automatically generate a + # new certificate for the domain based on Let's Encrypt and seek to + # accomplish a DNS-01 challenge. + attribute :certificate, "NameOrUUID" + end + + # Parameters for starting the instance. + class StartInstanceByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] wait_timeout_ms + # @return [Integer, nil] Deprecated: Use `timeout_s` instead. Timeout in milliseconds to + # wait for the instance to reach running state. If `timeout_s` is + # not set, this value is converted by rounding up to the next full + # second. No wait performed for a value of 0. + attribute :wait_timeout_ms + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the instance to reach running + # state. If you start your instance, you can wait for it to + # finish starting with a blocking API call if you specify a wait + # timeout greater than zero. No wait performed for a value of 0. + attribute :timeout_s + end + + # A single request item to start an instance. + class StartInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] wait_timeout_ms + # @return [Integer, nil] Deprecated: Use `timeout_s` instead. Timeout in milliseconds to + # wait for the instance to reach running state. If `timeout_s` is + # not set, this value is converted by rounding up to the next full + # second. No wait performed for a value of 0. + attribute :wait_timeout_ms + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the instance to reach running + # state. If you start your instance, you can wait for it to + # finish starting with a blocking API call if you specify a wait + # timeout greater than zero. No wait performed for a value of 0. + attribute :timeout_s + end + + # The response message for starting one or more instance(s) given their + # UUID(s) or name(s). + class StartInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [StartInstancesResponseData, nil] The response data for this request. + attribute :data, "StartInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class StartInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "StartInstancesResponseStartedInstance", array: true + end + + # Per-item result for a start instances operation. + class StartInstancesResponseStartedInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The current state of the instance after this request. + attribute :state + # @!attribute [r] previous_state + # @return [String, nil] The previous state of the instance before it was started. + attribute :previous_state + end + + # Parameters for stopping the instance. + class StopInstanceByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] force + # @return [Boolean, nil] Whether to immediately force stop the instance. + attribute :force + # @!attribute [r] drain_timeout_ms + # @return [Integer, nil] Timeout for draining connections in milliseconds. + # No draining will occur if set to 0. The instance + # does not receive new connections in the draining + # phase. The instance is stopped when the last + # connection has been closed or the timeout expired. + # The maximum timeout may vary. Use -1 for the + # largest possible value. Ignored if force is set. + # + # Note: This endpoint does not block. Use the wait + # endpoint for the instance to reach the stopped + # state. + attribute :drain_timeout_ms + # @!attribute [r] quick + # @return [Boolean, nil] Whether to perform a quick shutdown. This flag is + # overridden by force. + attribute :quick + # @!attribute [r] ifstate + # @return [String, nil] Only stop the instance if it is in this state. + attribute :ifstate + # @!attribute [r] dump + # @return [Boolean, nil] If set, forces the VMM to shutdown immediately and generate a coredump. + # Can only be used in conjunction with force. + attribute :dump + end + + # A single request item to stop an instance. + class StopInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] force + # @return [Boolean, nil] Whether to immediately force stop the instance. + attribute :force + # @!attribute [r] drain_timeout_ms + # @return [Integer, nil] Timeout for draining connections in milliseconds. + # No draining will occur if set to 0. The instance + # does not receive new connections in the draining + # phase. The instance is stopped when the last + # connection has been closed or the timeout expired. + # The maximum timeout may vary. Use -1 for the + # largest possible value. Ignored if force is set. + # + # Note: This endpoint does not block. Use the wait + # endpoint for the instance to reach the stopped + # state. + attribute :drain_timeout_ms + # @!attribute [r] quick + # @return [Boolean, nil] Whether to perform a quick shutdown. This flag is + # overridden by force. + attribute :quick + # @!attribute [r] ifstate + # @return [String, nil] Only stop the instance if it is in this state. + attribute :ifstate + # @!attribute [r] dump + # @return [Boolean, nil] If set, forces the VMM to shutdown immediately and generate a coredump. + # Can only be used in conjunction with force. + attribute :dump + end + + # The response message for stopping one or more instance(s) given their + # UUID(s) or name(s). + class StopInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [StopInstancesResponseData, nil] The response data for this request. + attribute :data, "StopInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class StopInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "StopInstancesResponseStoppedInstance", array: true + end + + # Per-item result for a stop instances operation. + class StopInstancesResponseStoppedInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The current state of the instance. + attribute :state + # @!attribute [r] previous_state + # @return [String, nil] The previous state of the instance before the stop operation was + # invoked. + attribute :previous_state + end + + # Parameters for suspending the instance. + class SuspendInstanceByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] drain_timeout_ms + # @return [Integer, nil] Timeout for draining connections in milliseconds. No draining + # will occur if set to 0. Use -1 for the largest possible value. + attribute :drain_timeout_ms + end + + # A single request item to suspend an instance. + class SuspendInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] drain_timeout_ms + # @return [Integer, nil] Timeout for draining connections in milliseconds. No draining + # will occur if set to 0. Use -1 for the largest possible value. + attribute :drain_timeout_ms + end + + # The response message for suspending one or more instance(s) given their + # UUID(s) or name(s). + class SuspendInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [SuspendInstancesResponseData, nil] The response data for this request. + attribute :data, "SuspendInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class SuspendInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "SuspendInstancesResponseSuspendedInstance", array: true + end + + # Per-item result for a suspend instances operation. + class SuspendInstancesResponseSuspendedInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The current state of the instance. + attribute :state + # @!attribute [r] previous_state + # @return [String, nil] The previous state of the instance before the suspend operation was + # invoked. + attribute :previous_state + end + + # Automatic delete-on-idle configuration for the template instance. Only + # applies when `prepare` is set. + class TemplateAutokill < Unikraft::Cloud::Model + # @!attribute [r] time_ms + # @return [Integer, nil] Time in milliseconds after the template was last used for cloning before + # it is deleted. A value of 0 disables template autokill. + attribute :time_ms + end + + # Request body for updating a single checkpoint instance by UUID. + class UpdateCheckpointInstanceByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform on the property. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "autokill": object with time_ms field + attribute :value + end + + # A single update operation to be applied to a checkpoint instance. + class UpdateCheckpointInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform on the property. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "autokill": object with time_ms field + attribute :value + end + + # The response message for updating one or more checkpoint instance(s) given + # their UUID(s) or name(s). + class UpdateCheckpointInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [UpdateCheckpointInstancesResponseData, nil] The response data for this request. + attribute :data, "UpdateCheckpointInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # Per-item result for an update checkpoint instances operation. + class UpdateCheckpointInstancesResponseCheckpointInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] id + # @return [String, nil] The client-provided ID from the request. + attribute :id + end + + # The response data for this request. + class UpdateCheckpointInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] List of checkpoint instances that were processed during the update operation. + attribute :instances, "UpdateCheckpointInstancesResponseCheckpointInstance", array: true + end + + # The `UpdateInstanceByUUIDRequestBody` model. + class UpdateInstanceByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform on the property. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "image": image reference string, or object with image url, + # credentials, headers and pull policy + # - For "args": string or array of strings + # - For "env": object (for SET/ADD) or string/array of strings (for DEL) + # - For "memory_mb": integer + # - For "vcpus": integer + # - For "scale_to_zero": object with cooldown_time_ms, policy, and stateful fields + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "schedules": array of schedule objects (with name, when, action, and optional args fields) + # for SET/ADD, or array of schedule names for DEL. Use action "exec" together with args to + # execute a command at the scheduled time. + # - For "autokill": object with time_ms and num_requests fields + # - For "hostname": string (valid DNS label) + # - For "roms": array of ROM objects (with name and image fields) for SET/ADD, or array of ROM names for DEL + # - For "plugins": array of plugin objects (with name, image, and optional config and + # authorization fields) for SET/ADD. The deprecated `rom` field is accepted in place of `image`. + # - For "dependencies": array of instance identifiers (name or UUID) + # - For "sched_priority": SchedPriority enum value ("normal", "medium", "high", "admin") + # - For "annotations": object (for SET/ADD) or string/array of strings (for DEL) + attribute :value + end + + # A single update operation to be applied to an instance. + class UpdateInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform on the property. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "image": image reference string, or object with image url, + # credentials, headers and pull policy + # - For "args": string or array of strings + # - For "env": object (for SET/ADD) or string/array of strings (for DEL) + # - For "memory_mb": integer + # - For "vcpus": integer + # - For "scale_to_zero": object with cooldown_time_ms, policy, and stateful fields + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "schedules": array of schedule objects (with name, when, action, and optional args fields) + # for SET/ADD, or array of schedule names for DEL. Use action "exec" together with args to + # execute a command at the scheduled time. + # - For "autokill": object with time_ms and num_requests fields + # - For "hostname": string (valid DNS label) + # - For "roms": array of ROM objects (with name and image fields) for SET/ADD, or array of ROM names for DEL + # - For "plugins": array of plugin objects (with name, image, and optional config and + # authorization fields) for SET/ADD. The deprecated `rom` field is accepted in place of `image`. + # - For "dependencies": array of instance identifiers (name or UUID) + # - For "sched_priority": SchedPriority enum value ("normal", "medium", "high", "admin") + # - For "annotations": object (for SET/ADD) or string/array of strings (for DEL) + attribute :value + end + + # The response message for updating one or more instance(s) given their + # UUID(s) or name(s). + class UpdateInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [UpdateInstancesResponseData, nil] The response data for this request. + attribute :data, "UpdateInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class UpdateInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "UpdateInstancesResponseUpdatedInstance", array: true + end + + # Per-item result for an update instances operation. + class UpdateInstancesResponseUpdatedInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] id + # @return [String, nil] The client-provided ID from the request. + attribute :id + end + + # The `UpdateTemplateInstanceByUUIDRequestBody` model. + class UpdateTemplateInstanceByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and + # operation: + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "autokill": object with time_ms field + # - For "image": image reference string or object (SET only) + # - For "roms": array of ROM objects (SET only) + # - For "plugins": array of plugin objects (SET only) + attribute :value + end + + # A single template instance update request item. + class UpdateTemplateInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and + # operation: + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "autokill": object with time_ms field + # - For "image": image reference string or object (SET only) + # - For "roms": array of ROM objects (SET only) + # - For "plugins": array of plugin objects (SET only) + attribute :value + end + + # The response message for updating one or more template instance(s) given + # their UUID(s) or name(s). + class UpdateTemplateInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [UpdateTemplateInstancesResponseData, nil] The response data for this request. + attribute :data, "UpdateTemplateInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class UpdateTemplateInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "UpdateTemplateInstancesResponseTemplateInstance", array: true + end + + # Per-item result for an update template instances operation. + class UpdateTemplateInstancesResponseTemplateInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] id + # @return [String, nil] Client-provided operation ID. + attribute :id + end + + # Wait parameters. + class WaitInstanceByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] state + # @return [String, nil] The desired state to wait for. Default is `running`. + attribute :state + # @!attribute [r] timeout_ms + # @return [Integer, nil] Deprecated: Use `timeout_s` instead. Timeout in milliseconds to + # wait for the instance to reach the desired state. If `timeout_s` is + # not set, this value is converted by rounding up to the next full + # second. A value of -1 means to wait indefinitely. + attribute :timeout_ms + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the instance to reach the desired + # state. If the timeout is reached, the request will fail with an + # error. A value of -1 means to wait indefinitely until the instance + # reaches the desired state. No wait performed for a value of 0. + attribute :timeout_s + end + + # A single request item to wait for an instance's state. + class WaitInstancesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] state + # @return [String, nil] The desired state to wait for. Default is `running`. + attribute :state + # @!attribute [r] timeout_ms + # @return [Integer, nil] Deprecated: Use `timeout_s` instead. Timeout in milliseconds to + # wait for the instance to reach the desired state. If `timeout_s` is + # not set, this value is converted by rounding up to the next full + # second. A value of -1 means to wait indefinitely. + attribute :timeout_ms + # @!attribute [r] timeout_s + # @return [Integer, nil] Timeout in seconds to wait for the instance to reach the desired + # state. If the timeout is reached, the request will fail with an + # error. A value of -1 means to wait indefinitely until the instance + # reaches the desired state. No wait performed for a value of 0. + attribute :timeout_s + end + + # The response message for waiting for one or more instance(s) to reach a + # certain state given their UUID(s) or name(s). + class WaitInstancesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [WaitInstancesResponseData, nil] The response data for this request. + attribute :data, "WaitInstancesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class WaitInstancesResponseData < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Array, nil] + attribute :instances, "WaitInstancesResponseWaitedInstance", array: true + end + + # Per-item result for a wait instances operation. + class WaitInstancesResponseWaitedInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The current state of the instance. + attribute :state + end + + # License information (admin only). + class DataLicense < Unikraft::Cloud::Model + # @!attribute [r] serial + # @return [String, nil] The serial number of the license certificate, hex-encoded. + attribute :serial + # @!attribute [r] valid + # @return [Boolean, nil] Whether the license is currently valid. + attribute :valid + # @!attribute [r] features + # @return [Array, nil] List of enabled features. + attribute :features + end + + # The health state reported by a single health checker. + module HealthState + UNKNOWN = "unknown" + HEALTHY = "healthy" + DEGRADED = "degraded" + + # Every value of this enumeration. + ALL = [UNKNOWN, HEALTHY, DEGRADED].freeze + end + + # Standard response envelope wrapping all API responses. + class HealthzResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [HealthzResponseData, nil] The response data for this request. + attribute :data, "HealthzResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # Additional data returned by the health check. + class HealthzResponseData < Unikraft::Cloud::Model + # @!attribute [r] checks + # @return [Hash{Symbol => String}, nil] The health state of each registered checker, keyed by checker name. + # Valid keys are "images", "systemd", and "user-defined"; a checker's + # key is only present if it is enabled. Checkers report only their + # aggregate state; per-check detail (e.g. which default image is + # missing, or which user-defined script failed) is not exposed here. + attribute :checks + # @!attribute [r] versions + # @return [Hash{Symbol => String}, nil] + attribute :versions + # @!attribute [r] license + # @return [DataLicense, nil] License information (admin only). + attribute :license, "DataLicense" + end + + # Connection handlers to use for the service. + # + # Handlers define how the service will handle incoming connections and + # forward traffic from the Internet to your application. For example, a + # service can be configured to terminate TLS connections, redirect HTTP + # traffic, or enable HTTP mode for load balancing. You configure the handlers + # for every published service port individually. + # + # There are currently 3 supported handlers: + # + # | Handler | Description | + # |------------|-------------| + # | `tls` | Terminate the TLS connection at the Unikraft Cloud gateway using our wildcard certificate issued for the kraft.cloud domain. The gateway forwards the unencrypted traffic to your application. | + # | `http` | Enable HTTP mode on the load balancer to load balance on the level of individual HTTP requests. In this mode, only HTTP connections are accepted. If this option is not set the load balancer works in TCP mode and distributes TCP connections. | + # | `redirect` | Redirect traffic from the source port to the destination port. | + # + # Note that there is a set of constraints when publishing ports: + # + # - Port 80: MUST have "http" and MUST not have "tls" set; + # - Port 443: MUST have http and tls set; + # - The `redirect` handler can only be set on port 80 (HTTP) to redirect to + # port 443 (HTTPS); + # - All other ports MUST have tls and MUST not have http set. + module ConnectionHandler + TLS = "tls" + HTTP = "http" + REDIRECT = "redirect" + + # Every value of this enumeration. + ALL = [TLS, HTTP, REDIRECT].freeze + end + + # The request message for creating a new service group. + class CreateServiceGroupRequest < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the resource. If not provided, a random name is generated. + # The name must be unique within the context of your account. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node to place the resource on. If not provided, the + # platform picks one. Only accepted on metros that span multiple nodes. + attribute :node + # @!attribute [r] services + # @return [Array, nil] Services to expose. At least one service is required. + attribute :services, "Service", array: true + # @!attribute [r] domains + # @return [Array, nil] Description of domains associated with the service group. + attribute :domains, "CreateServiceGroupRequestDomain", array: true + # @!attribute [r] soft_limit + # @return [Integer, nil] The soft limit is used by the Unikraft Cloud load balancer to decide when + # to wake up another standby instance. + # + # For example, if the soft limit is set to 5 and the service consists of 2 + # standby instances, one of the instances receives up to 5 concurrent + # requests. The 6th parallel requests wakes up the second instance. If + # there are no more standby instances to wake up, the number of requests + # assigned to each instance will exceed the soft limit. The load balancer + # makes sure that when the number of in-flight requests goes down again, + # instances are put into standby as fast as possible. + attribute :soft_limit + # @!attribute [r] hard_limit + # @return [Integer, nil] The hard limit defines the maximum number of concurrent requests that an + # instance assigned to the this service can handle. + # + # The load balancer will never assign more requests to a single instance. In + # case there are no other instances available, excess requests fail (i.e., + # they are blocked and not queued). + attribute :hard_limit + # @!attribute [r] autokill + # @return [CreateServiceGroupRequestAutokill, nil] Automatic delete-on-idle configuration. + attribute :autokill, "CreateServiceGroupRequestAutokill" + end + + # Autokill configuration when creating a service group. + class CreateServiceGroupRequestAutokill < Unikraft::Cloud::Model + # @!attribute [r] time_ms + # @return [Integer, nil] Time in milliseconds after the service group becomes empty before it is + # deleted. A value of 0 disables autokill. + attribute :time_ms + end + + # A domain to attach when creating a service group. + class CreateServiceGroupRequestDomain < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] Publicly accessible domain name. If this name ends in a period `.` it must + # be a valid Full Qualified Domain Name (FQDN), otherwise it will become a + # subdomain of the target metro. + attribute :name + # @!attribute [r] certificate + # @return [NameOrUUID, nil] Use an existing certificate for the domain. If this field is + # specified, the domain must be associated with a valid certificate. + attribute :certificate, "NameOrUUID" + end + + # The response message for creating a new service group. + class CreateServiceGroupResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CreateServiceGroupResponseData, nil] The response data for this request. + attribute :data, "CreateServiceGroupResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class CreateServiceGroupResponseData < Unikraft::Cloud::Model + # @!attribute [r] service_groups + # @return [Array, nil] + attribute :service_groups, "ServiceGroup", array: true + end + + # The response message for deleting of one or more service group(s) given + # their UUID(s) or name(s). + class DeleteServiceGroupsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DeleteServiceGroupsResponseData, nil] The response data for this request. + attribute :data, "DeleteServiceGroupsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class DeleteServiceGroupsResponseData < Unikraft::Cloud::Model + # @!attribute [r] service_groups + # @return [Array, nil] + attribute :service_groups, "DeleteServiceGroupsResponseDeletedServiceGroup", array: true + end + + # Per-item result for a delete service groups operation. + class DeleteServiceGroupsResponseDeletedServiceGroup < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code providing additional information about the status. + attribute :error + end + + # A domain name. Domain names are completely specified with all labels in the + # hierarchy of the DNS, having no parts omitted. The domain can be associated + # with an existing certificate by specifying the certificate's name or UUID. + # If no certificate is specified and a FQDN is provided, Unikraft Cloud will + # automatically generate a new certificate for the domain based on Let's + # Encrypt and seek to accomplish a DNS-01 challenge. + class Domain < Unikraft::Cloud::Model + # @!attribute [r] fqdn + # @return [String, nil] Publicly accessible domain name. If this name ends in a period `.` it must + # be a valid Full Qualified Domain Name (FQDN), otherwise it will become a + # subdomain of the target metro. + attribute :fqdn + # @!attribute [r] certificate + # @return [Certificate, nil] Use an existing certificate for the domain. If this field is + # specified, the domain must be associated with a valid certificate. + attribute :certificate, "Certificate" + end + + # The response message for getting one or more service group(s) given their + # UUID(s) or name(s). + class GetServiceGroupsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetServiceGroupsResponseData, nil] The response data for this request. + attribute :data, "GetServiceGroupsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetServiceGroupsResponseData < Unikraft::Cloud::Model + # @!attribute [r] service_groups + # @return [Array, nil] + attribute :service_groups, "ServiceGroup", array: true + end + + # The mutable operations available on a service group's properties. + module MutableServiceGroupOperation + SET = "set" + ADD = "add" + DEL = "del" + + # Every value of this enumeration. + ALL = [SET, ADD, DEL].freeze + end + + # Mutable service group properties. + module MutableServiceGroupProperty + SERVICES = "services" + DOMAINS = "domains" + SOFT_LIMIT = "soft_limit" + HARD_LIMIT = "hard_limit" + AUTOKILL = "autokill" + + # Every value of this enumeration. + ALL = [SERVICES, DOMAINS, SOFT_LIMIT, HARD_LIMIT, AUTOKILL].freeze + end + + # A service connects a public-facing port to an internal destination port on + # which an application instance listens on. Additional handlers can be + # defined for each published port in order to define how the service will + # handle incoming connections and forward traffic from the Internet to your + # application. For example, a service can be configured to terminate TLS + # connections, redirect HTTP traffic, or enable HTTP mode for load balancing. + class Service < Unikraft::Cloud::Model + # @!attribute [r] port + # @return [Integer, nil] This is the public-facing port that the service will be accessible from + # on the Internet. + attribute :port + # @!attribute [r] destination_port + # @return [Integer, nil] The port number that the instance is listening on. This is the internal + # port which Unikraft Cloud will forward traffic to. + attribute :destination_port + # @!attribute [r] protocol + # @return [String, nil] + attribute :protocol + # @!attribute [r] ip + # @return [String, nil] + attribute :ip + # @!attribute [r] handlers + # @return [Array, nil] Connection handlers to use for the service. Handlers define how the + # service will handle incoming connections and forward traffic from the + # Internet to your application. For example, a service can be configured + # to terminate TLS connections, redirect HTTP traffic, or enable HTTP mode + # for load balancing. You configure the handlers for every published + # service port individually. + attribute :handlers + end + + # A service group on Unikraft Cloud is used to describe how your application + # exposes its functionality to the outside world. Once defined, assigning an + # instance to the service will make it accessible from the Internet. + # + # An application, running as an instance, may expose one or more ports, e.g. + # it listens on port 80 because your application exposes a HTTP web service. + # This, along with a set of additional metadata defines how the "service" is + # configured and accessed. For example, a service may be configured to use + # TLS, or be bound to a specific domain name. + # + # When an instance is assigned to a service group, it immediately becomes + # accessible over the Internet on the exposed public port, using the set DNS + # name, and is routed to the set destination port. + # + # Note: If you do not specify a DNS name when you create a service and you + # indicate that the application exposes some ports, Unikraft Cloud will + # generates a random DNS name for you. Unikraft Cloud also supports custom + # domains like www.example.com and wildcard domains like *.example.com. + class ServiceGroup < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] created_at + # @return [String, nil] The time the service was created. + attribute :created_at + # @!attribute [r] persistent + # @return [Boolean, nil] Indicates if the service will stay remain even after the last instance + # detached. If this is set to false, the service will be deleted when the + # last instance detached from it. If this is set to true, the service will + # remain and can be reused by other instances. This is useful if you want to + # keep the service configuration, e.g., the published ports, handlers, and + # domains, even if there are no instances assigned to it. + attribute :persistent + # @!attribute [r] autoscale + # @return [Boolean, nil] Indicates if the service has autoscale enabled. See the associated + # autoscale documentation for more information about how to set this up. + # Autoscale policies can be set up after the service has been created. + attribute :autoscale + # @!attribute [r] soft_limit + # @return [Integer, nil] The soft limit is used by the Unikraft Cloud load balancer to decide when + # to wake up another standby instance. For example, if the soft limit is set + # to 5 and the service consists of 2 standby instances, one of the instances + # receives up to 5 concurrent requests. The 6th parallel requests wakes up + # the second instance. If there are no more standby instances to wake up, + # the number of requests assigned to each instance will exceed the soft + # limit. The load balancer makes sure that when the number of in-flight + # requests goes down again, instances are put into standby as fast as + # possible. + attribute :soft_limit + # @!attribute [r] hard_limit + # @return [Integer, nil] The hard limit defines the maximum number of concurrent requests that an + # instance assigned to the this service can handle. The load balancer will + # never assign more requests to a single instance. In case there are no + # other instances available, excess requests fail (i.e., they are blocked and + # not queued). + attribute :hard_limit + # @!attribute [r] services + # @return [Array, nil] List of published network ports for this service and the destination port + # to which Unikraft Cloud will forward traffic to. Additional handlers can + # be defined for each published port in order to define how the service will + # handle incoming connections and forward traffic from the Internet to your + # application. For example, a service can be configured to terminate TLS + # connections, redirect HTTP traffic, or enable HTTP mode for load balancing. + attribute :services, "Service", array: true + # @!attribute [r] domains + # @return [Array, nil] List of domains associated with the service. Domains are used to access + # the service over the Internet. + attribute :domains, "Domain", array: true + # @!attribute [r] instances + # @return [Array, nil] List of instances assigned to the service. + attribute :instances, "ServiceGroupInstance", array: true + # @!attribute [r] autokill + # @return [ServiceGroupAutokill, nil] Automatic delete-on-idle configuration. + attribute :autokill, "ServiceGroupAutokill" + end + + # Autokill configuration for a service group. + class ServiceGroupAutokill < Unikraft::Cloud::Model + # @!attribute [r] time_ms + # @return [Integer, nil] Time in milliseconds after the service group becomes empty before it is + # deleted. A value of 0 disables autokill. + attribute :time_ms + end + + # An instance belonging to a service group. + class ServiceGroupInstance < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # Protocol for a service. + module ServiceProtocol + TCP = "tcp" + UDP = "udp" + + # Every value of this enumeration. + ALL = [TCP, UDP].freeze + end + + # The `UpdateServiceGroupByUUIDRequestBody` model. + class UpdateServiceGroupByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "image": string + # - For "args": string or array of strings + # - For "env": object (for SET/ADD) or string/array of strings (for DEL) + # - For "memory_mb": integer + # - For "vcpus": integer + # - For "scale_to_zero": object with cooldown_time_ms, policy, and stateful fields + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "schedules": array of schedule objects (with name, when, action, and optional args fields). + # Use action "exec" together with args to execute a command at the scheduled time. + # - For "autokill": object with time_ms and num_requests fields + # - For "hostname": string (valid DNS label) + # - For "roms": array of ROM objects (with name and image fields) for SET/ADD, or array of ROM names for DEL + # - For "dependencies": array of instance identifiers (name or UUID) + # - For "sched_priority": SchedPriority enum value ("normal", "medium", "high", "admin") + attribute :value + end + + # A single update operation to be applied to a service group. + class UpdateServiceGroupsRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "image": string + # - For "args": string or array of strings + # - For "env": object (for SET/ADD) or string/array of strings (for DEL) + # - For "memory_mb": integer + # - For "vcpus": integer + # - For "scale_to_zero": object with cooldown_time_ms, policy, and stateful fields + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "schedules": array of schedule objects (with name, when, action, and optional args fields). + # Use action "exec" together with args to execute a command at the scheduled time. + # - For "autokill": object with time_ms and num_requests fields + # - For "hostname": string (valid DNS label) + # - For "roms": array of ROM objects (with name and image fields) for SET/ADD, or array of ROM names for DEL + # - For "dependencies": array of instance identifiers (name or UUID) + # - For "sched_priority": SchedPriority enum value ("normal", "medium", "high", "admin") + attribute :value + end + + # The response message for updating one or more service group(s) given their + # UUID(s) or name(s). + class UpdateServiceGroupsResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [UpdateServiceGroupsResponseData, nil] The response data for this request. + attribute :data, "UpdateServiceGroupsResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class UpdateServiceGroupsResponseData < Unikraft::Cloud::Model + # @!attribute [r] service_groups + # @return [Array, nil] + attribute :service_groups, "UpdateServiceGroupsResponseUpdatedServiceGroup", array: true + end + + # Per-item result for an update service groups operation. + class UpdateServiceGroupsResponseUpdatedServiceGroup < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] id + # @return [String, nil] The client-provided ID from the request. + attribute :id + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code providing additional information about the status. + attribute :error + end + + # Quotas with per-item response envelope fields merged in. + class Quotas < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the quota. + attribute :uuid + # @!attribute [r] used + # @return [QuotasStats, nil] Used quota. + attribute :used, "QuotasStats" + # @!attribute [r] hard + # @return [QuotasStats, nil] Configured quota limits. + attribute :hard, "QuotasStats" + # @!attribute [r] limits + # @return [QuotasLimits, nil] Additional limits. + attribute :limits, "QuotasLimits" + end + + # Additional resource limits. + class QuotasLimits < Unikraft::Cloud::Model + # @!attribute [r] min_memory_mb + # @return [Integer, nil] Minimum amount of memory assigned to live instances in megabytes + attribute :min_memory_mb + # @!attribute [r] max_memory_mb + # @return [Integer, nil] Maximum amount of memory assigned to live instances in megabytes + attribute :max_memory_mb + # @!attribute [r] min_volume_mb + # @return [Integer, nil] Minimum size of a volume in megabytes + attribute :min_volume_mb + # @!attribute [r] max_volume_mb + # @return [Integer, nil] Maximum size of a volume in megabytes + attribute :max_volume_mb + # @!attribute [r] min_autoscale_size + # @return [Integer, nil] Minimum size of an autoscale group + attribute :min_autoscale_size + # @!attribute [r] max_autoscale_size + # @return [Integer, nil] Maximum size of an autoscale group + attribute :max_autoscale_size + # @!attribute [r] min_vcpus + # @return [Integer, nil] Minimum number of vCPUs + attribute :min_vcpus + # @!attribute [r] max_vcpus + # @return [Integer, nil] Maximum number of vCPUs + attribute :max_vcpus + end + + # The response message for getting the quota of a user given their UUID. + class QuotasResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [QuotasResponseData, nil] The response data for this request. + attribute :data, "QuotasResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class QuotasResponseData < Unikraft::Cloud::Model + # @!attribute [r] quotas + # @return [Array, nil] + attribute :quotas, "Quotas", array: true + end + + # Quota statistics for resource usage. + class QuotasStats < Unikraft::Cloud::Model + # @!attribute [r] instances + # @return [Integer, nil] Number of instances. + attribute :instances + # @!attribute [r] live_instances + # @return [Integer, nil] Number of instances that are not in the stopped state. + attribute :live_instances + # @!attribute [r] live_vcpus + # @return [Integer, nil] Number of vCPUs. + attribute :live_vcpus + # @!attribute [r] live_memory_mb + # @return [Integer, nil] Amount of memory assigned to instances that are not in the `stopped` state + # in megabytes. + attribute :live_memory_mb + # @!attribute [r] service_groups + # @return [Integer, nil] Number of service groups. + attribute :service_groups + # @!attribute [r] services + # @return [Integer, nil] Number of published network ports over all existing services. + attribute :services + # @!attribute [r] volumes + # @return [Integer, nil] Number of volumes. + attribute :volumes + # @!attribute [r] total_volume_mb + # @return [Integer, nil] Total size of all volumes in megabytes. + attribute :total_volume_mb + end + + # A single request item to resume a user account. + class ResumeUsersRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the user. + attribute :uuid + end + + # The response message for resuming one or more user account(s) given their + # UUID(s). + class ResumeUsersResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [ResumeUsersResponseData, nil] The response data for this request. + attribute :data, "ResumeUsersResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class ResumeUsersResponseData < Unikraft::Cloud::Model + # @!attribute [r] users + # @return [Array, nil] + attribute :users, "ResumeUsersResponseResumedUser", array: true + end + + # An instance that a resume users operation restored. + class ResumeUsersResponseResumedInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The current state of the instance. + attribute :state + # @!attribute [r] previous_state + # @return [String, nil] The previous state of the instance before the resume operation was + # invoked. + attribute :previous_state + # @!attribute [r] on_resume + # @return [String, nil] What the resume operation did with this instance. + attribute :on_resume + end + + # Per-item result for a resume users operation. + class ResumeUsersResponseResumedUser < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] suspended + # @return [Boolean, nil] Whether the user account is still suspended after this request, for + # example because it was suspended again concurrently. + attribute :suspended + # @!attribute [r] instances + # @return [Array, nil] The instances of the user that were restored, as recorded when the user + # was suspended. Instances that had nothing to restore are not listed. An + # instance that failed to start keeps its record, so a later resume tries + # again. + attribute :instances, "ResumeUsersResponseResumedInstance", array: true + end + + # Parameters for suspending a user account. + class SuspendUserByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] suspend_instances + # @return [Boolean, nil] Whether to also bring all instances of the user to rest. Autostart is + # disabled, running instances are suspended (or stopped if they cannot be + # suspended, or if they only return to standby and are not stateful), and + # pending restarts are cancelled. Instances that are draining, stopping, or + # in a start-stop cycle finish that transition first. Booting instances are + # brought to rest once they are running. Without this flag only the account + # is suspended and its instances are left as they are. + attribute :suspend_instances + end + + # A single request item to suspend a user account. + class SuspendUsersRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the user. + attribute :uuid + # @!attribute [r] suspend_instances + # @return [Boolean, nil] Whether to also bring all instances of the user to rest. Autostart is + # disabled, running instances are suspended (or stopped if they cannot be + # suspended, or if they only return to standby and are not stateful), and + # pending restarts are cancelled. Instances that are draining, stopping, or + # in a start-stop cycle finish that transition first. Booting instances are + # brought to rest once they are running. Without this flag only the account + # is suspended and its instances are left as they are. + attribute :suspend_instances + end + + # The response message for suspending one or more user account(s) given their + # UUID(s). + class SuspendUsersResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [SuspendUsersResponseData, nil] The response data for this request. + attribute :data, "SuspendUsersResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class SuspendUsersResponseData < Unikraft::Cloud::Model + # @!attribute [r] users + # @return [Array, nil] + attribute :users, "SuspendUsersResponseSuspendedUser", array: true + end + + # An instance that a suspend users operation brought to rest. + class SuspendUsersResponseSuspendedInstance < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The current state of the instance. + attribute :state + # @!attribute [r] previous_state + # @return [String, nil] The previous state of the instance before the suspend operation was + # invoked. + attribute :previous_state + # @!attribute [r] on_resume + # @return [String, nil] What resuming the user will do with this instance. Absent if the + # instance was already at rest and resuming the user leaves it unchanged. + attribute :on_resume + end + + # Per-item result for a suspend users operation. + class SuspendUsersResponseSuspendedUser < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] suspended + # @return [Boolean, nil] Whether the user account is suspended after this request. + attribute :suspended + # @!attribute [r] instances + # @return [Array, nil] The instances of the user that were brought to rest. Only present if + # `suspend_instances` was set in the request. + attribute :instances, "SuspendUsersResponseSuspendedInstance", array: true + end + + # What resuming a user does with an instance that the suspension of the user + # brought to rest. + # + # | Action | Description | + # |-----------|-------------| + # | `standby` | Autostart is enabled again. The instance is in standby and starts on the next incoming request. | + # | `start` | The instance is started. | + module UserResumeAction + STANDBY = "standby" + START = "start" + + # Every value of this enumeration. + ALL = [STANDBY, START].freeze + end + + # The `AttachVolumeByUUIDRequestBody` model. + class AttachVolumeByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] attach_to + # @return [NameOrUUID, nil] UUID or name of the instance to attach the volume to. + attribute :attach_to, "NameOrUUID" + # @!attribute [r] at + # @return [String, nil] Path of the mountpoint. + # + # The path must be absolute, not contain `.` and `..` components, and not + # contain colons (`:`). The path must point to an empty directory. If the + # directory does not exist, it is created. + attribute :at + # @!attribute [r] readonly + # @return [Boolean, nil] Whether the volume should be mounted read-only. + attribute :readonly + end + + # A single request item to attach a volume to an instance. + class AttachVolumesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] attach_to + # @return [NameOrUUID, nil] UUID or name of the instance to attach the volume to. + attribute :attach_to, "NameOrUUID" + # @!attribute [r] at + # @return [String, nil] Path of the mountpoint. + # + # The path must be absolute, not contain `.` and `..` components, and not + # contain colons (`:`). The path must point to an empty directory. If the + # directory does not exist, it is created. + attribute :at + # @!attribute [r] readonly + # @return [Boolean, nil] Whether the volume should be mounted read-only. + attribute :readonly + end + + # The response message for attaching one or more volume(s) given their + # UUID(s) or name(s). + class AttachVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [AttachVolumesResponseData, nil] The response data for this request. + attribute :data, "AttachVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # Per-item result for an attach volumes operation. + class AttachVolumesResponseAttachedVolume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # The response data for this request. + class AttachVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "AttachVolumesResponseAttachedVolume", array: true + end + + # The `CloneVolumeByUUIDRequestBody` model. + class CloneVolumeByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] vol_name + # @return [String, nil] The name of the new cloned volume. If not provided, a random name + # of the form `vol-X` is generated for you, where `X` is a 5 character + # long random alphanumeric suffix. + attribute :vol_name + # @!attribute [r] quota_policy + # @return [String, nil] The quota policy for the new cloned volume. If not provided, the quota + # policy of the source volume is used. + attribute :quota_policy + # @!attribute [r] tags + # @return [Array, nil] A list of tags to assign to the new cloned volume. + attribute :tags + # @!attribute [r] access_mode + # @return [String, nil] + attribute :access_mode + end + + # A single request item to clone a volume. + class CloneVolumesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] vol_name + # @return [String, nil] The name of the new cloned volume. If not provided, a random name + # of the form `vol-X` is generated for you, where `X` is a 5 character + # long random alphanumeric suffix. + attribute :vol_name + # @!attribute [r] quota_policy + # @return [String, nil] The quota policy for the new cloned volume. If not provided, the quota + # policy of the source volume is used. + attribute :quota_policy + # @!attribute [r] tags + # @return [Array, nil] A list of tags to assign to the new cloned volume. + attribute :tags + # @!attribute [r] access_mode + # @return [String, nil] + attribute :access_mode + end + + # The response message for cloning one or more volume(s) given their UUID(s) + # or name(s). + class CloneVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CloneVolumesResponseData, nil] The response data for this request. + attribute :data, "CloneVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class CloneVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "CloneVolumesResponseVolume", array: true + end + + # Per-item result for a clone volumes operation. + class CloneVolumesResponseVolume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The state of the volume. + attribute :state + end + + # The response message for converting one or more volume(s) to templates. + class CreateTemplateVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CreateTemplateVolumesResponseData, nil] The response data for this request. + attribute :data, "CreateTemplateVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class CreateTemplateVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] The volume(s) which were attached by the request. + attribute :volumes, "CreateTemplateVolumesResponseTemplateVolume", array: true + end + + # Per-item result for a create template volume operation. + class CreateTemplateVolumesResponseTemplateVolume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The state of the volume. + attribute :state + end + + # The request message for creating a volume. + class CreateVolumeRequest < Unikraft::Cloud::Model + # @!attribute [r] name + # @return [String, nil] The name of the resource. If not provided, a random name is generated. + # The name must be unique within the context of your account. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node to place the resource on. If not provided, the + # platform picks one. Only accepted on metros that span multiple nodes. + attribute :node + # @!attribute [r] size_mb + # @return [Integer, nil] + attribute :size_mb + # @!attribute [r] host_path + # @return [String, nil] + attribute :host_path + # @!attribute [r] template + # @return [NameOrUUID, nil] + attribute :template, "NameOrUUID" + # @!attribute [r] quota_policy + # @return [String, nil] + attribute :quota_policy + # @!attribute [r] filesystem + # @return [String, nil] + attribute :filesystem + # @!attribute [r] tags + # @return [Array, nil] + attribute :tags + # @!attribute [r] uid + # @return [Integer, nil] + attribute :uid + # @!attribute [r] gid + # @return [Integer, nil] + attribute :gid + # @!attribute [r] access_mode + # @return [String, nil] + attribute :access_mode + # @!attribute [r] args + # @return [Hash{Symbol => String}, nil] + attribute :args + end + + # The response message for creating a volume. + class CreateVolumeResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [CreateVolumeResponseData, nil] The response data for this request. + attribute :data, "CreateVolumeResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class CreateVolumeResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "CreateVolumeResponseVolume", array: true + end + + # Per-item result for a create volume operation. + class CreateVolumeResponseVolume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] state + # @return [String, nil] The state of the volume. + attribute :state + end + + # The response message for deleting one or more template volume(s) given + # their UUID(s) or name(s). + class DeleteTemplateVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DeleteTemplateVolumesResponseData, nil] The response data for this request. + attribute :data, "DeleteTemplateVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class DeleteTemplateVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "DeleteTemplateVolumesResponseTemplateVolume", array: true + end + + # Per-item result for a delete template volumes operation. + class DeleteTemplateVolumesResponseTemplateVolume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # The response message for deleting one or more volume(s) given their + # UUID(s) or name(s). + class DeleteVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DeleteVolumesResponseData, nil] The response data for this request. + attribute :data, "DeleteVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class DeleteVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "DeleteVolumesResponseDeletedVolume", array: true + end + + # Per-item result for a delete volumes operation. + class DeleteVolumesResponseDeletedVolume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # The `DetachVolumeByUUIDRequestBody` model. + class DetachVolumeByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] from + # @return [NameOrUUID, nil] UUID or name of the instance to detach the volume from. If not specified, + # the volume is detached from all instances. + attribute :from, "NameOrUUID" + end + + # A single request item to detach a volume from an instance. + class DetachVolumesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] from + # @return [NameOrUUID, nil] UUID or name of the instance to detach the volume from. If not specified, + # the volume is detached from all instances. + attribute :from, "NameOrUUID" + end + + # The response message for detaching one or more volume(s) given their + # UUID(s) or name(s). + class DetachVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [DetachVolumesResponseData, nil] The response data for this request. + attribute :data, "DetachVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class DetachVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "DetachVolumesResponseDetachedVolume", array: true + end + + # Per-item result for a detach volumes operation. + class DetachVolumesResponseDetachedVolume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + end + + # The response message for getting one or more template volume(s) given their + # UUID(s) or name(s). + class GetTemplateVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetTemplateVolumesResponseData, nil] The response data for this request. + attribute :data, "GetTemplateVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetTemplateVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "Volume", array: true + end + + # The response message for getting one or more volume(s) given their UUID(s) + # or name(s). + class GetVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [GetVolumesResponseData, nil] The response data for this request. + attribute :data, "GetVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class GetVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "Volume", array: true + end + + # Mutable template volume operations. + module MutableTemplateVolumeOperation + SET = "set" + ADD = "add" + DEL = "del" + + # Every value of this enumeration. + ALL = [SET, ADD, DEL].freeze + end + + # Mutable template volume properties. + module MutableTemplateVolumeProperty + TAGS = "tags" + DELETE_LOCK = "delete_lock" + + # Every value of this enumeration. + ALL = [TAGS, DELETE_LOCK].freeze + end + + # Mutable volume operations. + module MutableVolumeOperation + SET = "set" + ADD = "add" + DEL = "del" + + # Every value of this enumeration. + ALL = [SET, ADD, DEL].freeze + end + + # Mutable volume properties. + module MutableVolumeProperty + SIZE_MB = "size_mb" + TAGS = "tags" + QUOTA_POLICY = "quota_policy" + DELETE_LOCK = "delete_lock" + + # Every value of this enumeration. + ALL = [SIZE_MB, TAGS, QUOTA_POLICY, DELETE_LOCK].freeze + end + + # The `UpdateTemplateVolumeByUUIDRequestBody` model. + class UpdateTemplateVolumeByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "image": string + # - For "args": string or array of strings + # - For "env": object (for SET/ADD) or string/array of strings (for DEL) + # - For "memory_mb": integer + # - For "vcpus": integer + # - For "scale_to_zero": object with cooldown_time_ms, policy, and stateful fields + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "schedules": array of schedule objects (with name, when, action, and optional args fields). + # Use action "exec" together with args to execute a command at the scheduled time. + # - For "autokill": object with time_ms and num_requests fields + # - For "hostname": string (valid DNS label) + # - For "roms": array of ROM objects (with name and image fields) for SET/ADD, or array of ROM names for DEL + # - For "dependencies": array of instance identifiers (name or UUID) + # - For "sched_priority": SchedPriority enum value ("normal", "medium", "high", "admin") + attribute :value + end + + # A single update operation to be applied to a template volume. + class UpdateTemplateVolumesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "image": string + # - For "args": string or array of strings + # - For "env": object (for SET/ADD) or string/array of strings (for DEL) + # - For "memory_mb": integer + # - For "vcpus": integer + # - For "scale_to_zero": object with cooldown_time_ms, policy, and stateful fields + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "schedules": array of schedule objects (with name, when, action, and optional args fields). + # Use action "exec" together with args to execute a command at the scheduled time. + # - For "autokill": object with time_ms and num_requests fields + # - For "hostname": string (valid DNS label) + # - For "roms": array of ROM objects (with name and image fields) for SET/ADD, or array of ROM names for DEL + # - For "dependencies": array of instance identifiers (name or UUID) + # - For "sched_priority": SchedPriority enum value ("normal", "medium", "high", "admin") + attribute :value + end + + # The response message for updating one or more template volume(s) given + # their UUID(s) or name(s). + class UpdateTemplateVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [UpdateTemplateVolumesResponseData, nil] The response data for this request. + attribute :data, "UpdateTemplateVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class UpdateTemplateVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "UpdateTemplateVolumesResponseTemplateVolume", array: true + end + + # Per-item result for an update template volumes operation. + class UpdateTemplateVolumesResponseTemplateVolume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] id + # @return [String, nil] The client-provided ID from the request. + attribute :id + end + + # The `UpdateVolumeByUUIDRequestBody` model. + class UpdateVolumeByUUIDRequestBody < Unikraft::Cloud::Model + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "image": string + # - For "args": string or array of strings + # - For "env": object (for SET/ADD) or string/array of strings (for DEL) + # - For "memory_mb": integer + # - For "vcpus": integer + # - For "scale_to_zero": object with cooldown_time_ms, policy, and stateful fields + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "schedules": array of schedule objects (with name, when, action, and optional args fields). + # Use action "exec" together with args to execute a command at the scheduled time. + # - For "autokill": object with time_ms and num_requests fields + # - For "hostname": string (valid DNS label) + # - For "roms": array of ROM objects (with name and image fields) for SET/ADD, or array of ROM names for DEL + # - For "dependencies": array of instance identifiers (name or UUID) + # - For "sched_priority": SchedPriority enum value ("normal", "medium", "high", "admin") + attribute :value + end + + # A single update operation to be applied to a volume. + class UpdateVolumesRequestItem < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the resource. + attribute :name + # @!attribute [r] id + # @return [String, nil] A client-provided identifier for tracking this operation in the response. + attribute :id + # @!attribute [r] prop + # @return [String, nil] The property to modify. + attribute :prop + # @!attribute [r] op + # @return [String, nil] The operation to perform. + attribute :op + # @!attribute [r] value + # @return [Object, nil] The value for the update operation. The type depends on the property and operation: + # - For "image": string + # - For "args": string or array of strings + # - For "env": object (for SET/ADD) or string/array of strings (for DEL) + # - For "memory_mb": integer + # - For "vcpus": integer + # - For "scale_to_zero": object with cooldown_time_ms, policy, and stateful fields + # - For "tags": array of strings + # - For "delete_lock": boolean + # - For "schedules": array of schedule objects (with name, when, action, and optional args fields). + # Use action "exec" together with args to execute a command at the scheduled time. + # - For "autokill": object with time_ms and num_requests fields + # - For "hostname": string (valid DNS label) + # - For "roms": array of ROM objects (with name and image fields) for SET/ADD, or array of ROM names for DEL + # - For "dependencies": array of instance identifiers (name or UUID) + # - For "sched_priority": SchedPriority enum value ("normal", "medium", "high", "admin") + attribute :value + end + + # The response message for updating one or more volume(s) given their + # UUID(s) or name(s). + class UpdateVolumesResponse < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] The status of the response. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information about the status. + attribute :message + # @!attribute [r] data + # @return [UpdateVolumesResponseData, nil] The response data for this request. + attribute :data, "UpdateVolumesResponseData" + # @!attribute [r] errors + # @return [Array, nil] A list of errors which may have occurred during the request. + attribute :errors, "ResponseError", array: true + # @!attribute [r] op_time_us + # @return [Integer, nil] The operation time in microseconds. + attribute :op_time_us + end + + # The response data for this request. + class UpdateVolumesResponseData < Unikraft::Cloud::Model + # @!attribute [r] volumes + # @return [Array, nil] + attribute :volumes, "UpdateVolumesResponseUpdatedVolume", array: true + end + + # Per-item result for an update volumes operation. + class UpdateVolumesResponseUpdatedVolume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] id + # @return [String, nil] The client-provided ID from the request. + attribute :id + end + + # A volume represents a storage device that can be attached to an instance. + class Volume < Unikraft::Cloud::Model + # @!attribute [r] status + # @return [String, nil] Indicates whether the operation was successful for this item. + attribute :status + # @!attribute [r] message + # @return [String, nil] An optional message providing additional information. + attribute :message + # @!attribute [r] error + # @return [Integer, nil] An optional error code. + attribute :error + # @!attribute [r] uuid + # @return [String, nil] The UUID of the resource. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The human-readable name of the resource. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] created_at + # @return [String, nil] The time the volume was created. + attribute :created_at + # @!attribute [r] state + # @return [String, nil] Current state of the volume. + attribute :state + # @!attribute [r] size_mb + # @return [Integer, nil] The size of the volume in megabytes. + attribute :size_mb + # @!attribute [r] persistent + # @return [Boolean, nil] Indicates if the volume will stay alive when the last instance is deleted + # that this volume is attached to. + attribute :persistent + # @!attribute [r] attached_to + # @return [Array, nil] List of instances that this volume is attached to. + attribute :attached_to, "VolumeInstanceID", array: true + # @!attribute [r] mounted_by + # @return [Array, nil] List of instances that have this volume mounted. + # This does not apply to template volumes. + attribute :mounted_by, "VolumeInstanceMount", array: true + # @!attribute [r] tags + # @return [Array, nil] The tags associated with the volume. + # Maximum 16 tags are allowed, and each tag may not be longer than 256 characters. + attribute :tags + # @!attribute [r] quota_policy + # @return [String, nil] Either static or dynamic reservation. + attribute :quota_policy + # @!attribute [r] delete_lock + # @return [Boolean, nil] If set to true, the volume cannot be deleted. + attribute :delete_lock + # @!attribute [r] free_mb + # @return [Integer, nil] The amount of free space in the volume in megabytes. + attribute :free_mb + # @!attribute [r] filesystem + # @return [String, nil] The filesystem type of this volume. + # Without custom configuration, this is either `ext4` or `virtiofs`. + attribute :filesystem + # @!attribute [r] host_path + # @return [String, nil] Host path backing this managed volume. + # This field is only available for managed volumes and users with + # appropriate permissions. + attribute :host_path + # @!attribute [r] access_mode + # @return [String, nil] The access mode of the volume, controlling volume sharing behavior. + # Defaults to `rwo` if not specified. + attribute :access_mode + # @!attribute [r] uid + # @return [Integer, nil] Guest UID for managed volumes (host_path mode only). + attribute :uid + # @!attribute [r] gid + # @return [Integer, nil] Guest GID for managed volumes (host_path mode only). + attribute :gid + # @!attribute [r] args + # @return [Hash{Symbol => String}, nil] Optional script arguments that were applied to the custom volume filesystem + # initialization scripts. + attribute :args + end + + # VolumeAccessMode defines the access mode of a volume, which controls sharing + # behavior and caching strategy. + module VolumeAccessMode + RWO = "rwo" + ROX = "rox" + RWX = "rwx" + + # Every value of this enumeration. + ALL = [RWO, ROX, RWX].freeze + end + + # An instance a volume is attached to. + class VolumeInstanceID < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the instance. This is a unique identifier for the instance + # that is generated when the instance is created. The UUID is used to + # reference the instance in API calls and can be used to identify the + # instance in all API calls that require an instance identifier. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the instance. This is a human-readable name that can be used + # to identify the instance. The name must be unique within the context of + # your account. If no name is specified, a random name is generated for + # you. The name can also be used to identify the instance in API calls. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the instance is placed on. + attribute :node + end + + # An instance mount of a volume. + class VolumeInstanceMount < Unikraft::Cloud::Model + # @!attribute [r] uuid + # @return [String, nil] The UUID of the instance that the volume is mounted in. + attribute :uuid + # @!attribute [r] name + # @return [String, nil] The name of the instance that the volume is mounted in. + attribute :name + # @!attribute [r] node + # @return [String, nil] The name of the node the resource is placed on. Only present on metros + # that span multiple nodes. + attribute :node + # @!attribute [r] readonly + # @return [Boolean, nil] Whether the volume is mounted read-only or read-write. + attribute :readonly + end + + # Quota policy for a volume. + module VolumeQuotaPolicy + STATIC = "static" + DYNAMIC = "dynamic" + + # Every value of this enumeration. + ALL = [STATIC, DYNAMIC].freeze + end + + # VolumeState defines the state of a volume at a given moment. + module VolumeState + UNINITIALIZED = "uninitialized" + INITIALIZING = "initializing" + AVAILABLE = "available" + IDLE = "idle" + MOUNTED = "mounted" + BUSY = "busy" + ERROR = "error" + TEMPLATE = "template" + + # Every value of this enumeration. + ALL = [UNINITIALIZED, INITIALIZING, AVAILABLE, IDLE, MOUNTED, BUSY, ERROR, TEMPLATE].freeze + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/node.gen.rb b/lib/unikraft/cloud/api/platform/node.gen.rb new file mode 100644 index 0000000..f392e57 --- /dev/null +++ b/lib/unikraft/cloud/api/platform/node.gen.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class Platform + # Low-level "plumbing" client for the `node` resource of the + # Platform API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class NodeApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Health Check + # + # `GET /v1/healthz` + # + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::HealthzResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def healthz(**options) + res = @client.request( + method: "GET", + path: "/v1/healthz", + **options + ) + Models::HealthzResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/resources.gen.rb b/lib/unikraft/cloud/api/platform/resources.gen.rb new file mode 100644 index 0000000..e2672c5 --- /dev/null +++ b/lib/unikraft/cloud/api/platform/resources.gen.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. +# +# Loads every generated client of the Platform API. + +require_relative "models.gen" +require_relative "audit.gen" +require_relative "autoscale.gen" +require_relative "certificates.gen" +require_relative "images.gen" +require_relative "instances.gen" +require_relative "node.gen" +require_relative "services.gen" +require_relative "users.gen" +require_relative "volumes.gen" diff --git a/lib/unikraft/cloud/api/platform/services.gen.rb b/lib/unikraft/cloud/api/platform/services.gen.rb new file mode 100644 index 0000000..8e7c64a --- /dev/null +++ b/lib/unikraft/cloud/api/platform/services.gen.rb @@ -0,0 +1,172 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class Platform + # Low-level "plumbing" client for the `services` resource of the + # Platform API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class ServicesApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Create Service Group + # + # `POST /v1/services` + # + # @param body [Models::CreateServiceGroupRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateServiceGroupResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_service_group(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/services", + body:, + **options + ) + Models::CreateServiceGroupResponse.from(res) + end + + # Delete Service Group by UUID + # + # `DELETE /v1/services/{uuid}` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteServiceGroupsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_service_group_by_uuid(uuid:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}", + **options + ) + Models::DeleteServiceGroupsResponse.from(res) + end + + # Delete Service Groups + # + # `DELETE /v1/services` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteServiceGroupsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_service_groups(body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/services", + body:, + **options + ) + Models::DeleteServiceGroupsResponse.from(res) + end + + # Get Service Group by UUID + # + # `GET /v1/services/{uuid}` + # + # @param uuid [String] + # @param details [Boolean, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetServiceGroupsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_service_group_by_uuid(uuid:, details: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}", + query: { + details: + }, + **options + ) + Models::GetServiceGroupsResponse.from(res) + end + + # List Service Groups + # + # `GET /v1/services` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param details [Boolean, nil] + # @param count [Integer, nil] + # @param from [String, nil] + # @param order [String, nil] + # @param sortby [String, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetServiceGroupsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_service_groups(uuid: nil, name: nil, details: nil, count: nil, from: nil, order: nil, sortby: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/services", + query: { + uuid:, + name:, + details:, + count:, + from:, + order:, + sortby: + }, + **options + ) + Models::GetServiceGroupsResponse.from(res) + end + + # Update Service Group by UUID + # + # `PATCH /v1/services/{uuid}` + # + # @param uuid [String] + # @param body [Models::UpdateServiceGroupByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateServiceGroupsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_service_group_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/services/#{Core::URL.escape_segment(uuid)}", + body:, + **options + ) + Models::UpdateServiceGroupsResponse.from(res) + end + + # Update Service Groups + # + # `PATCH /v1/services` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateServiceGroupsResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_service_groups(body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/services", + body:, + **options + ) + Models::UpdateServiceGroupsResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/users.gen.rb b/lib/unikraft/cloud/api/platform/users.gen.rb new file mode 100644 index 0000000..a13b265 --- /dev/null +++ b/lib/unikraft/cloud/api/platform/users.gen.rb @@ -0,0 +1,134 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class Platform + # Low-level "plumbing" client for the `users` resource of the + # Platform API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class UsersApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Get Current User Quotas + # + # `GET /v1/users/quotas` + # + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::QuotasResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_user(**options) + res = @client.request( + method: "GET", + path: "/v1/users/quotas", + **options + ) + Models::QuotasResponse.from(res) + end + + # Get User Quotas by UUID + # + # `GET /v1/users/{uuid}/quotas` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::QuotasResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_user_by_uuid(uuid:, **options) + res = @client.request( + method: "GET", + path: "/v1/users/#{Core::URL.escape_segment(uuid)}/quotas", + **options + ) + Models::QuotasResponse.from(res) + end + + # Resume User by UUID + # + # `PUT /v1/users/{uuid}/resume` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::ResumeUsersResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def resume_user_by_uuid(uuid:, **options) + res = @client.request( + method: "PUT", + path: "/v1/users/#{Core::URL.escape_segment(uuid)}/resume", + **options + ) + Models::ResumeUsersResponse.from(res) + end + + # Resume Users + # + # `PUT /v1/users/resume` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::ResumeUsersResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def resume_users(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/users/resume", + body:, + **options + ) + Models::ResumeUsersResponse.from(res) + end + + # Suspend User by UUID + # + # `PUT /v1/users/{uuid}/suspend` + # + # @param uuid [String] + # @param body [Models::SuspendUserByUUIDRequestBody, Hash, Array, nil] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::SuspendUsersResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def suspend_user_by_uuid(uuid:, body: nil, **options) + res = @client.request( + method: "PUT", + path: "/v1/users/#{Core::URL.escape_segment(uuid)}/suspend", + body:, + **options + ) + Models::SuspendUsersResponse.from(res) + end + + # Suspend Users + # + # `PUT /v1/users/suspend` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::SuspendUsersResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def suspend_users(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/users/suspend", + body:, + **options + ) + Models::SuspendUsersResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/api/platform/volumes.gen.rb b/lib/unikraft/cloud/api/platform/volumes.gen.rb new file mode 100644 index 0000000..216a331 --- /dev/null +++ b/lib/unikraft/cloud/api/platform/volumes.gen.rb @@ -0,0 +1,430 @@ +# frozen_string_literal: true + +# Code generated by openapi-gen; DO NOT EDIT. + +require_relative "../../core/url" +require_relative "models.gen" + +module Unikraft + module Cloud + class API + class Platform + # Low-level "plumbing" client for the `volumes` resource of the + # Platform API. Methods mirror the OpenAPI specification: they are + # named after the operationId and return the response envelope + # untouched. + class VolumesApi + # @return [#request, #bytes, #stream] the transport, usually a + # {Unikraft::Cloud::Core::ApiClient} + attr_reader :client + + # @param client [#request, #bytes, #stream] the transport + def initialize(client) + @client = client + end + + # Attach Volume by UUID + # + # `PUT /v1/volumes/{uuid}/attach` + # + # @param uuid [String] + # @param body [Models::AttachVolumeByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::AttachVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def attach_volume_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/volumes/#{Core::URL.escape_segment(uuid)}/attach", + body:, + **options + ) + Models::AttachVolumesResponse.from(res) + end + + # Attach Volumes + # + # `PUT /v1/volumes/attach` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::AttachVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def attach_volumes(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/volumes/attach", + body:, + **options + ) + Models::AttachVolumesResponse.from(res) + end + + # Clone Volume by UUID + # + # `POST /v1/volumes/{uuid}/clone` + # + # @param uuid [String] + # @param body [Models::CloneVolumeByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CloneVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def clone_volume_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "POST", + path: "/v1/volumes/#{Core::URL.escape_segment(uuid)}/clone", + body:, + **options + ) + Models::CloneVolumesResponse.from(res) + end + + # Clone Volumes + # + # `POST /v1/volumes/clone` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CloneVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def clone_volumes(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/volumes/clone", + body:, + **options + ) + Models::CloneVolumesResponse.from(res) + end + + # Create Template Volume + # + # `POST /v1/volumes/templates` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateTemplateVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_template_volume(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/volumes/templates", + body:, + **options + ) + Models::CreateTemplateVolumesResponse.from(res) + end + + # Create Volume + # + # `POST /v1/volumes` + # + # @param body [Models::CreateVolumeRequest, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::CreateVolumeResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def create_volume(body:, **options) + res = @client.request( + method: "POST", + path: "/v1/volumes", + body:, + **options + ) + Models::CreateVolumeResponse.from(res) + end + + # Delete Template Volume by UUID + # + # `DELETE /v1/volumes/templates/{uuid}` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteTemplateVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_template_volume_by_uuid(uuid:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/volumes/templates/#{Core::URL.escape_segment(uuid)}", + **options + ) + Models::DeleteTemplateVolumesResponse.from(res) + end + + # Delete Template Volumes + # + # `DELETE /v1/volumes/templates` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteTemplateVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_template_volumes(body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/volumes/templates", + body:, + **options + ) + Models::DeleteTemplateVolumesResponse.from(res) + end + + # Delete Volume by UUID + # + # `DELETE /v1/volumes/{uuid}` + # + # @param uuid [String] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_volume_by_uuid(uuid:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/volumes/#{Core::URL.escape_segment(uuid)}", + **options + ) + Models::DeleteVolumesResponse.from(res) + end + + # Delete Volumes + # + # `DELETE /v1/volumes` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DeleteVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def delete_volumes(body:, **options) + res = @client.request( + method: "DELETE", + path: "/v1/volumes", + body:, + **options + ) + Models::DeleteVolumesResponse.from(res) + end + + # Detach Volume by UUID + # + # `PUT /v1/volumes/{uuid}/detach` + # + # @param uuid [String] + # @param body [Models::DetachVolumeByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DetachVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def detach_volume_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/volumes/#{Core::URL.escape_segment(uuid)}/detach", + body:, + **options + ) + Models::DetachVolumesResponse.from(res) + end + + # Detach Volumes + # + # `PUT /v1/volumes/detach` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::DetachVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def detach_volumes(body:, **options) + res = @client.request( + method: "PUT", + path: "/v1/volumes/detach", + body:, + **options + ) + Models::DetachVolumesResponse.from(res) + end + + # Get Template Volume by UUID + # + # `GET /v1/volumes/templates/{uuid}` + # + # @param uuid [String] + # @param details [Boolean, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetTemplateVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_template_volume_by_uuid(uuid:, details: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/volumes/templates/#{Core::URL.escape_segment(uuid)}", + query: { + details: + }, + **options + ) + Models::GetTemplateVolumesResponse.from(res) + end + + # List Template Volumes + # + # `GET /v1/volumes/templates` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param details [Boolean, nil] + # @param count [Integer, nil] + # @param from [String, nil] + # @param order [String, nil] + # @param sortby [String, nil] + # @param tags [Array, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetTemplateVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_template_volumes(uuid: nil, name: nil, details: nil, count: nil, from: nil, order: nil, sortby: nil, tags: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/volumes/templates", + query: { + uuid:, + name:, + details:, + count:, + from:, + order:, + sortby:, + tags: tags&.join(",") + }, + **options + ) + Models::GetTemplateVolumesResponse.from(res) + end + + # Get Volume by UUID + # + # `GET /v1/volumes/{uuid}` + # + # @param uuid [String] + # @param details [Boolean, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_volume_by_uuid(uuid:, details: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/volumes/#{Core::URL.escape_segment(uuid)}", + query: { + details: + }, + **options + ) + Models::GetVolumesResponse.from(res) + end + + # List Volumes + # + # `GET /v1/volumes` + # + # @param uuid [Array, nil] The UUID of the resource. + # @param name [Array, nil] The name of the resource. + # @param details [Boolean, nil] + # @param count [Integer, nil] + # @param from [String, nil] + # @param order [String, nil] + # @param sortby [String, nil] + # @param tags [Array, nil] + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::GetVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def get_volumes(uuid: nil, name: nil, details: nil, count: nil, from: nil, order: nil, sortby: nil, tags: nil, **options) + res = @client.request( + method: "GET", + path: "/v1/volumes", + query: { + uuid:, + name:, + details:, + count:, + from:, + order:, + sortby:, + tags: tags&.join(",") + }, + **options + ) + Models::GetVolumesResponse.from(res) + end + + # Update Template Volume by UUID + # + # `PATCH /v1/volumes/templates/{uuid}` + # + # @param uuid [String] + # @param body [Models::UpdateTemplateVolumeByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateTemplateVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_template_volume_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/volumes/templates/#{Core::URL.escape_segment(uuid)}", + body:, + **options + ) + Models::UpdateTemplateVolumesResponse.from(res) + end + + # Update Template Volumes + # + # `PATCH /v1/volumes/templates` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateTemplateVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_template_volumes(body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/volumes/templates", + body:, + **options + ) + Models::UpdateTemplateVolumesResponse.from(res) + end + + # Update Volume by UUID + # + # `PATCH /v1/volumes/{uuid}` + # + # @param uuid [String] + # @param body [Models::UpdateVolumeByUUIDRequestBody, Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_volume_by_uuid(uuid:, body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/volumes/#{Core::URL.escape_segment(uuid)}", + body:, + **options + ) + Models::UpdateVolumesResponse.from(res) + end + + # Update Volumes + # + # `PATCH /v1/volumes` + # + # @param body [Hash, Array] the request body + # @param options [Hash] per-call `headers:`, `base_url:` and `timeout:` + # @return [Models::UpdateVolumesResponse, nil] the response envelope + # @raise [Unikraft::Cloud::Error] + def update_volumes(body:, **options) + res = @client.request( + method: "PATCH", + path: "/v1/volumes", + body:, + **options + ) + Models::UpdateVolumesResponse.from(res) + end + end + end + end + end +end diff --git a/lib/unikraft/cloud/core/url.rb b/lib/unikraft/cloud/core/url.rb index fe114b6..d56030d 100644 --- a/lib/unikraft/cloud/core/url.rb +++ b/lib/unikraft/cloud/core/url.rb @@ -3,6 +3,8 @@ # SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2026, Unikraft GmbH. +require "uri" + module Unikraft module Cloud module Core @@ -17,6 +19,15 @@ module URL def strip_trailing_slashes(url) url.to_s.sub(%r{/+\z}, "") end + + # Percent-encode one path segment, so a value with a `/`, `?` or `#` + # in it cannot change the path or start a query. + # + # @param value [#to_s] + # @return [String] + def escape_segment(value) + URI.encode_www_form_component(value.to_s).gsub("+", "%20") + end end end end diff --git a/test/unit/api_test.rb b/test/unit/api_test.rb new file mode 100644 index 0000000..76b016b --- /dev/null +++ b/test/unit/api_test.rb @@ -0,0 +1,138 @@ +# frozen_string_literal: true + +require_relative "../test_helper" + +# A transport that records each call and answers with a canned value. +class RecordingTransport + attr_reader :calls + + def initialize(response = { status: "success" }, events: []) + @response = response + @events = events + @calls = [] + end + + def request(**args) + @calls << [:request, args] + @response + end + + def bytes(**args) + @calls << [:bytes, args] + "\x00".b + end + + def stream(**args, &) + @calls << [:stream, args] + @events.each(&) + end +end + +class ApiTest < Minitest::Test + API = Unikraft::Cloud::API + + def resource_classes + [API::Platform, API::ControlPlane].flat_map do |surface| + surface.constants.map { |c| surface.const_get(c) } + .select { |k| k.is_a?(Class) && k.name.end_with?("Api") } + end + end + + # Fill every required keyword with a value that needs escaping in a path. + def required_args(meth) + meth.parameters.filter_map { |kind, name| [name, "a b/c"] if kind == :keyreq }.to_h + end + + def test_every_generated_operation_builds_a_request + count = 0 + resource_classes.each do |klass| + klass.public_instance_methods(false).each do |name| + next if name == :client + + transport = RecordingTransport.new + api = klass.new(transport) + meth = api.method(name) + args = required_args(meth).merge(headers: { "X" => "1" }) + # Only an event stream takes a block; it yields nothing here. + if meth.parameters.any? { |kind, _| kind == :block } + api.public_send(name, **args) { nil } + else + api.public_send(name, **args) + end + kind, args = transport.calls.fetch(0) + count += 1 + + assert_includes %i[request bytes stream], kind + assert_includes %w[GET POST PUT PATCH DELETE HEAD], args[:method], "#{klass}##{name}" + assert args[:path].start_with?("/"), "#{klass}##{name}: #{args[:path]}" + refute_includes args[:path], "{", "#{klass}##{name}: unfilled path parameter" + refute_includes args[:path], " ", "#{klass}##{name}: unescaped path parameter" + refute args.key?(:body) && %w[GET HEAD].include?(args[:method]), + "#{klass}##{name} sends a body on #{args[:method]}" + assert_equal({ "X" => "1" }, args[:headers], "#{klass}##{name} drops options") + end + end + + assert_operator count, :>, 50 + end + + def test_get_instances + transport = RecordingTransport.new({ status: "success", + data: { instances: [{ name: "web" }] } }) + instances = API::Platform.new(transport).instances + res = instances.get_instances(name: %w[a b], tags: %w[x y], count: 2, base_url: "https://other") + + assert_kind_of API::Platform::Models::GetInstancesResponse, res + assert_equal "web", res.data.instances.first.name + assert_equal [:request, { method: "GET", path: "/v1/instances", + query: { uuid: nil, name: %w[a b], details: nil, count: 2, from: nil, + order: nil, sortby: nil, tags: "x,y" }, + base_url: "https://other" }], transport.calls.first + end + + def test_update_instances_sends_the_body + transport = RecordingTransport.new + body = [{ name: "web", prop: "memory_mb", op: "set", value: 256 }] + API::Platform.new(transport).instances.update_instances(body:) + + assert_equal({ method: "PATCH", path: "/v1/instances", body: body }, transport.calls.first[1]) + end + + def test_path_parameters_are_escaped + transport = RecordingTransport.new + API::Platform.new(transport).instances.get_instance_by_uuid(uuid: "a/b?c") + + assert_equal "/v1/instances/a%2Fb%3Fc", transport.calls.first[1][:path] + end + + def test_event_streams_yield_models + transport = RecordingTransport.new(events: [{ type: "start" }]) + audit = API::Platform.new(transport).audit + events = audit.subscribe_audit_events(events: ["start"]).to_a + + assert_equal [API::Platform::Models::AuditEvent.new(type: "start")], events + assert_equal :stream, transport.calls.first[0] + end + + def test_empty_response_is_nil + assert_nil API::Platform.new(RecordingTransport.new(nil)).instances.get_instances + end + + def test_enums_are_frozen_constants + states = API::Platform::Models::InstanceState + + assert_equal "running", states::RUNNING + assert_includes states::ALL, "stopped" + assert_predicate states::ALL, :frozen? + end + + def test_containers + api = API.new(platform: { base_url: "https://api.fra.unikraft.cloud", token: "t" }, + controlplane: RecordingTransport.new) + + assert_kind_of API::Platform::InstancesApi, api.platform.instances + assert_equal "https://api.fra.unikraft.cloud", api.platform.client.base_url + assert_kind_of API::ControlPlane::MetrosApi, api.controlplane.metros + assert_same api.platform.client, api.platform.volumes.client + end +end From 382a8db3f1406827965dceec3625688195f8d54e Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 15:55:48 -0800 Subject: [PATCH 14/30] docs: Name the core files and the stream contract Point CONTRIBUTING.md at model.rb, api.rb, http.rb and ready.rb, and say that stream yields each server-sent event's parsed data rather than raw chunks, which is what the transport does. Signed-off-by: Alexander Jung --- CONTRIBUTING.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2056e63..19d5ab8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,12 +12,15 @@ lib/ cloud.rb # entry point: Unikraft::Cloud.new and the public requires cloud/ version.rb # VERSION = "0.0.0" placeholder, stamped by the release + model.rb # Model, the base class of every generated model api/ # the "plumbing" layer: raw, spec-shaped platform/ # GENERATED (*.gen.rb): one class per tag + models controlplane/ # GENERATED (*.gen.rb) *.rb # hand-written API::Platform / API::ControlPlane containers - core/ # hand-written shared machinery: transport, errors, - # metros, fan-out, pagination, models + api.rb # hand-written API container behind `ukc.api` + core/ # hand-written shared machinery: transport (http.rb), + # errors, readiness polling (ready.rb), metros, + # fan-out, pagination resources/ # the "porcelain" layer: hand-written idiomatic clients templates/ # Go templates consumed by openapi-gen to produce *.gen.rb test/ # minitest suites @@ -69,7 +72,8 @@ constructor: any object that responds to - `request(method:, path:, query: nil, body: nil, headers: nil, **options)`, returning the parsed JSON, - `bytes(...)`, returning the body as a binary `String`, and -- `stream(...) { |chunk| ... }`, yielding the body in chunks. +- `stream(...) { |event| ... }`, yielding the `data` of each server-sent + event parsed as JSON (an Enumerator without a block). The contract is duck-typed, so a plugin gem needs no dependency on the SDK. The porcelain hands each plugin client a `Unikraft::Cloud::Core::ApiClient`, From a40f6d212a96d073ba2c7d6deff77e39b711623e Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:06:35 -0800 Subject: [PATCH 15/30] test: Keep the fake server's connections alive Serve each connection on its own thread and keep it open across requests, count accepted connections, and let a canned response close the connection, drop it unanswered, or arrive late. The transport tests need this to observe connection reuse. Signed-off-by: Alexander Jung --- test/support/fake_server.rb | 60 +++++++++++++++++++++++++++---------- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/test/support/fake_server.rb b/test/support/fake_server.rb index 44de4a0..cfd260f 100644 --- a/test/support/fake_server.rb +++ b/test/support/fake_server.rb @@ -2,36 +2,48 @@ require "socket" -# A one-thread HTTP/1.1 server on 127.0.0.1 that answers each request with the -# next canned response and records what it received. Enough HTTP for the -# transport tests: Content-Length bodies in, fixed or streamed bodies out. +# An HTTP/1.1 server on 127.0.0.1 that answers each request with the next +# canned response and records what it received. Connections are kept alive +# and served on a thread each. Enough HTTP for the transport tests: +# Content-Length bodies in, fixed or streamed bodies out. class FakeServer - Request = Struct.new(:verb, :target, :headers, :body, keyword_init: true) do + Request = Struct.new(:verb, :target, :headers, :body, :conn, keyword_init: true) do def path = target.split("?", 2).first def query = target.split("?", 2)[1] end + # @return [Array] what arrived, in order; `conn` numbers the + # connection it came on, from 1 attr_reader :requests + # @return [Integer] connections accepted so far + attr_reader :accepts def initialize @server = TCPServer.new("127.0.0.1", 0) @responses = Queue.new @requests = [] + @accepts = 0 + @mutex = Mutex.new + @sessions = [] @thread = Thread.new { serve } end def url = "http://127.0.0.1:#{@server.addr[1]}" # @param chunks [Array] written one by one, with a flush between - def respond(status: 200, headers: {}, body: "", chunks: nil) - @responses << { status: status, headers: headers, body: body, chunks: chunks } + # @param close [Boolean] send `Connection: close` and hang up after + # @param drop [Boolean] hang up after reading the request, unanswered + # @param delay [Numeric] seconds to wait before answering + def respond(status: 200, headers: {}, body: "", chunks: nil, close: false, drop: false, + delay: 0) + @responses << { status:, headers:, body:, chunks:, close:, drop:, delay: } self end def last_request = @requests.last def close - @thread.kill + (@sessions + [@thread]).each(&:kill) @server.close end @@ -40,26 +52,44 @@ def close def serve loop do client = @server.accept - handle(client) - ensure - client&.close + conn = @accepts += 1 + @sessions << Thread.new { session(client, conn) } end end - def handle(client) - method, target = client.gets.split + def session(client, conn) + loop { break unless serve_one?(client, conn) } + rescue IOError, SystemCallError + nil + ensure + client.close + end + + # Serve one request; false when the connection is done. + def serve_one?(client, conn) + line = client.gets or return false + method, target = line.split headers = {} while (line = client.gets) && line != "\r\n" name, value = line.chomp.split(": ", 2) headers[name.downcase] = value end body = client.read(headers.fetch("content-length", "0").to_i) - @requests << Request.new(verb: method, target: target, headers: headers, body: body) - write(client, @responses.pop) + @mutex.synchronize do + @requests << Request.new(verb: method, target: target, headers: headers, body: body, + conn: conn) + end + res = @responses.pop + return false if res[:drop] + + sleep res[:delay] + write(client, res) + !res[:close] end def write(client, res) - client.write("HTTP/1.1 #{res[:status]} X\r\nConnection: close\r\n") + client.write("HTTP/1.1 #{res[:status]} X\r\n") + client.write("Connection: close\r\n") if res[:close] res[:headers].each { |k, v| client.write("#{k}: #{v}\r\n") } if res[:chunks] client.write("Transfer-Encoding: chunked\r\n\r\n") From f95988f3b1a794f8125bc75ce51e8f763e391797 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:08:57 -0800 Subject: [PATCH 16/30] feat(core): Reuse connections across requests ApiClient opened a new connection for every call. Keep finished connections in a per-client pool keyed by scheme, host, port and proxy, checked out by one thread at a time, at most 8 idle per key and for at most 5 seconds. Streams and bytes use it too. A connection that saw an error, answered Connection: close, or carried a stream left early is closed instead of returned. ApiClient#close closes the idle ones, and a forked child drops the connections it inherited without closing them. A reused connection the server closed while idle fails before any response arrives; only then, and only for an idempotent method, is the request sent once more on a fresh connection. POST and PATCH are never resent. Net::HTTP's own resend of idempotent requests, which also fired on timeouts, is now off. Signed-off-by: Alexander Jung --- CONTRIBUTING.md | 26 ++++++ lib/unikraft/cloud/core/http.rb | 103 ++++++++++++++++++++---- lib/unikraft/cloud/core/pool.rb | 97 +++++++++++++++++++++++ test/unit/http_test.rb | 135 ++++++++++++++++++++++++++++++++ test/unit/pool_test.rb | 56 +++++++++++++ 5 files changed, 400 insertions(+), 17 deletions(-) create mode 100644 lib/unikraft/cloud/core/pool.rb create mode 100644 test/unit/pool_test.rb diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 19d5ab8..a79f689 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -89,6 +89,32 @@ plugin gem. Two rules follow: `ApiClient` must not rely on a keyword the contract does not declare. Ruby checks none of this ahead of time, so only the tests can see that drift. +### Connection reuse + +`ApiClient` keeps finished connections alive in a per-client pool +(`core/pool.rb`), keyed by scheme, host, port and proxy, so a per-call +`base_url:` gets its own connections. A thread checks a connection out for +the length of one call and finds a new one if none is idle, so clients are +safe to share across threads and no two threads ever share a connection. At +most 8 connections per key stay idle, for at most 5 seconds. A connection +that saw an error, answered `Connection: close`, or carried a stream that +was left early is closed rather than put back. `ApiClient#close` closes the +idle ones; the client stays usable. A forked child drops, without closing, +the connections it inherited. + +The transport sends each request once. The one exception is not a retry: a +server may close an idle keep-alive connection just as it is reused, and the +request then fails with `EOFError`, `IOError`, `ECONNRESET`, `EPIPE` or +`ECONNABORTED` before any response arrives. Only in that case, only for a +reused connection, and only for an idempotent method (`GET`, `HEAD`, `PUT`, +`DELETE`, `OPTIONS`, as in RFC 9110), the request is sent once more on a +fresh connection. The server may have read the first copy before it hung +up, but sending an idempotent request twice has the same effect as sending +it once. `POST` and `PATCH` are never resent: a create could run twice. A +failure on a fresh connection, a timeout, or any failure after a response +began is raised as is. Net::HTTP's own resend of idempotent requests is +turned off. + ## Prerequisites - Ruby 3.3+ (CI covers 3.3, 3.4 and 4.0) diff --git a/lib/unikraft/cloud/core/http.rb b/lib/unikraft/cloud/core/http.rb index 32d9bc4..82d28a8 100644 --- a/lib/unikraft/cloud/core/http.rb +++ b/lib/unikraft/cloud/core/http.rb @@ -12,6 +12,7 @@ require "uri" require_relative "errors" +require_relative "pool" require_relative "url" require_relative "../version" @@ -20,7 +21,13 @@ module Cloud module Core # Transport for one base URL. Performs authenticated requests and # returns the parsed response envelope. Raises {Unikraft::Cloud::Error} - # on network failures and non-2xx responses. It never retries. + # on network failures and non-2xx responses. It never retries, except + # to resend an idempotent request once when a reused keep-alive + # connection turns out stale (see CONTRIBUTING.md). + # + # Connections are kept alive and reused across calls, also from + # several threads at once; see {#close} and CONTRIBUTING.md, + # "Connection reuse". # # It satisfies the duck-typed transport the plugin gems # (`unikraft-cloud-plugin--api`) take: `request`, `bytes` and @@ -54,6 +61,18 @@ class ApiClient OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::ProtocolError ].freeze + # On a reused connection and before any response: the server + # closed the connection while it sat idle (EOFError is an IOError). + STALE_ERRORS = [IOError, Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED].freeze + + # Methods safe to resend after a stale connection (RFC 9110): the + # server may have read the first copy before it hung up. + IDEMPOTENT = %w[GET HEAD PUT DELETE OPTIONS].freeze + + # A reused connection turned out stale; resend on a fresh one. + class StaleConnection < StandardError; end + private_constant :StaleConnection + # @return [String] the base URL, without trailing slashes attr_reader :base_url # @return [String, nil] the bearer token @@ -78,6 +97,15 @@ def initialize(base_url:, token: nil, headers: {}, user_agent: nil, headers&.each { |k, v| @headers[k.to_s] = v.to_s } @timeout = timeout @proxy_from_env = proxy_from_env + @pool = Pool.new + end + + # Close the idle connections. Calls made afterwards open new ones, + # so this is safe to call at any time, and more than once. + # + # @return [nil] + def close + @pool.close end # Perform a request and return its parsed JSON body (symbol keys). @@ -120,7 +148,7 @@ def bytes(method:, path:, query: nil, body: nil, headers: nil, **options) # Perform a request whose response is a `text/event-stream`, and yield # each event's JSON payload (symbol keys) as it arrives. Returns when # the server closes the stream; `break` out of the block to stop early - # and release the connection. + # (that closes the connection). # # @param (see #request) # @yieldparam event [Hash, Array] one event's parsed `data` @@ -143,8 +171,8 @@ def stream(method:, path:, query: nil, body: nil, headers: nil, **options, &bloc private - # Build and send one request, and hand the response to the block while - # the connection is open (so a stream can be read from it). + # Build and send one request, and hand the response to the block (a + # stream while it can still be read from the connection). def perform(accept, method:, path:, query:, body:, headers:, **options) options = call_options(options) verb = method.to_s.upcase @@ -157,23 +185,58 @@ def perform(accept, method:, path:, query:, body:, headers:, **options) path.to_s + encode_query(query) uri = URI(url) req = build_request(verb, uri, body, headers, accept) - via_proxy = false + fresh = connection(uri) + via_proxy = fresh.proxy? begin - http = connection(uri, options.fetch(:timeout)) - via_proxy = http.proxy? - http.start do - http.request(req) do |res| - return yield(res, url) if accept == "text/event-stream" - - res.read_body - return yield(res, url) - end - end + exchange(fresh, req, options.fetch(:timeout)) { |res| yield res, url } rescue *NETWORK_ERRORS => e raise network_error(url, e, via_proxy) end end + # Send req on an idle connection if there is one, else on fresh. + def exchange(fresh, req, timeout, &) + # Connections are interchangeable when all of these match. + key = [fresh.use_ssl?, fresh.address, fresh.port, fresh.proxy_address, + fresh.proxy_port, fresh.proxy_user, fresh.proxy_pass] + idle = @pool.checkout(key) + attempt(key, idle || fresh, req, timeout, reused: !idle.nil?, &) + rescue StaleConnection + attempt(key, fresh, req, timeout, reused: false, &) + end + + # Send req on http and yield the response: a stream while it is + # still being read, anything else once its body is in. Puts http + # back in the pool only after a clean, complete exchange. + # + # Raises StaleConnection, for one resend on a fresh connection, only + # when an IDEMPOTENT request on a reused connection fails with a + # STALE_ERRORS error before any response arrived: most likely the + # server closed it while idle. Anything else propagates as is. + def attempt(key, http, req, timeout, reused:) + stream = req["Accept"] == "text/event-stream" + responded = done = false + configure(http, timeout) + http.start unless http.started? + result = nil + res = http.request(req) do |r| + responded = true + result = yield r if stream + end + done = true + stream ? result : yield(res) + rescue *STALE_ERRORS + raise if responded || !reused || !IDEMPOTENT.include?(req.method) + + raise StaleConnection + ensure + if done && !/\bclose\b/i.match?(res["connection"].to_s) + @pool.checkin(key, http) + else + @pool.discard(http) + end + end + def call_options(options) unknown = options.keys - %i[base_url timeout] raise ArgumentError, "unknown keyword(s): #{unknown.join(", ")}" unless unknown.empty? @@ -194,14 +257,20 @@ def build_request(verb, uri, body, headers, accept) req end - def connection(uri, timeout) + def connection(uri) proxy = @proxy_from_env ? :ENV : nil http = Net::HTTP.new(uri.host, uri.port, proxy) http.use_ssl = uri.scheme == "https" + http + end + + # Set every time: the connection may come from the pool. + def configure(http, timeout) http.open_timeout = timeout http.read_timeout = timeout http.write_timeout = timeout - http + http.keep_alive_timeout = @pool.keep_alive + http.max_retries = 0 # Net::HTTP would resend idempotent requests end # Serialise a query hash in form/explode style. diff --git a/lib/unikraft/cloud/core/pool.rb b/lib/unikraft/cloud/core/pool.rb new file mode 100644 index 0000000..a3b3ac6 --- /dev/null +++ b/lib/unikraft/cloud/core/pool.rb @@ -0,0 +1,97 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +module Unikraft + module Cloud + module Core + # The idle, started Net::HTTP connections of one {ApiClient}, by + # destination. A connection is either checked out by exactly one + # thread or idle here, never both, so no two threads share one. + class Pool + # Idle connections kept per destination; more are closed on checkin. + MAX_IDLE = 8 + + # Seconds a connection may sit idle before it is discarded. Below + # the idle timeout of typical servers and load balancers, so the + # server rarely closes a connection first. + KEEP_ALIVE = 5 + + # @return [Numeric] the keep-alive window in seconds + attr_reader :keep_alive + + # @param max_idle [Integer] idle connections kept per key + # @param keep_alive [Numeric] seconds an idle connection is kept + def initialize(max_idle: MAX_IDLE, keep_alive: KEEP_ALIVE) + @max_idle = max_idle + @keep_alive = keep_alive + @mutex = Mutex.new + @idle = Hash.new { |h, k| h[k] = [] } + @pid = Process.pid + end + + # Take the most recently used idle connection for key, closing the + # expired ones on the way. + # + # @return [Net::HTTP, nil] nil when none is idle + def checkout(key) + expired = [] + http = @mutex.synchronize do + forget_if_forked + idle = @idle[key] + while (entry = idle.pop) + break entry[0] if now - entry[1] < @keep_alive + + expired << entry[0] + end + end + expired.each { |c| discard(c) } + http + end + + # Return a connection that finished its exchange cleanly. + def checkin(key, http) + kept = @mutex.synchronize do + forget_if_forked + idle = @idle[key] + idle << [http, now] if idle.size < @max_idle + end + discard(http) unless kept + end + + # Close a connection; never raises. + def discard(http) + http.finish + rescue StandardError + nil + end + + # Close every idle connection. Idempotent; the pool stays usable. + def close + conns = @mutex.synchronize do + forget_if_forked + all = @idle.values.flatten(1).map(&:first) + @idle.clear + all + end + conns.each { |c| discard(c) } + nil + end + + private + + # A forked child shares its parent's sockets: closing them would + # cut the parent's connections, so the child only forgets them. + def forget_if_forked + return if @pid == Process.pid + + @idle = Hash.new { |h, k| h[k] = [] } + @pid = Process.pid + end + + def now = Process.clock_gettime(Process::CLOCK_MONOTONIC) + end + end + end +end diff --git a/test/unit/http_test.rb b/test/unit/http_test.rb index 53ebf1a..3251d67 100644 --- a/test/unit/http_test.rb +++ b/test/unit/http_test.rb @@ -184,4 +184,139 @@ def test_stream_http_error assert_equal 401, err.status assert_equal "unauthorized", err.message end + + def test_reuses_one_connection_for_sequential_calls + 3.times { @server.respond(body: "{}") } + @client.request(method: :get, path: "/a") + @client.bytes(method: :get, path: "/b") + @client.request(method: :post, path: "/c", body: {}) + + assert_equal 1, @server.accepts + end + + def test_concurrent_calls_never_share_a_connection + 8.times { @server.respond(body: '{"ok":true}', delay: 0.1) } + 2.times do + results = Array.new(4) { Thread.new { @client.request(method: :get, path: "/") } } + .map(&:value) + + assert_equal [{ ok: true }] * 4, results + # The second round reuses the first round's connections. + assert_equal 4, @server.accepts + end + end + + def test_a_stale_reused_connection_is_resent_once_on_a_fresh_one + @server.respond(body: "{}").respond(drop: true).respond(body: '{"n":2}') + @client.request(method: :get, path: "/") + + assert_equal({ n: 2 }, @client.request(method: :get, path: "/x")) + assert_equal [1, 1, 2], @server.requests.map(&:conn) + end + + def test_a_non_idempotent_request_is_never_resent + %i[post patch].each do |verb| + server = FakeServer.new.respond(body: "{}").respond(drop: true) + client = ApiClient.new(base_url: server.url, proxy_from_env: false) + client.request(method: :get, path: "/") + err = assert_raises(Error) { client.request(method: verb, path: "/x", body: {}) } + + assert_equal :network, err.kind + assert_equal 2, server.requests.size, verb + ensure + server&.close + end + end + + def test_a_fresh_connection_is_never_resent + @server.respond(drop: true) + err = assert_raises(Error) { @client.request(method: :get, path: "/") } + + assert_equal :network, err.kind + assert_kind_of EOFError, err.cause + assert_equal 1, @server.requests.size + end + + def test_the_resend_is_not_resent_again + @server.respond(body: "{}").respond(drop: true).respond(drop: true) + @client.request(method: :get, path: "/") + err = assert_raises(Error) { @client.request(method: :get, path: "/") } + + assert_equal :network, err.kind + assert_equal 3, @server.requests.size + end + + def test_a_timeout_on_a_reused_connection_is_not_resent + @server.respond(body: "{}").respond(body: "{}", delay: 0.5) + @client.request(method: :get, path: "/") + err = assert_raises(Error) { @client.request(method: :get, path: "/", timeout: 0.05) } + + assert_equal :network, err.kind + assert_kind_of Net::ReadTimeout, err.cause + assert_equal 2, @server.requests.size + end + + def test_idle_connections_expire + @client.instance_variable_set(:@pool, Unikraft::Cloud::Core::Pool.new(keep_alive: 0.05)) + 2.times { @server.respond(body: "{}") } + @client.request(method: :get, path: "/") + sleep 0.1 + @client.request(method: :get, path: "/") + + assert_equal 2, @server.accepts + end + + def test_close_drops_idle_connections_and_the_client_stays_usable + 2.times { @server.respond(body: "{}") } + @client.request(method: :get, path: "/") + @client.close + @client.close + + assert_empty idle_connections + @client.request(method: :get, path: "/") + + assert_equal 2, @server.accepts + end + + def test_connection_close_is_honoured + @server.respond(body: "{}", close: true).respond(body: "{}") + @client.request(method: :get, path: "/") + + assert_empty idle_connections + @client.request(method: :get, path: "/") + + assert_equal 2, @server.accepts + end + + def test_an_http_error_keeps_the_connection + @server.respond(status: 404, body: "{}").respond(body: "{}") + assert_raises(Error) { @client.request(method: :get, path: "/") } + @client.request(method: :get, path: "/") + + assert_equal 1, @server.accepts + end + + def test_a_stream_left_early_closes_its_connection + @server.respond(chunks: ["data: 1\n\n", "data: 2\n\n"]).respond(body: "{}") + + assert_equal 1, @client.stream(method: :get, path: "/s").first + assert_empty idle_connections + @client.request(method: :get, path: "/") + + assert_equal 2, @server.accepts + end + + def test_a_finished_stream_returns_its_connection + @server.respond(chunks: ["data: 1\n\n"]).respond(body: "{}") + @client.stream(method: :get, path: "/s").to_a + @client.request(method: :get, path: "/") + + assert_equal 1, @server.accepts + end + + private + + def idle_connections + @client.instance_variable_get(:@pool).instance_variable_get(:@idle).values.flatten + end end diff --git a/test/unit/pool_test.rb b/test/unit/pool_test.rb new file mode 100644 index 0000000..cb22ee6 --- /dev/null +++ b/test/unit/pool_test.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require_relative "../test_helper" + +class PoolTest < Minitest::Test + Pool = Unikraft::Cloud::Core::Pool + + Conn = Struct.new(:finished) do + def finish = self.finished = true + end + + def test_keys_are_separate_and_most_recent_first + pool = Pool.new + a = Conn.new + b = Conn.new + pool.checkin(:x, a) + pool.checkin(:x, b) + + assert_nil pool.checkout(:y) + assert_same b, pool.checkout(:x) + assert_same a, pool.checkout(:x) + assert_nil pool.checkout(:x) + end + + def test_extra_idle_connections_are_closed + pool = Pool.new(max_idle: 1) + kept = Conn.new + extra = Conn.new + pool.checkin(:x, kept) + pool.checkin(:x, extra) + + assert extra.finished + refute kept.finished + end + + def test_expired_connections_are_closed_on_checkout + pool = Pool.new(keep_alive: 0) + old = Conn.new + pool.checkin(:x, old) + + assert_nil pool.checkout(:x) + assert old.finished + end + + def test_a_forked_child_forgets_inherited_connections_without_closing + pool = Pool.new + inherited = Conn.new + pool.checkin(:x, inherited) + pool.instance_variable_set(:@pid, -1) + + assert_nil pool.checkout(:x) + pool.close + + refute inherited.finished + end +end From 789919bfbc1d381860f3bc3f6aafabdbda65be37 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:05:31 -0800 Subject: [PATCH 17/30] feat(core): Add metros, refs and envelope unwrapping Core::Metro turns metro codes, URLs and scopes (Symbols or Strings, :all) into Endpoints; KNOWN_METROS, DEFAULT_METRO and the control plane URL live on Unikraft::Cloud. Core::Ref is a Data value holding a name or a uuid, never both, optionally qualified with a metro that never reaches the wire. Core::Response unwraps the envelope, reading a per-entry failure out of a 200 error envelope as the JS SDK does. Models gain deconstruct_keys, so results pattern-match with metro. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 3 + lib/unikraft/cloud/core/metro.rb | 75 +++++++++++++++++ lib/unikraft/cloud/core/ref.rb | 95 ++++++++++++++++++++++ lib/unikraft/cloud/core/response.rb | 96 ++++++++++++++++++++++ lib/unikraft/cloud/model.rb | 10 +++ test/unit/ref_test.rb | 122 ++++++++++++++++++++++++++++ 6 files changed, 401 insertions(+) create mode 100644 lib/unikraft/cloud/core/metro.rb create mode 100644 lib/unikraft/cloud/core/ref.rb create mode 100644 lib/unikraft/cloud/core/response.rb create mode 100644 test/unit/ref_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index d2525dd..0472393 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -11,3 +11,6 @@ require_relative "cloud/core/ready" require_relative "cloud/model" require_relative "cloud/api" +require_relative "cloud/core/metro" +require_relative "cloud/core/ref" +require_relative "cloud/core/response" diff --git a/lib/unikraft/cloud/core/metro.rb b/lib/unikraft/cloud/core/metro.rb new file mode 100644 index 0000000..121e44e --- /dev/null +++ b/lib/unikraft/cloud/core/metro.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "url" +require_relative "errors" + +module Unikraft + module Cloud + # The metros known when this version was published. Any other code works + # too: discovery trusts the control plane, so new metros need no upgrade. + KNOWN_METROS = %w[fra dal sin was sfo].freeze + + # The metro an operation that must pick one (such as `create`) uses when + # neither `metro:` nor `UKC_METRO` names one. + DEFAULT_METRO = "fra" + + # The global control-plane API. Unlike the platform API it has no metro. + CONTROLPLANE_BASE_URL = "https://controlplane.unikraft.cloud" + + module Core + # A metro paired with the platform API base URL that serves it. + # + # @!attribute [r] metro + # @return [String] the metro code, or the base URL itself for an + # explicitly named endpoint + # @!attribute [r] base_url + # @return [String] + Endpoint = Data.define(:metro, :base_url) + + # Turning metro codes, URLs and scopes into endpoints. + module Metro + module_function + + # @param metro [String, Symbol] + # @return [Boolean] whether the value is an `http(s)://` URL + def url?(metro) + metro.to_s.match?(%r{\Ahttps?://}i) + end + + # The platform API base URL of a metro: `fra` becomes + # `https://api.fra.unikraft.cloud`. A URL is used verbatim, minus + # trailing slashes and a trailing `/v1`, which every operation path + # already carries. + # + # @param metro [String, Symbol] + # @return [String] + def base_url(metro) + return "https://api.#{metro}.unikraft.cloud" unless url?(metro) + + URL.strip_trailing_slashes(metro).sub(%r{/v1\z}, "") + end + + # @param metro [String, Symbol] + # @return [Endpoint] + def endpoint(metro) + Endpoint.new(metro: metro.to_s, base_url: base_url(metro)) + end + + # Normalise a scope: `:all` (or `"all"`), one metro, or a list of them, + # as Symbols or Strings. + # + # @param scope [Symbol, String, Array] + # @return [:all, Array] + def scope(scope) + list = Array(scope).flatten + return :all if list.size == 1 && list.first.to_s == "all" + + list.map(&:to_s).uniq.freeze + end + end + end + end +end diff --git a/lib/unikraft/cloud/core/ref.rb b/lib/unikraft/cloud/core/ref.rb new file mode 100644 index 0000000..de33f34 --- /dev/null +++ b/lib/unikraft/cloud/core/ref.rb @@ -0,0 +1,95 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +module Unikraft + module Cloud + module Core + # A reference to one resource: a `name` or a `uuid`, never both. + # + # The API validates every identifier it is given, so a name sent in the + # `uuid` filter fails with `Invalid uuid ''`: the ref states which + # kind it holds, and only that field is sent. A name is unique only + # within a metro, so it can be qualified with `metro`, which also saves + # a lookup. A uuid identifies one resource wherever it lives. + # + # @example + # Ref.new(name: "web") + # Ref.new(name: "web", metro: :fra) + # Ref.coerce({ uuid: "550e8400-e29b-41d4-a716-446655440000" }) + # case ref + # in { name: String => name, metro: nil } then ... + # end + Ref = Data.define(:name, :uuid, :metro) do + # @raise [ArgumentError] when given both or neither of name and uuid + def initialize(name: nil, uuid: nil, metro: nil) + raise ArgumentError, "a ref takes `name:` or `uuid:`, not both" if name && uuid + raise ArgumentError, "a ref needs `name:` or `uuid:`" if name.nil? && uuid.nil? + + super(name: name&.to_s, uuid: uuid&.to_s, metro: metro&.to_s) + end + + # @param value [Ref, Hash] a ref, or a Hash with `:name` or `:uuid` + # and optionally `:metro` (Symbol or String keys) + # @return [Ref] + def self.coerce(value) + return value if value.is_a?(Ref) + unless value.is_a?(Hash) + raise ArgumentError, + "a ref is a Hash with `name:` or `uuid:`, got #{value.inspect}" + end + + fields = value.transform_keys(&:to_sym) + unknown = fields.keys - members + raise ArgumentError, "unknown ref key(s): #{unknown.join(", ")}" unless unknown.empty? + + new(**fields) + end + + # One ref or an Array of them, as an Array. + # + # @param value [Ref, Hash, Array] + # @return [Array] + def self.list(value) + refs = value.is_a?(Array) ? value.map { |v| coerce(v) } : [coerce(value)] + raise ArgumentError, "no refs given" if refs.empty? + + refs + end + + # The ref as a request body carries it: the identifier alone. `metro` + # says where to send the request and must not reach the wire. + # + # @return [Hash] + def wire + uuid ? { uuid: } : { name: } + end + + # The ref as a query filter. + # + # @return [Hash] + def query + uuid ? { uuid: [uuid] } : { name: [name] } + end + + # @return [String] e.g. `name "web" in fra` + def to_s + id = uuid ? %(uuid "#{uuid}") : %(name "#{name}") + metro ? "#{id} in #{metro}" : id + end + end + + # Where a handle's resource lives: the ref, and the metro and base URL + # serving it. + # + # @!attribute [r] ref + # @return [Ref] qualified with the metro + # @!attribute [r] metro + # @return [String] + # @!attribute [r] base_url + # @return [String] + Location = Data.define(:ref, :metro, :base_url) + end + end +end diff --git a/lib/unikraft/cloud/core/response.rb b/lib/unikraft/cloud/core/response.rb new file mode 100644 index 0000000..d12b2d9 --- /dev/null +++ b/lib/unikraft/cloud/core/response.rb @@ -0,0 +1,96 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "errors" + +module Unikraft + module Cloud + module Core + # Unwrapping the response envelope the plumbing returns. + module Response + # The platform's per-entry `error` codes the SDK acts on, as the HTTP + # status that says the same. Code 8 is "no such resource", answered + # with HTTP 200; the spec publishes no list, so this records observed + # behaviour. {absent} depends on it. + ENTRY_ERROR_STATUS = { 8 => 404 }.freeze + + module_function + + # The envelope's `data`, after checking it reports no failure. + # + # A whole-request failure fills the top-level `errors`; a per-resource + # one marks its entry inside `data` with `status: "error"`, which + # then supplies the message and status. A `partial_success` whose + # failures stay inside `data` is returned as is: the caller asked for + # several resources and the successes are in the same list. + # + # @param res [Model, nil] the envelope + # @return [Model, nil] + # @raise [Unikraft::Cloud::Error] kind `:http` + def unwrap(res) + return nil if res.nil? + + reported = Array(res[:errors]).first + return res[:data] if res[:status] != "error" && reported.nil? + + raise failure(res, reported.nil? ? first_failure(res[:data]) : nil, reported&.[](:status)) + end + + # The `data[key]` list of an envelope (empty when absent). + # + # @return [Array] + def list(res, key) + Array(unwrap(res)&.[](key)) + end + + # The first entry of `data[key]`. A single-resource caller has no + # use for a failed entry, so any failed one in a `partial_success` + # (e.g. one property of an update) raises. + # + # @param what [String] the subject of the not-found message + # @raise [Unikraft::Cloud::Error] status 404 when the list is empty + def first(res, key, what) + entries = list(res, key) + if entries.empty? + raise Error.new("#{what} not found", kind: :http, status: 404, body: res) + end + + failed = entries.find { |entry| entry[:status] == "error" } + raise failure(res, failed) if failed + + entries.first + end + + # The block's value, or nil when it reports the resource absent (404). + # Searching several metros means most legitimately answer "not here". + def absent + yield + rescue Error => e + raise unless e.status == 404 + + nil + end + + def failure(res, entry, status = nil) + status ||= ENTRY_ERROR_STATUS[entry&.[](:error)] + message = entry&.[](:message) || res[:message] || "Unikraft Cloud API reported an error" + Error.new(message, kind: :http, status:, errors: res.to_h[:errors], body: res) + end + private_class_method :failure + + def first_failure(data) + data.to_h.each_value do |value| + next unless value.is_a?(Array) + + hit = value.find { |entry| entry.is_a?(Hash) && entry[:status] == "error" } + return hit if hit + end + nil + end + private_class_method :first_failure + end + end + end +end diff --git a/lib/unikraft/cloud/model.rb b/lib/unikraft/cloud/model.rb index 0ec14b4..2d0e589 100644 --- a/lib/unikraft/cloud/model.rb +++ b/lib/unikraft/cloud/model.rb @@ -104,6 +104,16 @@ def to_h @values.transform_values { |v| plain(v) } end + # Pattern matching on the fields, and on the `metro` tag when set. + # + # @example + # case inst + # in { state: "running", metro: "fra" } then ... + # end + def deconstruct_keys(_keys) + @metro ? @values.merge(metro: @metro) : @values + end + # @return [String] def to_json(*) to_h.to_json(*) diff --git a/test/unit/ref_test.rb b/test/unit/ref_test.rb new file mode 100644 index 0000000..c858bba --- /dev/null +++ b/test/unit/ref_test.rb @@ -0,0 +1,122 @@ +# frozen_string_literal: true + +require_relative "../test_helper" + +class RefTest < Minitest::Test + Core = Unikraft::Cloud::Core + Models = Unikraft::Cloud::API::Platform::Models + + def test_metro_base_url + assert_equal "https://api.fra.unikraft.cloud", Core::Metro.base_url(:fra) + assert_equal "https://api.staging.internal", Core::Metro.base_url("https://api.staging.internal") + # Every operation path carries /v1, so a trailing one is dropped. + assert_equal "https://api.staging.internal", + Core::Metro.base_url("https://api.staging.internal/v1/") + end + + def test_scope_accepts_symbols_and_strings + assert_equal :all, Core::Metro.scope(:all) + assert_equal :all, Core::Metro.scope("all") + assert_equal %w[fra], Core::Metro.scope(:fra) + assert_equal %w[fra dal], Core::Metro.scope([:fra, "dal"]) + end + + def test_ref_states_one_identifier + assert_raises(ArgumentError) { Core::Ref.new(name: "a", uuid: "b") } + assert_raises(ArgumentError) { Core::Ref.new } + assert_raises(ArgumentError) { Core::Ref.coerce("web") } + assert_raises(ArgumentError) { Core::Ref.coerce({ nme: "web" }) } + end + + def test_ref_keeps_metro_off_the_wire + ref = Core::Ref.coerce({ "name" => "web", "metro" => :fra }) + + assert_equal "fra", ref.metro + assert_equal({ name: "web" }, ref.wire) + assert_equal({ name: ["web"] }, ref.query) + assert_equal 'name "web" in fra', ref.to_s + assert_equal({ uuid: ["u1"] }, Core::Ref.new(uuid: "u1").query) + end + + def test_ref_list + assert_equal 2, Core::Ref.list([{ name: "a" }, { uuid: "b" }]).size + assert_equal 1, Core::Ref.list({ name: "a" }).size + assert_raises(ArgumentError) { Core::Ref.list([]) } + end + + def test_refs_and_models_pattern_match + matched = case Core::Ref.new(name: "web", metro: :fra) + in { name:, metro: "fra" } then name + end + + assert_equal "web", matched + inst = Models::Instance.new(name: "web", state: "running").with_metro("dal") + + assert_pattern { inst => { state: "running", metro: "dal" } } + end + + def envelope(body) + Models::GetInstancesResponse.new(body) + end + + def test_unwrap_returns_data + res = envelope(status: "success", data: { instances: [{ name: "web" }] }) + + assert_equal "web", Core::Response.first(res, :instances, "instance").name + assert_empty Core::Response.list(envelope(status: "success"), :instances) + end + + def test_unwrap_raises_on_a_reported_error + err = assert_raises(Unikraft::Cloud::Error) do + Core::Response.list(envelope(status: "error", message: "nope", errors: [{ status: 500 }]), + :instances) + end + + assert_equal 500, err.status + assert_equal "nope", err.message + end + + def test_unwrap_reads_a_per_entry_failure + res = envelope(status: "error", message: "Failed to perform all operations", + data: { instances: [{ status: "error", error: 8, + message: "No instance with uuid 'u1'" }] }) + err = assert_raises(Unikraft::Cloud::Error) { Core::Response.list(res, :instances) } + + assert_equal 404, err.status + assert_equal "No instance with uuid 'u1'", err.message + assert_nil(Core::Response.absent { Core::Response.list(res, :instances) }) + end + + def test_partial_success_is_returned + res = envelope(status: "partial_success", + data: { instances: [{ name: "a" }, { status: "error", error: 8 }] }) + + assert_equal 2, Core::Response.list(res, :instances).size + end + + def test_first_raises_a_later_failed_entry + res = envelope(status: "partial_success", + data: { instances: [{ name: "a" }, { status: "error", message: "bad prop" }] }) + err = assert_raises(Unikraft::Cloud::Error) { Core::Response.first(res, :instances, "instance") } + + assert_equal "bad prop", err.message + end + + def test_first_raises_a_failed_partial_success_entry + res = envelope(status: "partial_success", + data: { instances: [{ status: "error", error: 8, message: "gone" }] }) + err = assert_raises(Unikraft::Cloud::Error) { Core::Response.first(res, :instances, "instance") } + + assert_equal 404, err.status + assert_equal "gone", err.message + end + + def test_first_raises_not_found + err = assert_raises(Unikraft::Cloud::Error) do + Core::Response.first(envelope(status: "success", data: { instances: [] }), :instances, + "instance") + end + + assert_equal 404, err.status + end +end From d46a31aa9c279594630c8a3de466786fb19c3af1 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:06:36 -0800 Subject: [PATCH 18/30] feat(core): Add metro fan-out and pagination Core::Fanout runs per-metro work on threads. merge pushes items onto a yielder in arrival order through a SizedQueue of about one item per metro, so each metro fetches its next page only as the consumer uses up the last. It drains every healthy metro before raising one MetroFanoutError, and kills the metros still in flight when the consumer leaves early. Every producer reports from ensure, so the consumer never waits on a dead thread. all and settled run one call per metro and keep the successes on the error as results. Only a Unikraft::Cloud::Error is a metro failure; anything else, a bug or an interrupt, is re-raised to the caller. Core::Pagination follows the count/from cursor of the list endpoints. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 2 + lib/unikraft/cloud/core/fanout.rb | 150 +++++++++++++++++++++++ lib/unikraft/cloud/core/pagination.rb | 43 +++++++ test/unit/fanout_test.rb | 167 ++++++++++++++++++++++++++ 4 files changed, 362 insertions(+) create mode 100644 lib/unikraft/cloud/core/fanout.rb create mode 100644 lib/unikraft/cloud/core/pagination.rb create mode 100644 test/unit/fanout_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 0472393..3e2a5be 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -14,3 +14,5 @@ require_relative "cloud/core/metro" require_relative "cloud/core/ref" require_relative "cloud/core/response" +require_relative "cloud/core/fanout" +require_relative "cloud/core/pagination" diff --git a/lib/unikraft/cloud/core/fanout.rb b/lib/unikraft/cloud/core/fanout.rb new file mode 100644 index 0000000..a782c05 --- /dev/null +++ b/lib/unikraft/cloud/core/fanout.rb @@ -0,0 +1,150 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# Running one operation across several metros and sewing the results back +# together. The platform API is metro-scoped, so an account-wide view means +# asking every metro and merging what comes back. + +require_relative "errors" + +module Unikraft + module Cloud + module Core + # Concurrent per-metro work on threads. + module Fanout + # One item's outcome from {settled}. + Outcome = Data.define(:item, :value, :error) do + def ok? = error.nil? + end + + module_function + + # Run `producer` for every endpoint concurrently and push each item it + # emits onto `out` as soon as it arrives, so a slow metro never holds + # up a fast one. Every healthy metro is drained first, then one + # {MetroFanoutError} names the failures. A single endpoint runs + # inline, and its failure propagates as itself. Only an {Error} is a + # metro failure: anything else (a bug, an interrupt) is re-raised. + # + # The queue holds about one item per metro, so a producer fetches + # its next page only once the consumer has nearly used up the last. + # Leaving early (`break`, `first`) kills the metros still in flight. + # An external enumerator (`Enumerator#next`) abandoned midway never + # leaves, so its producers stay parked on the full queue, sending + # nothing, until the process exits: prefer `each`, `first` or `lazy`. + # + # @param endpoints [Array] + # @param out [#<<] e.g. an Enumerator::Yielder + # @yieldparam endpoint [Endpoint] + # @yieldparam emit [Proc] call with each item + def merge(endpoints, out) + return yield(endpoints.first, ->(item) { out << item }) if endpoints.size == 1 + + queue = SizedQueue.new(endpoints.size) + threads = endpoints.map do |endpoint| + Thread.new do + error = nil + yield endpoint, ->(item) { queue << [:item, item] } + rescue Exception => e # rubocop:disable Lint/RescueException + error = e # handed to the consumer, which re-raises what is not an Error + ensure + # Always report, or the consumer waits forever. A killed + # producer (the consumer left, or the process is exiting) has + # no one to report to, and could block on the full queue. + begin + queue << [:finished, endpoint, error] unless Thread.current.status == "aborting" + rescue ClosedQueueError + nil + end + end + end + drain(queue, out, endpoints.size) + ensure + queue&.close # wakes producers blocked on a full queue + threads&.each(&:kill) + end + + def drain(queue, out, total) + failures = [] + pending = total + while pending.positive? + kind, value, error = queue.pop + next out << value if kind == :item + + pending -= 1 + next if error.nil? + raise error unless error.is_a?(Error) + + failures << { metro: value.metro, error: } + end + raise error(total, failures) unless failures.empty? + end + private_class_method :drain + + # Run the block for every item (anything with a `metro`) concurrently + # and report every outcome, successes and failures alike. A failure + # is an {Error}; any other exception propagates. + # + # @return [Array] in the order of `items` + def settled(items) + run = lambda do |item| + Outcome.new(item:, value: yield(item), error: nil) + rescue Error => e + Outcome.new(item:, value: nil, error: e) + end + return items.map(&run) if items.size < 2 + + # Collected as they finish, so a bug (anything but an Error) in one + # surfaces at once, even while another is still blocked. + done = Queue.new + threads = items.each_with_index.map do |item, i| + Thread.new do + done << [i, run.call(item), nil] + rescue Exception => e # rubocop:disable Lint/RescueException + done << [i, nil, e] + end + end + items.size.times.with_object(Array.new(items.size)) do |_, outcomes| + i, outcome, error = done.pop + raise error if error + + outcomes[i] = outcome + end + ensure + # One raised: stop the rest, or they go on sending after the caller left. + threads&.each(&:kill) + end + + # Run the block for every item concurrently and return the values. + # When some fail, raise a {MetroFanoutError} carrying the successes as + # `results`. + # + # @param flat [Boolean] each value is an Array to concatenate + # @return [Array] + def all(items, flat: false, &) + outcomes = settled(items, &) + results = outcomes.select(&:ok?).map(&:value) + results = results.flatten(1) if flat + failures = outcomes.reject(&:ok?).map { |o| { metro: o.item.metro, error: o.error } } + raise error(items.size, failures, results:) unless failures.empty? + + results + end + + # The aggregate error, e.g. `1 of 3 metros failed: sin (503)`. + # + # @return [MetroFanoutError] + def error(attempted, failures, results: []) + detail = failures.map do |f| + status = f[:error].respond_to?(:status) ? f[:error].status : nil + status ? "#{f[:metro]} (#{status})" : f[:metro] + end + message = "#{failures.size} of #{attempted} metros failed: #{detail.join(", ")}" + MetroFanoutError.new(message, failures:, results:) + end + end + end + end +end diff --git a/lib/unikraft/cloud/core/pagination.rb b/lib/unikraft/cloud/core/pagination.rb new file mode 100644 index 0000000..bad9a21 --- /dev/null +++ b/lib/unikraft/cloud/core/pagination.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +module Unikraft + module Cloud + module Core + # Following a list endpoint's pages. The platform API pages with a + # `count` page size and a `from` cursor (exclusive); a page shorter than + # `count` is the last. + module Pagination + DEFAULT_PAGE_SIZE = 100 + + module_function + + # Yield every item of every page, fetching a page only when the + # previous one is used up. + # + # @param fetch [#call] `(count, from)` -> the page, an Array + # @param page_size [Integer, nil] defaults to {DEFAULT_PAGE_SIZE} + # @param cursor [Symbol] the field of the last item the next page + # starts after + # @yieldparam item [Object] + def each(fetch:, page_size: nil, cursor: :uuid, &) + count = page_size.is_a?(Integer) && page_size.positive? ? page_size : DEFAULT_PAGE_SIZE + from = nil + loop do + page = fetch.call(count, from) + page.each(&) + return if page.size < count + + last = page.last && page.last[cursor] + # No usable cursor: stop rather than loop forever. + return if last.nil? || last == from + + from = last + end + end + end + end + end +end diff --git a/test/unit/fanout_test.rb b/test/unit/fanout_test.rb new file mode 100644 index 0000000..8dc794d --- /dev/null +++ b/test/unit/fanout_test.rb @@ -0,0 +1,167 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require "timeout" + +class FanoutTest < Minitest::Test + Core = Unikraft::Cloud::Core + + def endpoints(*codes) = codes.map { |c| Core::Metro.endpoint(c) } + + def failure(status) = Unikraft::Cloud::Error.new("down", kind: :http, status:) + + def test_merge_interleaves_in_arrival_order + slow = Queue.new + out = [] + Core::Fanout.merge(endpoints(:fra, :dal), out) do |endpoint, emit| + if endpoint.metro == "fra" + slow.pop # fra answers only after dal has delivered + emit.call("fra") + else + emit.call("dal") + slow << :go + end + end + + assert_equal %w[dal fra], out + end + + def test_merge_drains_healthy_metros_then_raises + out = [] + err = assert_raises(Unikraft::Cloud::MetroFanoutError) do + Core::Fanout.merge(endpoints(:fra, :dal, :sin), out) do |endpoint, emit| + raise failure(503) if endpoint.metro == "sin" + + emit.call(endpoint.metro) + end + end + + assert_equal %w[dal fra], out.sort + assert_includes err.message, "1 of 3 metros failed: sin (503)" + assert_equal(["sin"], err.failures.map { |f| f[:metro] }) + assert_equal 503, err.status + end + + def test_merge_with_one_metro_raises_the_error_itself + err = assert_raises(Unikraft::Cloud::Error) do + Core::Fanout.merge(endpoints(:fra), []) { raise failure(500) } + end + + refute_kind_of Unikraft::Cloud::MetroFanoutError, err + end + + def test_merge_stops_the_remaining_metros_on_break + before = Thread.list.size + enum = Enumerator.new do |y| + Core::Fanout.merge(endpoints(:fra, :dal), y) do |endpoint, emit| + emit.call(endpoint.metro) if endpoint.metro == "fra" + sleep + end + end + + assert_equal "fra", enum.first + deadline = Time.now + 5 + Thread.pass until Thread.list.size == before || Time.now > deadline + + assert_equal before, Thread.list.size + end + + def test_merge_reraises_what_is_not_an_error + [ArgumentError, NotImplementedError].each do |klass| + assert_raises(klass) do + Timeout.timeout(5) do + Core::Fanout.merge(endpoints(:fra, :dal), []) do |endpoint, emit| + raise klass, "bug" if endpoint.metro == "dal" + + emit.call(endpoint.metro) + end + end + end + end + end + + def test_merge_buffers_about_one_item_per_metro + emitted = Queue.new + enum = Enumerator.new do |y| + Core::Fanout.merge(endpoints(:fra, :dal), y) do |endpoint, emit| + 100.times do |i| + emit.call(i) + emitted << endpoint.metro + end + end + end + enum.next + sleep 0.05 + + # Each producer parks on the full queue instead of running ahead. + assert_operator emitted.size, :<=, 4 + ensure + enum&.rewind + end + + def test_settled_reraises_what_is_not_an_error + assert_raises(NoMethodError) do + Core::Fanout.settled(endpoints(:fra, :dal)) { |e| e.metro == "dal" ? nil.boom : 1 } + end + end + + def test_settled_stops_the_rest_when_one_raises + finished = false + assert_raises(NoMethodError) do + Core::Fanout.settled(endpoints(:dal, :fra)) do |e| + next nil.boom if e.metro == "dal" + + sleep 0.2 + finished = true + end + end + sleep 0.3 + + refute finished + end + + def test_settled_raises_a_later_failure_while_an_earlier_item_blocks + gate = Queue.new + assert_raises(NoMethodError) do + Timeout.timeout(2) do + Core::Fanout.settled(endpoints(:fra, :dal)) { |e| e.metro == "fra" ? gate.pop : nil.boom } + end + end + end + + def test_all_keeps_the_successes_on_failure + err = assert_raises(Unikraft::Cloud::MetroFanoutError) do + Core::Fanout.all(endpoints(:fra, :dal), flat: true) do |endpoint| + raise failure(503) if endpoint.metro == "dal" + + [1, 2] + end + end + + assert_equal [1, 2], err.results + assert_equal [[1], [2]], Core::Fanout.all(endpoints(:fra, :dal)) { |e| [e.metro == "fra" ? 1 : 2] } + end + + def test_pagination_follows_the_cursor + pages = { nil => [{ uuid: "a" }, { uuid: "b" }], "b" => [{ uuid: "c" }] } + seen = [] + items = [] + Core::Pagination.each(page_size: 2, fetch: lambda { |count, from| + seen << [count, from] + pages.fetch(from) + }) { |item| items << item[:uuid] } + + assert_equal %w[a b c], items + assert_equal [[2, nil], [2, "b"]], seen + end + + def test_pagination_stops_without_a_cursor + calls = 0 + Core::Pagination.each(page_size: 1, fetch: lambda { |_, _| + calls += 1 + [{}] + }) { nil } + + assert_equal 1, calls + end +end From b92f654a7a48f997ce16a92075d1472893db799d Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:07:53 -0800 Subject: [PATCH 19/30] feat(core): Add the session and metro discovery Core::Session holds one client's credentials, the transports it built (one per base URL) and the metro discovery, asked of the control plane once and shared across threads; a failed discovery is not cached. It turns a scope into endpoints, picks the one endpoint of a create (the default metro under a wider scope, and a :config error when a scope of named metros leaves the default out), and never discovers or invents hostnames when a URL was named. close closes every transport it built. The transport builder is injectable, which test/support/fake_cloud.rb uses to route calls. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/core/session.rb | 182 +++++++++++++++++++++++++++++ test/support/fake_cloud.rb | 87 ++++++++++++++ test/unit/session_test.rb | 93 +++++++++++++++ 4 files changed, 363 insertions(+) create mode 100644 lib/unikraft/cloud/core/session.rb create mode 100644 test/support/fake_cloud.rb create mode 100644 test/unit/session_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 3e2a5be..2a0159b 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -16,3 +16,4 @@ require_relative "cloud/core/response" require_relative "cloud/core/fanout" require_relative "cloud/core/pagination" +require_relative "cloud/core/session" diff --git a/lib/unikraft/cloud/core/session.rb b/lib/unikraft/cloud/core/session.rb new file mode 100644 index 0000000..7cbbf7a --- /dev/null +++ b/lib/unikraft/cloud/core/session.rb @@ -0,0 +1,182 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# The transport and metro knowledge shared by every resource client: one set +# of credentials, one memoised metro discovery, and the rules for turning a +# metro scope into concrete endpoints. + +require_relative "errors" +require_relative "http" +require_relative "metro" +require_relative "response" +require_relative "../api" + +module Unikraft + module Cloud + module Core + # Shared state behind one client. Scoped clients (`ukc.metro(:fra)`) + # reuse the same session, so discovery and transports are shared rather + # than duplicated. Safe to share across threads: discovery and the + # transport cache are guarded by a Mutex. + class Session + # @return [Endpoint] the endpoint of operations that must pick one + # metro, such as `create` + attr_reader :default_endpoint + # @return [Endpoint, nil] the only endpoint there is, when the caller + # named a URL + attr_reader :pinned + + # @param config [Hash] {ApiClient#initialize} keywords other than + # `base_url:` (token, headers, timeout, ...) + # @param platform_url [String] the default metro's base URL + # @param controlplane_url [String] + # @param default_metro [String] + # @param pinned [Boolean] `platform_url` was named explicitly: never + # discover, never invent hostnames + # @param transport [#call, nil] builds a transport from the + # {ApiClient} keywords; defaults to `ApiClient.new` + def initialize(config:, platform_url:, controlplane_url:, default_metro:, + pinned: false, transport: nil) + @config = config + @build = transport || ->(**kw) { ApiClient.new(**kw) } + @platform_url = platform_url + @controlplane_url = controlplane_url + @pinned = Endpoint.new(metro: platform_url, base_url: platform_url) if pinned + @default_endpoint = @pinned || Endpoint.new(metro: default_metro, base_url: platform_url) + @mutex = Mutex.new + @discovery = Mutex.new + @transports = {} + @discovered = nil + end + + # The transport for a base URL, built once and shared. + # + # @param base_url [String] + # @return [#request, #bytes, #stream] + def transport(base_url = @platform_url) + @mutex.synchronize { @transports[base_url] ||= @build.call(base_url:, **@config) } + end + + # Both raw API surfaces, the platform one pointing at `base_url`. + # + # @return [API] + def api(base_url = @platform_url) + API.new(platform: transport(base_url), controlplane: transport(@controlplane_url)) + end + + # Every metro the account can reach, asked of the control plane once + # and cached. A failed discovery is not cached, so a transient outage + # does not poison the client. + # + # @return [Array] + # @raise [Unikraft::Cloud::Error] kind `:fanout` + def discover + return [@pinned] if @pinned + + # Held across the request, so concurrent callers share one discovery. + @discovery.synchronize { @discovered ||= list_metros }.values + end + + # The endpoint for a metro code, from what the session already knows. + # Sends no request. A discovered metro may report an endpoint its code + # does not build, so that wins over the URL derived from the code. + # + # @param metro [String, Symbol] + # @return [Endpoint] + def endpoint_for(metro) + return @pinned if @pinned + + # @discovered is frozen and assigned once, so reading it needs no lock. + @discovered&.[](metro.to_s) || Metro.endpoint(metro) + end + + # The endpoints a scope covers. A named scope never discovers. + # + # @param scope [:all, Array] + # @return [Array] + def resolve(scope) + return [@pinned] if @pinned + return discover if scope == :all + if scope.empty? + raise Error.new("An empty metro scope selects no metros; pass :all or a metro.", + kind: :fanout) + end + + scope.map { |metro| endpoint_for(metro) } + end + + # The one endpoint of an operation that must pick exactly one metro. + # A wider scope falls back to the default metro, since "create this + # in every metro" is not a thing a caller can mean; a named scope + # must hold it, or the call is refused rather than sent elsewhere. + # + # @param operation [String] e.g. "Creating an instance" + # @return [Endpoint] + # @raise [Unikraft::Cloud::Error] kind `:config` when a scope of + # several metros leaves out the default one + def resolve_one(scope, operation) + return @pinned if @pinned + + default = @default_endpoint.metro + return endpoint_for(default) if scope == :all + + endpoints = resolve(scope) + return endpoints.first if endpoints.size == 1 + return endpoint_for(default) if scope.include?(default) + + metros = endpoints.map(&:metro) + raise Error.new("#{operation} targets a single metro, but the scope spans " \ + "#{metros.size} (#{metros.join(", ")}) and leaves out the default " \ + "metro (#{default}). Pick one with `ukc.metro(:#{metros.first})` " \ + "or `metros: :#{metros.first}`.", + kind: :config) + end + + # Close every transport this session built (idle connections only; + # a later call reopens them). Idempotent. + # + # @return [nil] + def close + transports = @mutex.synchronize { @transports.values } + # ApiClient#close closes the pooled idle connections. A custom + # `transport:` need only satisfy request/bytes/stream, so it may not + # have one. + transports.each { |t| t.close if t.respond_to?(:close) } + nil + end + + def inspect + "#<#{self.class.name} default=#{@default_endpoint.metro.inspect}" \ + "#{" pinned" if @pinned}>" + end + + private + + def list_metros + metros = begin + Response.list(API::ControlPlane::MetrosApi.new(transport(@controlplane_url)).list_metros, + :metros) + rescue Error => e + raise Error.new("Could not discover the available metros from the control plane. " \ + "Name the metros you want (`Unikraft::Cloud.new(metro: :fra)`, " \ + "`ukc.metro(:fra)`, or `metros: [...]`) to skip discovery.", + kind: :fanout, cause: e) + end + endpoints = metros.filter_map do |m| + # The IATA code is what users type; the control plane's endpoint + # is trusted over one built from it, so new metros just work. + code = [m[:iata_code], m[:name]].find { |c| c.is_a?(String) && !c.empty? } + code && [code, + Endpoint.new(metro: code, base_url: Metro.base_url(m[:endpoint] || code))] + end.to_h + return endpoints.freeze unless endpoints.empty? + + raise Error.new("The control plane reported no metros for this account, so there is " \ + "nothing to query.", kind: :fanout) + end + end + end + end +end diff --git a/test/support/fake_cloud.rb b/test/support/fake_cloud.rb new file mode 100644 index 0000000..927fcf6 --- /dev/null +++ b/test/support/fake_cloud.rb @@ -0,0 +1,87 @@ +# frozen_string_literal: true + +require "json" +require "uri" + +# An in-memory Unikraft Cloud: a transport builder for `transport:` that +# records every call and answers through a routing block. Fan-out runs on +# threads, so answers are routed per call rather than queued in order. +# +# cloud = FakeCloud.new { |call| FakeCloud.ok(instances: [{ name: "web" }]) } +# ukc = Unikraft::Cloud.new(token: "t", metro: :fra, transport: cloud.transport) +# +# The block returns the JSON body, or `[status, body]` for a non-2xx answer. +class FakeCloud + Call = Struct.new(:verb, :base_url, :path, :params, :body, :options, keyword_init: true) do + # `https://api.fra.unikraft.cloud` -> `fra` + def metro = URI(base_url).host.split(".")[1] + def host = URI(base_url).host + def url = base_url + path + end + + # One transport per base URL, as the session builds them. + class Transport + attr_reader :base_url, :config + + def initialize(cloud, base_url, config) + @cloud = cloud + @base_url = base_url + @config = config + end + + def request(method:, path:, query: nil, body: nil, headers: nil, **options) + @cloud.dispatch(Call.new(verb: method.to_s.upcase, path:, + base_url: options[:base_url] || @base_url, + params: FakeCloud.params(query), + body: body.nil? ? nil : JSON.parse(JSON.generate(body)), + options: options.merge(headers:).compact)) + end + + def close = @cloud.closed << @base_url + end + + attr_reader :calls, :closed, :transports + + def self.ok(data = {}) = { status: "success", op_time_us: 1, data: } + + def self.metros(*codes) + ok(metros: codes.map do |c| + { uuid: "uuid-#{c}", name: c.to_s, iata_code: c.to_s, endpoint: "https://api.#{c}.unikraft.cloud" } + end) + end + + def self.failure(status) = [status, { status: "error", op_time_us: 1, errors: [{ status: }] }] + + # The query as the URL carries it: nil dropped, arrays joined. + def self.params(query) + (query || {}).compact.to_h { |k, v| [k.to_s, Array(v).join(",")] } + end + + def initialize(&route) + @route = route + @calls = [] + @closed = [] + @transports = [] + @mutex = Mutex.new + end + + def transport + lambda do |base_url:, **config| + Transport.new(self, base_url, config).tap { |t| @mutex.synchronize { @transports << t } } + end + end + + def dispatch(call) + @mutex.synchronize { @calls << call } + answer = @route.call(call) + status, body = answer.is_a?(Array) ? answer : [200, answer] + json = JSON.parse(JSON.generate(body), symbolize_names: true) + return json if status < 300 + + raise Unikraft::Cloud::Error.new("HTTP #{status}", kind: :http, status:, + errors: json[:errors], body: json) + end + + def paths = calls.map(&:path) + def verbs = calls.map(&:verb) +end diff --git a/test/unit/session_test.rb b/test/unit/session_test.rb new file mode 100644 index 0000000..53beff6 --- /dev/null +++ b/test/unit/session_test.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/fake_cloud" + +class SessionTest < Minitest::Test + Core = Unikraft::Cloud::Core + + def session(cloud, **overrides) + Core::Session.new(config: { token: "t" }, platform_url: "https://api.fra.unikraft.cloud", + controlplane_url: Unikraft::Cloud::CONTROLPLANE_BASE_URL, + default_metro: "fra", transport: cloud.transport, **overrides) + end + + def test_discovers_once_across_threads + cloud = FakeCloud.new { FakeCloud.metros(:fra, :dal) } + s = session(cloud) + + results = Array.new(8) { Thread.new { s.discover.map(&:metro) } }.map(&:value) + + assert_equal [%w[fra dal]], results.uniq + assert_equal ["/v1/metros"], cloud.paths + assert_equal "https://controlplane.unikraft.cloud", cloud.calls.first.base_url + end + + def test_trusts_the_reported_endpoint + cloud = FakeCloud.new do + FakeCloud.ok(metros: [{ iata_code: "stg", endpoint: "https://api.stg.example/v1" }]) + end + s = session(cloud) + + assert_equal [Core::Endpoint.new(metro: "stg", base_url: "https://api.stg.example")], s.discover + assert_equal "https://api.stg.example", s.endpoint_for(:stg).base_url + end + + def test_a_failed_discovery_is_not_cached + answers = [FakeCloud.failure(500), FakeCloud.metros(:fra)] + cloud = FakeCloud.new { answers.shift } + s = session(cloud) + + err = assert_raises(Unikraft::Cloud::Error) { s.discover } + + assert_match(/Could not discover/, err.message) + assert_equal :fanout, err.kind + assert_equal 500, err.cause.status + assert_equal ["fra"], s.discover.map(&:metro) + end + + def test_a_named_scope_never_discovers + cloud = FakeCloud.new { flunk "no request expected" } + s = session(cloud) + + assert_equal %w[https://api.fra.unikraft.cloud https://api.dal.unikraft.cloud], + s.resolve(%w[fra dal]).map(&:base_url) + assert_equal "fra", s.resolve_one(:all, "Creating").metro + assert_raises(Unikraft::Cloud::Error) { s.resolve([]) } + end + + def test_one_endpoint_falls_back_to_the_default_metro + s = session(FakeCloud.new { flunk "no request expected" }) + + assert_equal "fra", s.resolve_one(:all, "Creating").metro + assert_equal "fra", s.resolve_one(%w[dal fra], "Creating").metro + assert_equal "dal", s.resolve_one(%w[dal], "Creating").metro + err = assert_raises(Unikraft::Cloud::Error) { s.resolve_one(%w[sin dal], "Creating an instance") } + + assert_equal :config, err.kind + assert_match(/targets a single metro.*leaves out the default metro \(fra\)/, err.message) + end + + def test_a_pinned_endpoint_is_the_only_one + cloud = FakeCloud.new { flunk "no request expected" } + s = session(cloud, pinned: true) + + assert_equal [s.pinned], s.resolve(:all) + assert_equal [s.pinned], s.discover + assert_equal s.pinned, s.endpoint_for(:dal) + assert_equal s.pinned, s.resolve_one(%w[fra dal], "Creating") + end + + def test_close_closes_every_transport + cloud = FakeCloud.new { FakeCloud.metros(:fra) } + s = session(cloud) + s.transport + s.discover + s.close + s.close + + assert_equal 2, cloud.transports.size + assert_includes cloud.closed, "https://controlplane.unikraft.cloud" + refute_includes s.inspect, "t\"" + end +end From ab431ebe4bf98f87cbb9943622bb973bc91824bf Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:08:32 -0800 Subject: [PATCH 20/30] feat(core): Add patch triples and the staged editor Core::Patch turns keyword arguments into the API's prop/op/value triples: a value sets the property, nil removes it (JSON Merge Patch), an omitted one is untouched, and raw triples still pass through. Patch::Editor stages set, add and remove (the API's del) and applies them as one request, chained or from a block. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/core/patch.rb | 113 +++++++++++++++++++++++++++++++ test/unit/patch_test.rb | 51 ++++++++++++++ 3 files changed, 165 insertions(+) create mode 100644 lib/unikraft/cloud/core/patch.rb create mode 100644 test/unit/patch_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 2a0159b..23fc3f6 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -17,3 +17,4 @@ require_relative "cloud/core/fanout" require_relative "cloud/core/pagination" require_relative "cloud/core/session" +require_relative "cloud/core/patch" diff --git a/lib/unikraft/cloud/core/patch.rb b/lib/unikraft/cloud/core/patch.rb new file mode 100644 index 0000000..6ebd325 --- /dev/null +++ b/lib/unikraft/cloud/core/patch.rb @@ -0,0 +1,113 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# Updating a resource. The API models an update as a list of +# `{ prop:, op:, value: }` triples. This turns that into two idiomatic forms, +# both sent as one request: +# +# update(memory_mb: 512, autokill: nil) # ops inferred +# edit.set(...).add(...).remove(...).apply # ops stated outright + +module Unikraft + module Cloud + module Core + # Patch triples from keyword arguments. + module Patch + module_function + + # Turn a patch into triples. A value takes `operation`; nil removes the + # property outright (JSON Merge Patch), whichever method supplied it. + # Omitted properties are left alone. + # + # @param patch [Hash{Symbol => Object}] + # @param operation ["set", "add", "del"] + # @return [Array] + def items(patch, operation) + patch.map do |prop, value| + value.nil? ? { prop: prop.to_s, op: "del" } : { prop: prop.to_s, op: operation, value: } + end + end + + # The triples of an `update`: a patch Hash, or raw triples as an + # escape hatch. + # + # @param changes [Hash, Array] + # @return [Array] + def changes(changes) + list = if changes.is_a?(Array) + changes.map { |c| c.transform_keys(&:to_sym) } + else + items(changes, "set") + end + raise ArgumentError, "nothing to update" if list.empty? + + list + end + + # A staged edit: chain {#set}, {#add} and {#remove}, then {#apply} to + # send every change in one request, in the order written. + # + # @example + # inst.edit.set(memory_mb: 512).add(tags: ["prod"]).remove(env: ["OLD"]).apply + # inst.edit do |e| + # e.set(memory_mb: 512) + # e.remove(autokill: nil) + # end + class Editor + # @param what [String] the noun of the error message + # @yieldparam items [Array] the triples, on {#apply} + def initialize(what, &commit) + @what = what + @commit = commit + @items = [] + end + + # Replace these properties' values; nil removes the property. + # @return [self] + def set(**patch) = stage(patch, "set") + + # Merge into these properties, keeping what is already there. + # @return [self] + def add(**patch) = stage(patch, "add") + + # Remove members from these properties (`env: ["LOG_LEVEL"]`), or + # the whole property with nil. The API calls this op `del`. + # @return [self] + def remove(**patch) = stage(patch, "del") + + # @return [Array] the triples staged so far + def changes = @items.dup.freeze + + # Send every staged change as one update. + # + # @return [Object] what the update returns: a handle, or an Array + # of them for a set + # @raise [ArgumentError] when nothing was staged + def apply + if @items.empty? + raise ArgumentError, "This #{@what} edit has no changes to apply; call set, add or " \ + "remove first." + end + + @commit.call(changes) + end + + # Values left out: any of them may be a secret (a token, credentials). + def inspect + staged = @items.map { |i| "#{i[:op]} #{i[:prop]}" }.join(", ") + "#<#{self.class.name} #{@what} #{staged}>" + end + + private + + def stage(patch, operation) + @items.concat(Patch.items(patch, operation)) + self + end + end + end + end + end +end diff --git a/test/unit/patch_test.rb b/test/unit/patch_test.rb new file mode 100644 index 0000000..63c0288 --- /dev/null +++ b/test/unit/patch_test.rb @@ -0,0 +1,51 @@ +# frozen_string_literal: true + +require_relative "../test_helper" + +class PatchTest < Minitest::Test + Patch = Unikraft::Cloud::Core::Patch + + def test_a_value_sets_and_nil_removes + assert_equal [{ prop: "memory_mb", op: "set", value: 512 }, { prop: "autokill", op: "del" }], + Patch.changes({ memory_mb: 512, autokill: nil }) + end + + def test_raw_triples_pass_through + raw = [{ "prop" => "memory_mb", "op" => "set", "value" => 1 }] + + assert_equal [{ prop: "memory_mb", op: "set", value: 1 }], Patch.changes(raw) + assert_raises(ArgumentError) { Patch.changes({}) } + end + + def test_editor_stages_in_order + sent = nil + result = Patch::Editor.new("instance") { |items| sent = items } + .set(memory_mb: 512) + .add(env: { LOG_LEVEL: "debug" }, tags: ["prod"]) + .remove(env: ["OLD"], schedules: nil) + .apply + + assert_same sent, result + assert_equal [ + { prop: "memory_mb", op: "set", value: 512 }, + { prop: "env", op: "add", value: { LOG_LEVEL: "debug" } }, + { prop: "tags", op: "add", value: ["prod"] }, + { prop: "env", op: "del", value: ["OLD"] }, + { prop: "schedules", op: "del" } + ], sent + end + + def test_editor_inspect_leaves_out_values + editor = Patch::Editor.new("instance") { flunk } + .set(image: { credentials: "SECRET" }, token: "T") + + assert_equal "#", + editor.inspect + end + + def test_an_empty_edit_refuses_to_apply + err = assert_raises(ArgumentError) { Patch::Editor.new("instance") { flunk }.apply } + + assert_match(/no changes to apply/, err.message) + end +end From 48595d68138fa2639f0761e62c893bed3bbce460 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:15:22 -0800 Subject: [PATCH 21/30] feat(core): Add handles, handle sets and the resource base Core::Resource holds a plumbing client for a metro scope and owns the shared collection verbs: create in one metro (metro: routes it, and keywords merge over a positional body), a lazy get, where for every match, a paginated fan-out list that is also the Enumerable each, bulk delete grouped per metro with the refs located concurrently, and update/edit shorthands. list takes tags: only where the operation does. It locates a ref only when the ref or the scope does not already name the metro, raises AmbiguousRefError for a ref found in several metros, and reports a resource missing everywhere as a 404 naming them. Core::Handle reads lazily and memoizes, but runs mutations at once: Ruby has no await, and a mutation nobody forced would never run. Each returns a new handle on the endpoint's result at the same location, so calls chain; a declared attribute that partial result leaves out is read once on first use. headers: and timeout: are call options in every form of update, never properties. Core::HandleSet is Enumerable over the matches and runs each operation in every metro, keeping the successes on a MetroFanoutError. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 3 + lib/unikraft/cloud/core/handle.rb | 214 ++++++++++++++ lib/unikraft/cloud/core/handle_set.rb | 105 +++++++ lib/unikraft/cloud/core/resource.rb | 399 ++++++++++++++++++++++++++ 4 files changed, 721 insertions(+) create mode 100644 lib/unikraft/cloud/core/handle.rb create mode 100644 lib/unikraft/cloud/core/handle_set.rb create mode 100644 lib/unikraft/cloud/core/resource.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 23fc3f6..503bcae 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -18,3 +18,6 @@ require_relative "cloud/core/pagination" require_relative "cloud/core/session" require_relative "cloud/core/patch" +require_relative "cloud/core/handle" +require_relative "cloud/core/handle_set" +require_relative "cloud/core/resource" diff --git a/lib/unikraft/cloud/core/handle.rb b/lib/unikraft/cloud/core/handle.rb new file mode 100644 index 0000000..4b6222e --- /dev/null +++ b/lib/unikraft/cloud/core/handle.rb @@ -0,0 +1,214 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "patch" +require_relative "ref" +require_relative "response" +require_relative "../model" + +module Unikraft + module Cloud + module Core + # Where a resource was found, and the resource itself when finding it + # already read it. + Located = Data.define(:location, :value) + + # A reference to one resource in one metro. + # + # `get` returns a handle without sending anything. Reading an attribute + # (`handle.state`) resolves it once: it locates the resource if the + # scope spans several metros, reads it, and memoizes the result. + # + # Ruby has no `await`, and a lazy mutation that nobody forces would + # silently never run, so mutations (`delete`, `update`, `apply`, and + # each resource's own verbs) run immediately. Each returns a new handle + # carrying what the endpoint reported, at the same location, so calls + # still chain: + # + # ukc.instances.get(name: "web").suspend.state # => "standby" + # + # A handle is meant for one thread. The client behind it is shared. + class Handle + class << self + # Define a reader per attribute of the resource's model, resolving + # the handle on first use. Names the handle already answers keep + # their own meaning. + # + # @param klass [Class] + def attributes_of(klass) + klass.attributes.each_key do |name| + next if method_defined?(name) || private_method_defined?(name) + + define_method(name) { attribute(name) } + end + end + end + + # @api private + # @param partial [Boolean] `located.value` is a mutation's reply, + # which may leave out attributes the resource has + def initialize(resource, ref, opts = {}, located: nil, partial: false, &locator) + @resource = resource + @ref = ref + @opts = opts + @located = located + @locator = locator + @model = located&.value + @partial = partial + end + + # Where the resource lives, locating it first if the scope spans + # several metros. Raises {AmbiguousRefError} when a name matches in + # more than one. An operation's own `headers:`/`timeout:` apply to + # that lookup too, over those given to `get`. + # + # @param call [Hash] `headers:`, `timeout:` + # @return [Location] + def location(**call) + (@located ||= @locator.call(call_opts(call))).location + end + alias resolve location + + # @return [String] the metro holding the resource + def metro = location.metro + + # The resource: what the endpoint reported for a handle a mutation + # returned, or else the resource read once and memoized. + # + # @return [Model] + def model + @model ||= (@located ||= @locator.call).value || @resource.fetch(location, + **call_opts(@opts)) + end + + # Read the resource again (in place, like ActiveRecord's reload). + # + # @return [self] + def reload(**call) + @model = @resource.fetch(location(**call), **call_opts(@opts), **call) + @partial = false + self + end + + # @return [Object] a field by its wire key, declared or not + def [](key) = model[key] + + # @return [Hash] + def to_h = model.to_h + + def deconstruct_keys(keys) = model.deconstruct_keys(keys) + + # Delete the resource. + # + # @param call [Hash] `headers:`, `timeout:` + # @return [Handle] carrying what the endpoint reported + def delete(**call) = mutate(@resource.spec.delete, [wire(call)], **call) + + # Change the resource's properties. A value sets a property, nil + # removes it, an omitted one is left alone. `headers:` and + # `timeout:` are always call options, never properties. Raw + # `{prop:, op:, value:}` triples (or a Hash) go positionally. + # + # @example + # inst.update(memory_mb: 512, autokill: nil, timeout: 10) + # inst.update([{ prop: "memory_mb", op: "set", value: 512 }]) + # @return [Handle] carrying the updated resource + def update(changes = nil, **kwargs) + call = kwargs.slice(:headers, :timeout) + props = kwargs.except(*call.keys) + if changes && props.any? + raise ArgumentError, "pass the changes positionally or as keywords, not both" + end + + patch(Patch.changes(changes || props), **call) + end + + # Stage several operations and send them as one update, at the end of + # the block or on {Patch::Editor#apply}. + # + # @example + # inst.edit.set(memory_mb: 512).add(tags: ["prod"]).apply + # inst.edit { |e| e.remove(env: ["OLD"]) } + # @yieldparam editor [Patch::Editor] + # @return [Patch::Editor, Handle] the editor, or the applied result + def edit(**call) + editor = Patch::Editor.new(@resource.spec.noun) { |items| patch(items, **call) } + return editor unless block_given? + + yield editor + editor.apply + end + + def method_missing(name, *args, &) + return super unless args.empty? && loaded_attribute?(name) + + @model[name] + end + + def respond_to_missing?(name, include_private = false) + loaded_attribute?(name) || super + end + + def inspect + return "#<#{self.class.name} #{@ref} (not loaded)>" unless @model + + "#<#{self.class.name} #{@model.inspect_fields}>" + end + alias to_s inspect + + protected + + # The ref as the request body carries it. + def wire(call = {}) = location(**call).ref.wire + + # Send update triples to where the resource lives. + def patch(items, **call) + mutate(@resource.spec.update, items.map { |item| wire(call).merge(item) }, **call) + end + + # Send one operation with `body` to the resource's metro, and return + # a handle on what it reported. + def mutate(operation, body, **call) + call = effective(call) + loc = location(**call) + res = @resource.api.public_send(operation, body:, **@resource.call_options(loc, call)) + following(loc, one(res), call) + end + + # Unwrap a single-resource response, tagged with the metro. + def one(res, key = @resource.spec.key) + Response.first(res, key, "#{@resource.spec.noun} #{location.ref}").with_metro(metro) + end + + # The handle a mutation returns keeps the options it ran with, so a + # later read uses the same credentials. + def following(loc, value, call = {}) + self.class.new(@resource, loc.ref, @opts.merge(call_opts(call)), + located: Located.new(location: loc, value:), partial: true) + end + + # A declared attribute. A mutation's reply may leave it out; then + # the resource is read once to fill it in. + def attribute(name) + value = model[name] + return value unless value.nil? && @partial + + reload(**call_opts(@opts))[name] + end + + def call_opts(opts) = opts.slice(:headers, :timeout) + + # An operation's options over the `headers:`/`timeout:` given to `get`. + def effective(call) = call_opts(@opts).merge(call) + + private + + def loaded_attribute?(name) + @model.is_a?(Model) && @model.class.attributes.key?(name) + end + end + end + end +end diff --git a/lib/unikraft/cloud/core/handle_set.rb b/lib/unikraft/cloud/core/handle_set.rb new file mode 100644 index 0000000..e8cb065 --- /dev/null +++ b/lib/unikraft/cloud/core/handle_set.rb @@ -0,0 +1,105 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# Acting on every metro that holds a name. Names are unique within a metro, +# not across them, so one name can legitimately refer to a resource in every +# metro. `where(name: ...)` addresses all of them at once, on purpose. + +require_relative "fanout" +require_relative "patch" + +module Unikraft + module Cloud + module Core + # Every resource matching one ref, one per metro. Enumerable over the + # resources; each operation runs in every metro concurrently and + # returns an Array with one result per metro. When some metros fail, + # the successes ride on the {MetroFanoutError} as `results`. + # + # The matches are located once, on first use. + # + # @example + # web = ukc.instances.where(name: "web") + # web.metros # => ["fra", "dal"] + # web.map(&:state) # => ["running", "standby"] + # web.suspend # => [handle, handle] + class HandleSet + include Enumerable + + class << self + # Expose a handle operation on the set. + # + # @param names [Array] + def forward(*names) + names.each do |name| + define_method(name) do |*args, **kw, &block| + fan(kw) { |handle| handle.public_send(name, *args, **kw, &block) } + end + end + end + end + + # @api private + def initialize(noun, &locate) + @noun = noun + @locate = locate + end + + # @param call [Hash] `headers:`/`timeout:` for the lookup, over + # those given to `where`; only the first use locates + # @return [Array] one per metro holding a match + def handles(**call) + @handles ||= @locate.call(call.slice(:headers, :timeout)).freeze + end + + # Yield each match's resource. + # + # @yieldparam resource [Model] + def each(&) + return enum_for(:each) { size } unless block_given? + + handles.each { |handle| yield handle.model } + self + end + + # @return [Array] the metros holding a match + def metros = handles.map(&:metro) + + # @return [Integer] how many metros hold a match + def size = handles.size + alias length size + + forward :delete, :update + + # Read every match again, in place. + # + # @return [self] + def reload(**call) + fan(call) { |handle| handle.reload(**call) } + self + end + + # Stage changes once and apply them to every match. + # + # @return [Patch::Editor, Array] + def edit(**call) + editor = Patch::Editor.new(@noun) do |items| + fan(call) { |handle| handle.update(items, **call) } + end + return editor unless block_given? + + yield editor + editor.apply + end + + def inspect = "#<#{self.class.name} #{@handles ? metros.inspect : "(not located)"}>" + + private + + def fan(call = {}, &) = Fanout.all(handles(**call), &) + end + end + end +end diff --git a/lib/unikraft/cloud/core/resource.rb b/lib/unikraft/cloud/core/resource.rb new file mode 100644 index 0000000..983f227 --- /dev/null +++ b/lib/unikraft/cloud/core/resource.rb @@ -0,0 +1,399 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# The base every idiomatic ("porcelain") resource client is built on. It owns +# the metro scope, the plumbing client the operations go through, and the two +# hard problems of a metro-scoped API: finding which metro holds a named +# resource, and grouping a bulk operation by metro. + +require_relative "errors" +require_relative "fanout" +require_relative "handle" +require_relative "handle_set" +require_relative "metro" +require_relative "pagination" +require_relative "ref" +require_relative "response" + +module Unikraft + module Cloud + module Core + # A porcelain client bound to a metro scope. It holds, rather than + # inherits from, its plumbing client ({#api}). + class Scoped + # The per-call options every porcelain method takes besides its own: + # `metros:` overrides the scope, `base_url:` names one endpoint, and + # `headers:` and `timeout:` go to the transport. + OPTIONS = %i[metros base_url headers timeout].freeze + + # @return [Object] the raw ("plumbing") client of this resource: every + # operation of the specification, returning the envelope untouched. + # Calls go to the scope's metro unless given `base_url:`. + attr_reader :api + # @return [:all, Array] the metros this client covers + attr_reader :scope + + # @api private + def initialize(session, scope, transport) + @session = session + @scope = scope + @api = self.class::API_CLASS.new(transport) + end + + # The keywords of one plumbing call to an endpoint. + # + # @api private + # @param target [Endpoint, Location] + # @param call [Hash] `headers:`, `timeout:`; any other {OPTIONS} key + # is ignored, and an unknown one raises + def call_options(target, call) + { base_url: target.base_url, **check_options!(call).slice(:headers, :timeout) } + end + + def inspect = "#<#{self.class.name} scope=#{@scope.inspect}>" + + private + + # The endpoints a call covers, honouring `metros:` or `base_url:`. + def endpoints(opts) + return [explicit(opts[:base_url])] if opts[:base_url] + + @session.resolve(opts.key?(:metros) ? Metro.scope(opts[:metros]) : @scope) + end + + # The single endpoint of an operation that must pick one metro. + def one_endpoint(operation, opts) + return explicit(opts[:base_url]) if opts[:base_url] + + @session.resolve_one(opts.key?(:metros) ? Metro.scope(opts[:metros]) : @scope, operation) + end + + def explicit(url) + url = Metro.base_url(url) + Endpoint.new(metro: url, base_url: url) + end + + def check_options!(opts) + unknown = opts.keys - OPTIONS + raise ArgumentError, "unknown keyword(s): #{unknown.join(", ")}" unless unknown.empty? + + opts + end + end + + # The collection operations every resource shares: create, get, where, + # list (and Enumerable), delete, update and edit. + class Resource < Scoped + include Enumerable + + # What a concrete resource is called and which operations serve it. + Spec = Data.define(:noun, :key, :list, :create, :delete, :update) + + # @api private + # @return [Spec] + def spec = self.class::SPEC + + # Create a resource in one metro and return a handle on it. Creating + # never fans out: it uses the scope's metro, or the default metro + # when the scope is wider. `metro:` picks the metro, like + # `metros: [metro]`, and never reaches the body. + # + # @param attributes [Hash, nil] the request body; keywords are + # merged over it + # @return [Handle] + def create(attributes = nil, **kwargs) + body, opts = create_args(attributes, kwargs) + endpoint = one_endpoint("Creating #{article} #{spec.noun}", opts) + res = api.public_send(spec.create, body:, **call_options(endpoint, opts)) + value = Response.first(res, spec.key, spec.noun).with_metro(endpoint.metro) + ref = Ref.new(uuid: value[:uuid], name: value[:uuid] ? nil : value[:name], + metro: endpoint.metro) + location = Location.new(ref:, metro: endpoint.metro, base_url: endpoint.base_url) + self.class::HANDLE.new(self, ref, opts, located: Located.new(location:, value:), + partial: true) + end + + # A handle on one resource. Nothing is sent until it is used; then + # the resource is located (one concurrent read per metro, unless the + # ref or the scope already names the metro) and read once. + # + # @example + # ukc.instances.get(name: "web") + # ukc.instances.get(uuid: "550e8400-e29b-41d4-a716-446655440000") + # ukc.instances.get(name: "web", metro: :fra) + # ukc.instances.get({ name: "web" }, metros: %i[fra dal]) + # @param ref [Hash, Ref, nil] or pass `name:`/`uuid:`/`metro:` + # @return [Handle] + # @raise [ArgumentError] for both or neither of name and uuid + def get(ref = nil, **kwargs) + ref, opts = split(ref, kwargs) + self.class::HANDLE.new(self, ref, opts) { |call = {}| locate(ref, opts.merge(call)) } + end + + # Every resource matching a ref, one per metro holding it: the + # deliberate plural of {#get}. + # + # @example + # ukc.instances.where(name: "web").suspend + # @return [HandleSet] + def where(ref = nil, **kwargs) + ref, opts = split(ref, kwargs) + self.class::SET.new(spec.noun) do |call = {}| + located = opts.merge(call) + locate_all(ref, located).map do |hit| + self.class::HANDLE.new(self, hit.location.ref, located, located: hit) + end + end + end + + # Every resource in scope, following each metro's pagination and + # interleaving the metros as their pages arrive. Each result is + # tagged with its `metro`. If some metros fail, the healthy ones are + # drained first, then a {MetroFanoutError} is raised. + # + # @param details [Boolean, nil] full resources rather than refs + # @param page_size [Integer, nil] the page size while paginating + # @param filters [Hash] e.g. `tags:` where the list operation takes + # it (instances, volumes), plus the call options + # @return [Enumerator, self] an Enumerator without a block + def list(details: nil, page_size: nil, **filters, &block) + opts = check_options!(takes_tags? ? filters.except(:tags) : filters) + query = { details:, tags: filters[:tags] }.compact + enum = Enumerator.new do |out| + Fanout.merge(endpoints(opts), out) do |endpoint, emit| + fetch = lambda do |count, from| + res = api.public_send(spec.list, count:, from:, **query, + **call_options(endpoint, opts)) + Response.list(res, spec.key).map { |item| item.with_metro(endpoint.metro) } + end + Pagination.each(fetch:, page_size:, &emit) + end + end + return enum unless block + + enum.each(&block) + self + end + + # Enumerable over every resource in scope, with details. + # + # @yieldparam resource [Model] + def each(&) + return enum_for(:each) unless block_given? + + list(details: true, &) + end + + # Delete one or more resources, in whichever metros hold them. Under + # a wide scope a name deletes every match in scope; qualify the ref + # or narrow the scope to delete one. + # + # @example + # ukc.instances.delete(name: "web", metro: :fra) + # ukc.instances.delete([{ name: "a" }, { uuid: "..." }]) + # @param refs [Hash, Ref, Array, nil] or pass one ref as keywords + # @return [Array] what each metro reported, tagged + def delete(refs = nil, **kwargs) = bulk(spec.delete, refs, kwargs) + + # Change one resource. Shorthand for `get(ref).update(...)`: the ref + # keys (and `metros:`/`base_url:`) locate it, `headers:` and + # `timeout:` go to the call, the rest is the patch. + # + # @example + # ukc.instances.update(name: "web", memory_mb: 512) + # ukc.instances.update({ name: "web" }, [{ prop: "vcpus", op: "set", value: 2 }]) + # @return [Handle] + def update(ref = nil, changes = nil, **kwargs) + handle, rest = on(ref, kwargs) + handle.update(changes, **rest) + end + + # Stage changes to one resource. Shorthand for `get(ref).edit`. + # + # @return [Patch::Editor, Handle] + def edit(ref = nil, **kwargs, &) + handle, call = on(ref, kwargs) + handle.edit(**call, &) + end + + # Read one resource where it was located. + # + # @api private + # @return [Model] + def fetch(location, **call) + res = api.public_send(spec.list, **location.ref.query, details: true, + **call_options(location, call)) + Response.first(res, spec.key, "#{spec.noun} #{location.ref}").with_metro(location.metro) + end + + private + + def article = spec.noun.match?(/\A[aeiou]/) ? "an" : "a" + + # Whether the list operation filters by `tags:`. + def takes_tags? = api.method(spec.list).parameters.include?(%i[key tags]) + + # The body and call options of a create: keywords merge over the + # positional attributes, and `metro:` routes rather than sends. + def create_args(attributes, kwargs) + opts = kwargs.slice(*OPTIONS) + body = (attributes || {}).merge(kwargs.except(*OPTIONS)) + if (metro = body.delete(:metro)) + raise ArgumentError, "pass `metro:` or `metros:`, not both" if opts.key?(:metros) + + opts[:metros] = metro + end + [body, opts] + end + + # A ref from a positional Hash or keywords, and the call options. + def split(ref, kwargs) + ref_kw = kwargs.slice(*Ref.members) + opts = check_options!(kwargs.except(*Ref.members)) + if ref && ref_kw.any? + raise ArgumentError, + "pass the ref positionally or as keywords, not both" + end + + [ref ? Ref.coerce(ref) : Ref.new(**ref_kw), opts] + end + + # A handle from the locating keywords, and the keywords left for the + # operation, for the shorthand forms. `headers:` and `timeout:` go to + # both: the lookup needs the same credentials as the operation. + def on(ref, kwargs) + locating = Ref.members + %i[metros base_url] + [get(ref, **kwargs.slice(*locating, :headers, :timeout)), kwargs.except(*locating)] + end + + def bulk(operation, refs, kwargs) + check_options!(kwargs) if refs # positional refs leave only options + opts = kwargs.slice(*OPTIONS) + refs = Ref.list(refs || Ref.coerce(kwargs.except(*OPTIONS))) + groups = group_by_metro(refs, opts) + run = lambda do |endpoint| + body = groups[endpoint].map(&:wire) + res = api.public_send(operation, body:, **call_options(endpoint, opts)) + Response.list(res, spec.key).map { |item| item.with_metro(endpoint.metro) } + end + return run.call(groups.keys.first) if groups.size == 1 + + Fanout.all(groups.keys, flat: true, &run) + end + + # The endpoints to search for one ref. A ref that names its metro + # needs no search and no discovery. + def endpoints_for(ref, opts) + return [@session.endpoint_for(ref.metro)] if ref.metro && !opts[:base_url] + + endpoints(opts) + end + + # Find which metro holds one resource. Free when the ref or the scope + # already says; otherwise every metro is asked concurrently, and the + # resource found travels back so it is not read twice. A name in + # several metros raises rather than guessing, since the caller may be + # about to mutate it. A uuid should be unique, but if several metros + # report it, that is just as ambiguous. + def locate(ref, opts) + found = locate_all(ref, opts) + return found.first if found.size == 1 + + metros = found.map { |hit| hit.location.metro } + id = ref.uuid ? "uuid: #{ref.uuid.inspect}" : "name: #{ref.name.inspect}" + raise AmbiguousRefError.new( + "#{spec.noun} #{ref} exists in #{found.size} metros (#{metros.join(", ")}). Say " \ + "which one with `get(#{id}, metro: :#{metros.first})`, or act on all of them " \ + "with `where(#{id})`.", + matches: found.map(&:value) + ) + end + + # Locate every metro holding a match: the same name in five metros + # is five results, not an error. One endpoint is taken on trust, + # lazily, rather than spending a request to confirm it. + def locate_all(ref, opts) + endpoints = endpoints_for(ref, opts) + if endpoints.size == 1 + return [Located.new(location: location_at(endpoints.first, ref), + value: nil)] + end + + search(ref, endpoints, opts).map do |endpoint, value| + Located.new(location: location_at(endpoint, ref), value:) + end + end + + def location_at(endpoint, ref) + Location.new(ref: ref.with(metro: endpoint.metro), metro: endpoint.metro, + base_url: endpoint.base_url) + end + + # Ask every endpoint for the ref concurrently. Absent is not a + # failure, but absent everywhere is. Any metro that could not answer + # fails the search too, even with matches elsewhere: it might hold + # another match, and the caller may be about to mutate it. + def search(ref, endpoints, opts) + outcomes = Fanout.settled(endpoints) { |endpoint| lookup(endpoint, ref, opts) } + hits = outcomes.select { |o| o.ok? && o.value } + found = hits.map { |o| [o.item, o.value.with_metro(o.item.metro)] } + failures = outcomes.reject(&:ok?).map { |o| { metro: o.item.metro, error: o.error } } + return found if failures.empty? && found.any? + + not_found(ref, endpoints.map(&:metro).join(", "), failures, found) + end + + def not_found(ref, searched, failures, found) + unreachable = failures.map { |f| f[:metro] }.join(", ") + if found.any? + raise MetroFanoutError.new( + "#{spec.noun} #{ref} was found in #{found.map { |e, _| e.metro }.join(", ")}, but " \ + "#{failures.size} metros could not be reached and might hold it too: #{unreachable}.", + failures:, results: found.map(&:last) + ) + end + if failures.any? + raise MetroFanoutError.new( + "#{spec.noun} #{ref} was not found in #{searched}, and #{failures.size} of those " \ + "metros could not be reached: #{unreachable}.", + failures: + ) + end + raise Error.new("#{spec.noun} #{ref} not found in #{searched}", kind: :http, status: 404) + end + + # Look for one resource in one metro; nil when it is not there. + def lookup(endpoint, ref, opts) + Response.absent do + res = api.public_send(spec.list, **ref.query, details: true, + **call_options(endpoint, opts)) + Response.first(res, spec.key, spec.noun) + end + end + + # Group refs by the metro holding them, so a bulk operation is one + # call per metro. Free when the scope is one metro and no ref names + # its own; otherwise refs are located concurrently, and a name + # matching in several metros counts in each. Refs that all name + # their metro skip resolving the scope, and so discovery. + def group_by_metro(refs, opts) + if refs.none?(&:metro) + endpoints = endpoints(opts) + return { endpoints.first => refs } if endpoints.size == 1 + end + + outcomes = Fanout.settled(refs) { |ref| locate_all(ref, opts) } + failed = outcomes.find { |o| !o.ok? } + raise failed.error if failed + + outcomes.flat_map(&:value).each_with_object({}) do |hit, groups| + loc = hit.location + (groups[Endpoint.new(metro: loc.metro, base_url: loc.base_url)] ||= []) << loc.ref + end + end + end + end + end +end From 721802485e67a55010770ccd953cfafdf0e38e47 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:15:46 -0800 Subject: [PATCH 22/30] feat(core): Add the client and its metro scopes Unikraft::Cloud.new builds a Client from token:, metro:, metros:, base_url:, control_plane_url:, headers:, timeout:, proxy_from_env: and a transport builder, falling back to UKC_TOKEN and UKC_METRO. A metro given as a URL is the only endpoint there is. ukc.metro(:fra) gives a cached MetroScope with its own api; ukc.metros(:fra, :dal) a Scope. ukc.api is the raw layer, ukc.available_metros the discovered metros. The client is thread-safe and meant to be shared; close closes its connections, and Unikraft::Cloud.open yields a client and closes it after the block. ApiClient#inspect leaves out the token and headers, so echoing the client, its api or a resource's api in IRB or a log cannot leak them. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/client.rb | 170 ++++++++++++++++++++++++++++++++ lib/unikraft/cloud/core/http.rb | 7 +- test/support/fake_cloud.rb | 36 +++++++ test/unit/client_test.rb | 107 ++++++++++++++++++++ 5 files changed, 318 insertions(+), 3 deletions(-) create mode 100644 lib/unikraft/cloud/client.rb create mode 100644 test/unit/client_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 503bcae..70a96c0 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -21,3 +21,4 @@ require_relative "cloud/core/handle" require_relative "cloud/core/handle_set" require_relative "cloud/core/resource" +require_relative "cloud/client" diff --git a/lib/unikraft/cloud/client.rb b/lib/unikraft/cloud/client.rb new file mode 100644 index 0000000..d542518 --- /dev/null +++ b/lib/unikraft/cloud/client.rb @@ -0,0 +1,170 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "core/http" +require_relative "core/metro" +require_relative "core/session" + +module Unikraft + # The official Ruby SDK for Unikraft Cloud. + module Cloud + # The idiomatic resource clients for one metro scope. Reads fan out across + # the scope and are merged; each result carries the `metro` it came from. + class Scope + # @return [Core::Session] the credentials, transports and metro + # discovery these clients share + attr_reader :session + # @return [:all, Array] the metros these clients cover + attr_reader :scope + + # @api private + def initialize(session, scope, transport = session.transport) + @session = session + @scope = scope + @transport = transport + end + + def inspect = "#<#{self.class.name} scope=#{@scope.inspect}>" + end + + # The resource clients for exactly one metro, from {Client#metro}. The + # metro is known, so `get(name: ...).suspend` is one request. + # + # A sandbox lives in exactly one metro, so `sandboxes` belongs here rather + # than on {Scope}, built in {#initialize} from `session` and `endpoint`. + class MetroScope < Scope + # @return [Core::Endpoint] the metro these clients are pinned to + attr_reader :endpoint + # @return [API] the raw API surfaces, the platform one pinned to this + # metro + attr_reader :api + + # @api private + def initialize(session, endpoint) + super(session, [endpoint.metro].freeze, session.transport(endpoint.base_url)) + @endpoint = endpoint + @api = session.api(endpoint.base_url) + end + end + + # The Unikraft Cloud SDK entry point, built by {Unikraft::Cloud.new}. + # + # By default the client is account-wide: reads cover every metro the + # account can reach and are merged, each result tagged with its metro. + # Narrow that with {#metro}, {#metros}, `metros:` on a call, or `metro:` + # / `metros:` here, which also skips metro discovery. + # + # A client is thread-safe and meant to be long-lived: build one and share + # it. {#close} releases its connections. + # + # @example + # ukc = Unikraft::Cloud.new(token: ENV["UKC_TOKEN"]) + # ukc.instances.each { |inst| puts "#{inst.metro} #{inst.name}" } + # ukc.metro(:fra).instances.get(name: "web").suspend + class Client < Scope + # @return [API] the raw ("plumbing") API surfaces: `api.platform` + # (pointing at the default metro unless a call passes `base_url:`) + # and `api.controlplane` + attr_reader :api + + # @param token [String, nil] bearer token; defaults to `UKC_TOKEN` + # @param metro [String, Symbol, nil] the metro of operations that must + # pick one (and the scope, unless `metros:` is given), or a full + # `http(s)://` base URL for a self-hosted deployment; defaults to + # `UKC_METRO` + # @param metros [:all, String, Symbol, Array, nil] the default scope; + # `:all` (every metro the account reaches) unless `metro:` is set + # @param base_url [String, nil] an explicit platform base URL; + # overrides `metro:` + # @param control_plane_url [String, nil] + # @param headers [Hash] sent with every request + # @param timeout [Numeric, nil] seconds per connect and read + # @param proxy_from_env [Boolean] honour `http_proxy`/`https_proxy` + # @param user_agent [String, nil] + # @param transport [#call, nil] builds the transport from the + # {Core::ApiClient} keywords (`base_url:`, `token:`, ...); for tests + # or a custom HTTP stack + def initialize(token: nil, metro: nil, metros: nil, base_url: nil, control_plane_url: nil, + headers: {}, timeout: Core::ApiClient::DEFAULT_TIMEOUT, proxy_from_env: true, + user_agent: nil, transport: nil) + metro ||= env("UKC_METRO") + explicit = base_url || (metro if Core::Metro.url?(metro)) + config = { token: token || env("UKC_TOKEN"), headers:, timeout:, proxy_from_env:, + user_agent: } + session = Core::Session.new( + config:, transport:, pinned: !explicit.nil?, + platform_url: Core::Metro.base_url(explicit || metro || DEFAULT_METRO), + controlplane_url: control_plane_url || CONTROLPLANE_BASE_URL, + default_metro: (metro || DEFAULT_METRO).to_s + ) + scope = Core::Metro.scope(metros || metro || :all) + super(session, scope) + @api = session.api + @scopes = {} + @mutex = Mutex.new + end + + # The resource clients for one metro, cached. + # + # @param metro [String, Symbol] + # @return [MetroScope] + def metro(metro) + endpoint = session.endpoint_for(metro) + @mutex.synchronize { @scopes[endpoint.base_url] ||= MetroScope.new(session, endpoint) } + end + + # The resource clients for several metros, or every one. + # + # @example + # ukc.metros(:fra, :dal).instances.to_a + # ukc.metros(:all) + # @return [Scope] + def metros(*metros) = Scope.new(session, Core::Metro.scope(metros)) + + # Every metro the account can reach, as the control plane reports it, + # cached for the client's lifetime. + # + # @return [Array] each with `metro` and `base_url` + def available_metros = session.discover + + # Close every connection the client opened. Idempotent; a later call + # reopens what it needs. + # + # @return [nil] + def close = session.close + + private + + def env(name) + value = ENV.fetch(name, nil) + value unless value.nil? || value.empty? + end + end + + class << self + # Build a client. + # + # @example + # ukc = Unikraft::Cloud.new(token: ENV["UKC_TOKEN"]) + # @param (see Client#initialize) + # @return [Client] + def new(**) = Client.new(**) + + # Build a client, yield it, and close it when the block returns. + # + # @example + # Unikraft::Cloud.open(metro: :fra) { |ukc| ukc.instances.count } + # @param (see Client#initialize) + # @yieldparam ukc [Client] + # @return [Object] the block's value + def open(**) + client = Client.new(**) + yield client + ensure + client&.close + end + end + end +end diff --git a/lib/unikraft/cloud/core/http.rb b/lib/unikraft/cloud/core/http.rb index 82d28a8..78a8c22 100644 --- a/lib/unikraft/cloud/core/http.rb +++ b/lib/unikraft/cloud/core/http.rb @@ -100,13 +100,14 @@ def initialize(base_url:, token: nil, headers: {}, user_agent: nil, @pool = Pool.new end + # Leaves out the token and headers, so echoing what holds it is safe. + def inspect = "#<#{self.class.name} base_url=#{@base_url.inspect}>" + # Close the idle connections. Calls made afterwards open new ones, # so this is safe to call at any time, and more than once. # # @return [nil] - def close - @pool.close - end + def close = @pool.close # Perform a request and return its parsed JSON body (symbol keys). # diff --git a/test/support/fake_cloud.rb b/test/support/fake_cloud.rb index 927fcf6..a55f59c 100644 --- a/test/support/fake_cloud.rb +++ b/test/support/fake_cloud.rb @@ -84,4 +84,40 @@ def dispatch(call) def paths = calls.map(&:path) def verbs = calls.map(&:verb) + + # A developer's real UKC_METRO or UKC_TOKEN would change what the porcelain + # tests exercise, so they are cleared around each test. + module Helpers + def setup + super + @saved_env = ENV.to_h.slice("UKC_METRO", "UKC_TOKEN") + ENV.delete("UKC_METRO") + ENV.delete("UKC_TOKEN") + end + + def teardown + ENV.delete("UKC_METRO") # a test may have set one the environment lacked + ENV.delete("UKC_TOKEN") + @saved_env.each { |k, v| ENV[k] = v } + super + end + + def ok(data = {}) = FakeCloud.ok(data) + + # A client over a FakeCloud routed by the block; the cloud is @cloud. + def client(**, &) + @cloud = FakeCloud.new(&) + Unikraft::Cloud.new(token: "t", transport: @cloud.transport, **) + end + + # Answers as if every metro listed holds a resource under `key`, and + # the control plane reports those metros. + def everywhere(codes, key: :instances, **opts) + client(**opts) do |call| + next FakeCloud.metros(*codes) if call.path == "/v1/metros" + + ok(key => [{ uuid: "u-#{call.metro}", name: "web", state: "running" }]) + end + end + end end diff --git a/test/unit/client_test.rb b/test/unit/client_test.rb new file mode 100644 index 0000000..be4e6b5 --- /dev/null +++ b/test/unit/client_test.rb @@ -0,0 +1,107 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require "pp" +require_relative "../support/fake_cloud" + +class ClientTest < Minitest::Test + include FakeCloud::Helpers + + def test_new_builds_a_client + ukc = client(metro: :dal) { ok } + + assert_kind_of Unikraft::Cloud::Client, ukc + assert_equal %w[dal], ukc.scope + assert_equal "t", @cloud.transports.first.config[:token] + end + + def test_reads_token_and_metro_from_the_environment + ENV["UKC_TOKEN"] = "from-env" + ENV["UKC_METRO"] = "sin" + cloud = FakeCloud.new { ok } + ukc = Unikraft::Cloud.new(transport: cloud.transport) + + assert_equal %w[sin], ukc.scope + assert_equal "from-env", cloud.transports.first.config[:token] + assert_equal "https://api.sin.unikraft.cloud", cloud.transports.first.base_url + end + + def test_scope_precedence + assert_equal :all, client { ok }.scope + assert_equal %w[fra dal], client(metro: :sin, metros: %i[fra dal]).scope + assert_equal :all, client(metro: :sin, metros: :all).scope + assert_equal %w[fra dal], client { ok }.metros(:fra, "dal").scope + assert_equal :all, client { ok }.metros(:all).scope + end + + def test_raw_layers + ukc = client(metro: :fra) { ok(instances: [{ uuid: "u1" }]) } + res = ukc.api.platform.instances.get_instances(count: 10) + + assert_equal "success", res.status + assert_equal "https://api.fra.unikraft.cloud", @cloud.calls.last.base_url + ukc.api.controlplane.metros.list_metros + + assert_equal "https://controlplane.unikraft.cloud/v1/metros", @cloud.calls.last.url + ukc.metro(:dal).api.platform.instances.get_instances + + assert_equal "https://api.dal.unikraft.cloud", @cloud.calls.last.base_url + end + + def test_metro_scopes_are_cached + ukc = client { ok } + + assert_same ukc.metro(:fra), ukc.metro("fra") + refute_same ukc.metro(:fra), ukc.metro(:dal) + assert_equal "fra", ukc.metro(:fra).endpoint.metro + end + + def test_available_metros + ukc = client { FakeCloud.metros(:fra, :dal) } + + assert_equal([%w[fra https://api.fra.unikraft.cloud], %w[dal https://api.dal.unikraft.cloud]], + ukc.available_metros.map { |m| [m.metro, m.base_url] }) + assert_equal %w[fra dal sin was sfo], Unikraft::Cloud::KNOWN_METROS + end + + def test_a_url_metro_is_used_verbatim_and_never_discovers + ukc = client(metro: "https://api.staging.internal/v1", + control_plane_url: "https://cp.staging.internal") { ok } + + assert_equal ["https://api.staging.internal"], ukc.available_metros.map(&:base_url) + assert_equal "https://api.staging.internal", ukc.metro(:dal).endpoint.base_url + + assert_empty @cloud.calls + ukc.api.controlplane.metros.list_metros + + assert_equal "https://cp.staging.internal", @cloud.calls.last.base_url + end + + def test_close_and_open + ukc = client { FakeCloud.metros(:fra) } + ukc.available_metros + ukc.close + + assert_includes @cloud.closed, "https://controlplane.unikraft.cloud" + cloud = FakeCloud.new { ok } + value = Unikraft::Cloud.open(token: "t", metro: :fra, transport: cloud.transport) do |c| + c.api.platform.instances.get_instances + :done + end + + assert_equal :done, value + assert_equal ["https://api.fra.unikraft.cloud", "https://controlplane.unikraft.cloud"], + cloud.closed.sort + end + + def test_inspect_hides_the_token + refute_includes client(token: "secret") { ok }.inspect, "secret" + ukc = Unikraft::Cloud.new(token: "secret", metro: :fra, headers: { "X-Key" => "hidden" }) + + [ukc, ukc.api, ukc.api.platform.instances, ukc.metro(:dal).api].each do |object| + refute_includes object.inspect, "secret" + refute_includes PP.pp(object, +""), "secret" + refute_includes object.inspect, "hidden" + end + end +end From 8ef9ab748a349bbd1c3ca93c0eff38b019e01432 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:16:00 -0800 Subject: [PATCH 23/30] feat(instances): Add the idiomatic instances client ukc.instances adds bulk start, stop and suspend to the shared verbs, and shorthands for wait, logs, metrics and history. InstanceHandle reads each instance attribute lazily, answers running?, stopped? and the other API states, and chains start, stop, suspend, wait, logs, metrics and history. wait forwards state and within: (seconds) to the server-side wait and stretches the read timeout to outlive it; timeout: stays the HTTP timeout, as on every call. where(name:) returns an InstanceSet that runs each of those in every metro holding the name. The tests port the JS SDK's client suite: fan-out merge and metro tags, ambiguity of names and of uuids, partial failure, create in one metro, bulk grouped per metro, patch triples, the editor, handles running each step once, scope precedence and URL metros. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/client.rb | 3 + lib/unikraft/cloud/resources/instances.rb | 172 +++++ test/unit/instances_test.rb | 754 ++++++++++++++++++++++ 4 files changed, 930 insertions(+) create mode 100644 lib/unikraft/cloud/resources/instances.rb create mode 100644 test/unit/instances_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 70a96c0..2060725 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -21,4 +21,5 @@ require_relative "cloud/core/handle" require_relative "cloud/core/handle_set" require_relative "cloud/core/resource" +require_relative "cloud/resources/instances" require_relative "cloud/client" diff --git a/lib/unikraft/cloud/client.rb b/lib/unikraft/cloud/client.rb index d542518..fb76aa5 100644 --- a/lib/unikraft/cloud/client.rb +++ b/lib/unikraft/cloud/client.rb @@ -18,12 +18,15 @@ class Scope attr_reader :session # @return [:all, Array] the metros these clients cover attr_reader :scope + # @return [Resources::Instances] instances (microVMs) + attr_reader :instances # @api private def initialize(session, scope, transport = session.transport) @session = session @scope = scope @transport = transport + @instances = Resources::Instances.new(session, scope, transport) end def inspect = "#<#{self.class.name} scope=#{@scope.inspect}>" diff --git a/lib/unikraft/cloud/resources/instances.rb b/lib/unikraft/cloud/resources/instances.rb new file mode 100644 index 0000000..46a0d7a --- /dev/null +++ b/lib/unikraft/cloud/resources/instances.rb @@ -0,0 +1,172 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "../core/resource" +require_relative "../api/platform" + +module Unikraft + module Cloud + # The idiomatic ("porcelain") resource clients. + module Resources + # A handle on one instance (see {Core::Handle}). Readers such as + # `state` and `memory_mb` resolve it once; `running?`, `stopped?` and + # the other predicates compare `state` with each API state. + # + # @example + # web = ukc.instances.get(name: "web") + # web.running? # one read, memoized + # web.suspend.state # => "standby" + # fra.instances.create(image: "nginx:latest") + # .wait(state: :running, within: 30) + # .logs(offset: -4096) + class InstanceHandle < Core::Handle + # Start the instance. + # @return [InstanceHandle] carrying what the endpoint reported + def start(**call) = mutate(:start_instances, [wire(call)], **call) + + # Stop the instance. + # @return [InstanceHandle] + def stop(**call) = mutate(:stop_instances, [wire(call)], **call) + + # Suspend the instance. + # @return [InstanceHandle] + def suspend(**call) = mutate(:suspend_instances, [wire(call)], **call) + + # Block until the instance reaches a state. The platform holds the + # request open until then, and fails it when `within` passes first, + # so this raises rather than returning. + # + # @param state [Symbol, String, nil] e.g. `:running` (the API's + # default) + # @param within [Integer, nil] seconds the platform waits; -1 waits + # indefinitely. The read timeout of the request is stretched to + # cover it, unless `timeout:` sets it. + # @param call [Hash] `headers:`, `timeout:` (the HTTP timeout, as + # on every call) + # @return [InstanceHandle] carrying the observed state + def wait(state: nil, within: nil, **call) + http = call + # The connection must outlive the server-side wait. + http = { timeout: within.negative? ? nil : within + 10 }.merge(call) if within + http = effective(http) + loc = location(**http) + res = @resource.api.wait_instances(**loc.ref.query, state: state && [state.to_s], + timeout_s: within && [within], + **@resource.call_options(loc, http)) + following(loc, one(res), effective(call)) + end + + # The console log. `output` is base64, as the API sends it. + # + # @param offset [Integer, nil] byte offset; negative counts from the end + # @param limit [Integer, nil] at most this many bytes + # @return [Model] tagged with the metro + def logs(offset: nil, limit: nil, **call) + call = effective(call) + loc = location(**call) + one(@resource.api.get_instance_logs(**loc.ref.query, offset: offset && [offset], + limit: limit && [limit], + **@resource.call_options(loc, call))) + end + + # Resource-usage metrics. + # @return [Model] + def metrics(**call) + call = effective(call) + loc = location(**call) + one(@resource.api.get_instance_metrics(**loc.ref.query, + **@resource.call_options(loc, call))) + end + + # The state-change history: this instance's entries, each tagged + # with the metro. A failed per-instance result raises. + # @return [Array] + def history(**call) + call = effective(call) + loc = location(**call) + res = @resource.api.get_instance_history(**loc.ref.query, + **@resource.call_options(loc, call)) + Array(one(res, :instances)[:history]).map { |entry| entry.with_metro(loc.metro) } + end + + API::Platform::Models::InstanceState::ALL.each do |value| + define_method(:"#{value}?") { state == value } + end + + attributes_of API::Platform::Models::Instance + end + + # Every instance matching one ref, one per metro (see + # {Core::HandleSet}). + # + # @example + # ukc.instances.where(name: "web").suspend + class InstanceSet < Core::HandleSet + forward :start, :stop, :suspend, :wait, :logs, :metrics, :history + end + + # Instances (microVMs). Enumerable over every instance in scope. + # + # @example + # ukc.instances.list(details: true).each { |i| puts "#{i.metro} #{i.name}" } + # ukc.instances.select { |i| i.state == "running" } + # ukc.instances.get(name: "web").suspend + # ukc.instances.stop([{ name: "a" }, { name: "b" }]) + class Instances < Core::Resource + API_CLASS = API::Platform::InstancesApi + HANDLE = InstanceHandle + SET = InstanceSet + SPEC = Spec.new(noun: "instance", key: :instances, list: :get_instances, + create: :create_instance, delete: :delete_instances, + update: :update_instances) + + # Start one or more instances, in whichever metros hold them. + # @param (see Core::Resource#delete) + # @return [Array] + def start(refs = nil, **kwargs) = bulk(:start_instances, refs, kwargs) + + # Stop one or more instances. + # @return [Array] + def stop(refs = nil, **kwargs) = bulk(:stop_instances, refs, kwargs) + + # Suspend one or more instances. + # @return [Array] + def suspend(refs = nil, **kwargs) = bulk(:suspend_instances, refs, kwargs) + + # Shorthand for `get(ref).wait(...)`: the ref keys (and `metros:`) + # locate the instance, the rest go to the operation. + # + # @example + # ukc.instances.wait(name: "web", state: :running, within: 30) + # @return [InstanceHandle] + def wait(ref = nil, **kwargs) + handle, rest = on(ref, kwargs) + handle.wait(**rest) + end + + # Shorthand for `get(ref).logs(...)`. + # @return [Model] + def logs(ref = nil, **kwargs) + handle, rest = on(ref, kwargs) + handle.logs(**rest) + end + + # Shorthand for `get(ref).metrics`. + # @return [Model] + def metrics(ref = nil, **kwargs) + handle, rest = on(ref, kwargs) + handle.metrics(**rest) + end + + # Shorthand for `get(ref).history`. + # @return [Array] + def history(ref = nil, **kwargs) + handle, rest = on(ref, kwargs) + handle.history(**rest) + end + end + end + end +end diff --git a/test/unit/instances_test.rb b/test/unit/instances_test.rb new file mode 100644 index 0000000..02f403b --- /dev/null +++ b/test/unit/instances_test.rb @@ -0,0 +1,754 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/fake_cloud" + +class InstancesTest < Minitest::Test + include FakeCloud::Helpers + + UUID = "550e8400-e29b-41d4-a716-446655440000" + + def instance(name = "web", **fields) = ok(instances: [{ uuid: "u1", name:, **fields }]) + + # The web instance, in `metro` only. + def web_in(metro, call) = ok(instances: call.metro == metro ? [{ uuid: "u1", name: "web" }] : []) + + # --- one metro ----------------------------------------------------------- + + def test_get_is_lazy_and_reads_once + ukc = client(metro: :dal) { instance(state: "running") } + web = ukc.instances.get(name: "web") + + assert_empty @cloud.calls + assert_equal "running", web.state + assert_predicate web, :running? + assert_equal "dal", web.model.metro + assert_equal 1, @cloud.calls.size + call = @cloud.calls.first + + assert_equal "https://api.dal.unikraft.cloud", call.base_url + assert_equal "/v1/instances", call.path + # Only the identifier the caller gave is sent. + assert_equal({ "name" => "web", "details" => "true" }, call.params) + end + + def test_uuid_refs_query_by_uuid_alone + ukc = client(metro: :fra) { ok(instances: [{ uuid: UUID }]) } + ukc.instances.get(uuid: UUID).model + + assert_equal({ "uuid" => UUID, "details" => "true" }, @cloud.calls.first.params) + end + + def test_refs_need_exactly_one_identifier + ukc = client(metro: :fra) { flunk } + + assert_raises(ArgumentError) { ukc.instances.get(name: "a", uuid: "b") } + assert_raises(ArgumentError) { ukc.instances.get } + assert_raises(ArgumentError) { ukc.instances.get(nme: "web") } + assert_raises(ArgumentError) { ukc.instances.delete(name: "a", uuid: "b") } + assert_raises(ArgumentError) { ukc.instances.stop({ name: "web" }, timout: 5) } + assert_raises(ArgumentError) { ukc.instances.get(name: "web", metro: :fra).stop(timout: 5) } + end + + def test_http_errors_raise + ukc = client(metro: :fra) { FakeCloud.failure(404) } + err = assert_raises(Unikraft::Cloud::Error) { ukc.instances.get(name: "missing").state } + + assert_equal 404, err.status + end + + def test_a_per_entry_failure_raises + ukc = client(metro: :fra) do + { status: "error", message: "Failed to perform all operations", + data: { instances: [{ status: "error", error: 8, + message: "No instance with uuid 'u1'" }] } } + end + err = assert_raises(Unikraft::Cloud::Error) { ukc.instances.get(uuid: "u1").model } + + assert_equal 404, err.status + assert_equal "No instance with uuid 'u1'", err.message + end + + def test_list_paginates_lazily + first = Array.new(100) { |n| { uuid: "u#{n}", name: "i#{n}" } } + ukc = client(metro: :fra) do |call| + ok(instances: call.params["from"] ? [{ uuid: "u100", name: "i100" }] : first) + end + enum = ukc.instances.list + + assert_kind_of Enumerator, enum + assert_empty @cloud.calls + assert_equal 101, enum.count + assert_equal "u99", @cloud.calls[1].params["from"] + assert_equal "100", @cloud.calls[0].params["count"] + end + + def test_list_takes_a_block_and_resources_are_enumerable + ukc = client(metro: :fra) { ok(instances: [{ name: "a", state: "running" }, { name: "b" }]) } + names = [] + ukc.instances.list(tags: %w[prod]) { |i| names << i.name } + + assert_equal %w[a b], names + assert_equal "prod", @cloud.calls.last.params["tags"] + assert_equal ["a"], ukc.instances.select { |i| i.state == "running" }.map(&:name) + assert_equal "true", @cloud.calls.last.params["details"] + assert_equal "a", ukc.instances.first.name + assert_same(ukc.instances, ukc.instances.list { nil }) + end + + def test_a_bug_in_one_metro_propagates_rather_than_failing_it + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + raise NoMethodError, "bug" if call.metro == "dal" + + ok(instances: []) + end + + assert_raises(ArgumentError) { ukc.instances.list(colour: "red") } + assert_raises(NoMethodError) { ukc.instances.to_a } + end + + def test_list_raises_on_an_error_envelope + ukc = client(metro: :fra) { { status: "error", message: "nope", errors: [{ status: 500 }] } } + + assert_raises(Unikraft::Cloud::Error) { ukc.instances.to_a } + end + + def test_create_sends_the_body_as_given + ukc = client(metro: :fra) { instance } + ukc.instances.create(image: "nginx:latest", memory_mb: 256) + ukc.instances.create({ image: { url: "nginx:latest", credentials: "tok" } }) + ukc.instances.create({ image: "a", memory_mb: 128 }, memory_mb: 256) + + assert_equal({ "image" => "nginx:latest", "memory_mb" => 256 }, @cloud.calls[0].body) + assert_equal({ "image" => { "url" => "nginx:latest", "credentials" => "tok" } }, + @cloud.calls[1].body) + assert_equal({ "image" => "a", "memory_mb" => 256 }, @cloud.calls[2].body) + assert_equal %w[POST POST POST], @cloud.verbs + end + + def test_create_takes_metro_as_routing + ukc = client(metros: %i[fra dal]) { instance } + + assert_equal "dal", ukc.instances.create(metro: :dal, image: "x").metro + assert_equal "api.dal.unikraft.cloud", @cloud.calls.last.host + assert_equal({ "image" => "x" }, @cloud.calls.last.body) + assert_raises(ArgumentError) { ukc.instances.create(image: "x", metro: :dal, metros: :fra) } + end + + def test_logs_and_wait_send_query_params_only + ukc = client(metro: :fra) { ok(instances: [{ output: "aGk=", state: "running" }]) } + logs = ukc.instances.logs(name: "web", offset: -4096, limit: 4096) + + assert_equal "aGk=", logs.output + assert_equal "fra", logs.metro + assert_equal({ "name" => "web", "offset" => "-4096", "limit" => "4096" }, + @cloud.calls[0].params) + assert_nil @cloud.calls[0].body + ukc.instances.wait(name: "web", state: :running, within: 30) + + assert_equal "/v1/instances/wait", @cloud.calls[1].path + assert_equal({ "name" => "web", "state" => "running", "timeout_s" => "30" }, + @cloud.calls[1].params) + # The read must outlive the server-side wait. + assert_equal 40, @cloud.calls[1].options[:timeout] + end + + def test_wait_keeps_timeout_as_the_http_option + ukc = client(metro: :fra) { instance(state: "running") } + ukc.instances.get(name: "web").wait(within: 30, timeout: 90) + ukc.instances.get(name: "web").wait(timeout: 5) + + assert_equal({ "name" => "web", "timeout_s" => "30" }, @cloud.calls[0].params) + assert_equal 90, @cloud.calls[0].options[:timeout] + assert_equal({ "name" => "web" }, @cloud.calls[1].params) + assert_equal 5, @cloud.calls[1].options[:timeout] + end + + def test_history_and_metrics + ukc = client(metro: :fra) do + ok(instances: [{ name: "web", state: "running", history: [{ uuid: "c1" }, { uuid: "c2" }] }]) + end + + assert_equal %w[c1 c2], ukc.instances.history(name: "web").map(&:uuid) + assert_equal "/v1/instances/history", @cloud.calls.last.path + assert_equal "running", ukc.instances.get(name: "web").metrics[:state] + assert_equal "/v1/instances/metrics", @cloud.calls.last.path + end + + def test_bulk_one_metro_sends_one_call + ukc = client(metro: :fra) { ok(instances: [{ uuid: "u1" }, { uuid: "u2" }]) } + results = ukc.instances.delete([{ name: "web" }, { uuid: UUID }]) + + assert_equal 1, @cloud.calls.size + assert_equal "DELETE", @cloud.calls.first.verb + assert_equal [{ "name" => "web" }, { "uuid" => UUID }], @cloud.calls.first.body + assert_equal %w[fra fra], results.map(&:metro) + ukc.instances.stop(name: "web") + + assert_equal ["/v1/instances/stop", [{ "name" => "web" }]], + [@cloud.paths.last, @cloud.calls.last.body] + end + + # --- the two layers ---------------------------------------------------- + + def test_a_resource_api_hides_the_token + api = Unikraft::Cloud.new(token: "secret", metro: :fra).instances.api + + refute_includes api.inspect, "secret" + end + + def test_per_resource_escape_hatch + ukc = client(metro: :fra) { ok(instances: [{ uuid: "u1" }]) } + + assert_equal "u1", ukc.instances.api.get_instances(count: 1).data.instances.first.uuid + ukc.metro(:dal).instances.api.get_instances + + assert_equal "https://api.dal.unikraft.cloud", @cloud.calls.last.base_url + end + + # --- metro scope ------------------------------------------------------- + + def test_fan_out_merges_and_tags + ukc = client do |call| + next FakeCloud.metros(:fra, :dal, :sin) if call.path == "/v1/metros" + + ok(instances: [{ uuid: "u-#{call.metro}", name: "web-#{call.metro}" }]) + end + + assert_equal %w[dal:web-dal fra:web-fra sin:web-sin], + ukc.instances.list(details: true).map { |i| "#{i.metro}:#{i.name}" }.sort + assert_equal 1, @cloud.paths.count("/v1/metros") + assert_equal 4, @cloud.calls.size + ukc.instances.to_a + + assert_equal 1, @cloud.paths.count("/v1/metros") + end + + def test_named_metros_skip_discovery + ukc = client { ok(instances: []) } + ukc.instances.list(metros: %i[fra dal]).to_a + + assert_equal %w[api.dal.unikraft.cloud api.fra.unikraft.cloud], @cloud.calls.map(&:host).sort + ukc.metros(:sin).instances.to_a + + assert_equal "api.sin.unikraft.cloud", @cloud.calls.last.host + end + + def test_a_repeated_metro_is_searched_once + ukc = everywhere(%i[fra dal]) + + assert_equal "u-fra", ukc.metros(:fra, "fra").instances.get(name: "web").uuid + assert_equal 1, @cloud.calls.size + end + + def test_shorthand_locates_with_the_call_options + ukc = client do |call| + ok(instances: call.metro == "fra" ? [{ uuid: "u", name: "web" }] : []) + end + ukc.instances.update(name: "web", metros: %i[fra dal], timeout: 5, headers: { "X-A" => "1" }, + memory_mb: 512) + + assert_equal 3, @cloud.calls.size # two lookups, one update + assert_equal([5] * 3, @cloud.calls.map { |c| c.options[:timeout] }) + assert_equal([{ "X-A" => "1" }] * 3, @cloud.calls.map { |c| c.options[:headers] }) + end + + def test_a_handle_operation_locates_with_its_own_options + ukc = client do |call| + ok(instances: call.metro == "fra" ? [{ uuid: "u", name: "web" }] : []) + end + ukc.instances.get(name: "web", metros: %i[fra dal], timeout: 1).suspend(timeout: 5) + + assert_equal([5] * 3, @cloud.calls.map { |c| c.options[:timeout] }) + end + + def test_a_handle_operation_keeps_the_options_of_get + ukc = client(metro: :fra) { ok(instances: [{ uuid: "u", name: "web" }]) } + web = ukc.instances.get(name: "web", headers: { "X-A" => "1" }) + web.suspend + web.logs(timeout: 3) + + assert_equal([{ "X-A" => "1" }] * 2, @cloud.calls.map { |c| c.options[:headers] }) + assert_equal 3, @cloud.calls.last.options[:timeout] + end + + def test_a_returned_handle_reads_with_the_options_it_ran_with + ukc = client(metro: :fra) { ok(instances: [{ uuid: "u", name: "web" }]) } + ukc.instances.get(name: "web").suspend(headers: { "X-B" => "2" }).state + + assert_equal([{ "X-B" => "2" }] * 2, @cloud.calls.map { |c| c.options[:headers] }) + end + + def test_a_set_operation_locates_with_its_own_options + ukc = everywhere(%i[fra dal]) + ukc.instances.where(name: "web").suspend(timeout: 5) + + timeouts = @cloud.calls.reject { |c| c.path == "/v1/metros" }.map { |c| c.options[:timeout] } + + assert_equal [5] * 4, timeouts # two lookups, two suspends + end + + def test_qualified_refs_skip_discovery_in_bulk + ukc = everywhere(%i[fra dal]) + ukc.instances.delete(name: "web", metro: :fra) + + refute_includes @cloud.paths, "/v1/metros" + assert_equal ["https://api.fra.unikraft.cloud/v1/instances"], @cloud.calls.map(&:url) + end + + def test_per_call_base_url_is_normalized + ukc = client { ok(instances: [{ uuid: "u1", name: "web" }]) } + found = ukc.instances.list(base_url: "https://api.staging.internal/v1/").to_a + + assert_equal ["https://api.staging.internal"], @cloud.calls.map(&:base_url) + assert_equal "https://api.staging.internal", found.first.metro + end + + def test_a_url_metro_never_discovers + ukc = client(metro: "https://api.staging.internal/v1") { ok(instances: [{ uuid: "u1" }]) } + ukc.instances.to_a + + assert_equal ["https://api.staging.internal/v1/instances"], @cloud.calls.map(&:url) + end + + def test_partial_failure_drains_healthy_metros_first + ukc = client do |call| + next FakeCloud.metros(:fra, :dal, :sin) if call.path == "/v1/metros" + next FakeCloud.failure(503) if call.metro == "sin" + + ok(instances: [{ uuid: "u-#{call.metro}" }]) + end + seen = [] + err = assert_raises(Unikraft::Cloud::MetroFanoutError) do + ukc.instances.each { |i| seen << i.metro } + end + + assert_equal %w[dal fra], seen.sort + assert_includes err.message, "1 of 3 metros failed: sin (503)" + assert_equal 503, err.status + end + + def test_breaking_early_stops_the_other_metros + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + + ok(instances: [{ uuid: "u-#{call.metro}" }]) + end + ukc.instances.list.first + + assert_operator @cloud.calls.size, :<=, 3 + end + + def test_discovery_failure_explains_itself + ukc = client { FakeCloud.failure(500) } + err = assert_raises(Unikraft::Cloud::Error) { ukc.instances.to_a } + + assert_match(/Could not discover/, err.message) + end + + def test_locates_then_acts_only_where_it_lives + ukc = client do |call| + next FakeCloud.metros(:fra, :dal, :sin) if call.path == "/v1/metros" + next instance(state: "standby") if call.path.end_with?("suspend") + + web_in("dal", call) + end + suspended = ukc.instances.get(name: "web").suspend + + assert_equal "standby", suspended.state + assert_equal "dal", suspended.metro + suspends = @cloud.calls.select { |c| c.path == "/v1/instances/suspend" } + + assert_equal ["api.dal.unikraft.cloud"], suspends.map(&:host) + end + + def test_missing_everywhere_is_a_404_naming_the_metros + misses = [ + ok(instances: []), + { status: "error", message: "Failed to perform all operations", + data: { instances: [{ status: "error", error: 8, + message: "No instance with name 'nope'" }] } } + ] + misses.each do |miss| + ukc = client { |call| call.path == "/v1/metros" ? FakeCloud.metros(:fra, :dal) : miss } + err = assert_raises(Unikraft::Cloud::Error) { ukc.instances.get(name: "nope").model } + + assert_equal 404, err.status + assert_equal 'instance name "nope" not found in fra, dal', err.message + end + end + + def test_bulk_acts_on_every_metro_a_name_matches + ukc = client do |call| + next FakeCloud.metros(:fra, :dal, :sin) if call.path == "/v1/metros" + next ok(instances: []) if call.verb == "GET" && call.metro == "sin" + next instance if call.verb == "GET" + + ok(instances: [{ uuid: "u-#{call.metro}" }]) + end + deleted = ukc.instances.delete(name: "web") + + deletes = @cloud.calls.select { |c| c.verb == "DELETE" } + + assert_equal %w[api.dal.unikraft.cloud api.fra.unikraft.cloud], deletes.map(&:host).sort + assert(deletes.all? { |c| c.body == [{ "name" => "web" }] }) + assert_equal %w[dal fra], deleted.map(&:metro).sort + end + + def test_bulk_groups_refs_by_metro + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + + if call.verb == "GET" + name = call.params["name"] + here = (call.metro == "fra" && name == "a") || (call.metro == "dal" && name == "b") + next ok(instances: here ? [{ uuid: "u-#{name}", name: }] : []) + end + ok(instances: [{ uuid: "u-#{call.metro}" }]) + end + ukc.instances.delete([{ name: "a" }, { name: "b" }]) + deletes = @cloud.calls.select { |c| c.verb == "DELETE" }.to_h { |c| [c.metro, c.body] } + + assert_equal({ "fra" => [{ "name" => "a" }], "dal" => [{ "name" => "b" }] }, deletes) + end + + def test_bulk_locates_refs_concurrently + mutex = Mutex.new + in_flight = peak = 0 + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + next ok(instances: [{ uuid: "u" }]) unless call.verb == "GET" + + mutex.synchronize { peak = [peak, in_flight += 1].max } + sleep 0.05 + mutex.synchronize { in_flight -= 1 } + ok(instances: call.metro == "fra" ? [{ uuid: "u", name: call.params["name"] }] : []) + end + ukc.instances.stop([{ name: "a" }, { name: "b" }]) + + # Two refs across two metros: one at a time would peak at two. + assert_operator peak, :>, 2 + end + + def test_bulk_partial_failure_keeps_results + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + next FakeCloud.failure(503) if call.verb == "PUT" && call.metro == "dal" + + ok(instances: [{ uuid: "u-#{call.metro}", name: "web" }]) + end + err = assert_raises(Unikraft::Cloud::MetroFanoutError) { ukc.instances.stop(name: "web") } + + assert_equal ["fra"], err.results.map(&:metro) + assert_equal(["dal"], err.failures.map { |f| f[:metro] }) + end + + def test_create_needs_one_metro + ukc = client { instance } + + assert_equal "fra", ukc.instances.create(image: "nginx:latest").metro + assert_equal ["https://api.fra.unikraft.cloud/v1/instances"], @cloud.calls.map(&:url) + assert_equal "sfo", ukc.instances.create(image: "nginx:latest", metros: :sfo).metro + sin = client(metro: :sin, metros: :all) { instance } + + assert_equal "sin", sin.instances.create(image: "x").metro + assert_equal "fra", ukc.metros(:dal, :fra).instances.create(image: "x").metro + # Only the default metro is a fallback; elsewhere is refused. + err = assert_raises(Unikraft::Cloud::Error) do + ukc.metros(:sin, :dal).instances.create(image: "nginx:latest") + end + + assert_equal :config, err.kind + assert_match(/targets a single metro/, err.message) + end + + # --- handles ----------------------------------------------------------- + + def test_one_request_when_the_metro_is_known + ukc = client(metro: :fra) { instance(state: "standby") } + suspended = ukc.instances.get(name: "web").suspend + + assert_equal 1, @cloud.calls.size + assert_equal %w[PUT], @cloud.verbs + assert_equal ["/v1/instances/suspend"], @cloud.paths + assert_equal [{ "name" => "web" }], @cloud.calls.first.body + assert_equal "fra", suspended.metro + assert_kind_of Unikraft::Cloud::Resources::InstanceHandle, suspended + end + + def test_chained_steps_run_once_and_in_order + ukc = client(metro: :fra) do |call| + next ok(instances: [{ uuid: "u1", state: "running" }]) if call.path == "/v1/instances/wait" + next ok(instances: [{ output: "aGk=" }]) if call.path == "/v1/instances/log" + + instance + end + logs = ukc.instances.create(image: "nginx:latest").wait(state: :running).logs(offset: -1024) + + assert_equal "aGk=", logs.output + assert_equal %w[/v1/instances /v1/instances/wait /v1/instances/log], @cloud.paths + # The created instance is addressed by its uuid from then on. + assert_equal({ "uuid" => "u1", "state" => "running" }, @cloud.calls[1].params) + end + + def test_history_raises_a_failed_entry + ukc = client(metro: :fra) do + { status: "partial_success", data: { instances: [{ status: "error", error: 8 }] } } + end + err = assert_raises(Unikraft::Cloud::Error) { ukc.instances.history(name: "web") } + + assert_equal 404, err.status + end + + def test_reload_keeps_the_read_options_of_get + ukc = client(metro: :fra) { instance } + web = ukc.instances.get(name: "web", timeout: 5) + web.reload + web.reload(timeout: 7) + + assert_equal([5, 7], @cloud.calls.map { |c| c.options[:timeout] }) + end + + def test_a_handle_memoizes_and_reloads + ukc = client(metro: :fra) { instance } + web = ukc.instances.get(name: "web") + web.name + web.to_h + + assert_equal 1, @cloud.calls.size + assert_same web, web.reload + assert_equal 2, @cloud.calls.size + end + + def test_location_and_inspect + ukc = client(metro: :dal) { instance } + web = ukc.instances.get(name: "web") + + assert_match(/name "web" \(not loaded\)/, web.inspect) + assert_equal "dal", web.metro + assert_equal "https://api.dal.unikraft.cloud", web.location.base_url + assert_equal({ name: "web" }, web.resolve.ref.wire) + assert_empty @cloud.calls + web.model + + assert_match(/state=|name="web"/, web.inspect) + end + + def test_extra_fields_of_a_mutation_result_are_readable + ukc = client(metro: :fra) { instance(state: "standby", previous_state: "running") } + suspended = ukc.instances.get(name: "web").suspend + + assert_equal "running", suspended[:previous_state] + assert_respond_to suspended, :state + assert_pattern { suspended => { state: "standby", metro: "fra" } } + end + + def test_an_attribute_missing_from_a_mutation_reply_is_read_once + ukc = client(metro: :fra) do |call| + next ok(instances: [{ uuid: "u1", name: "web" }]) if call.verb == "PATCH" + + instance(state: "running", memory_mb: 512) + end + updated = ukc.instances.update(name: "web", memory_mb: 512) + + assert_predicate updated, :running? + assert_equal 512, updated.memory_mb + assert_nil updated.vcpus + assert_equal %w[PATCH GET], @cloud.verbs + end + + # --- a name in several metros ----------------------------------------- + + def test_get_reports_ambiguity_with_the_matches + ukc = everywhere(%i[fra dal sin]) + err = assert_raises(Unikraft::Cloud::AmbiguousRefError) { ukc.instances.get(name: "web").suspend } + + assert_equal %w[dal fra sin], err.metros.sort + assert_equal %w[u-dal u-fra u-sin], err.matches.map(&:uuid).sort + assert_includes err.message, "metro: :" + assert_equal 0, @cloud.paths.count("/v1/instances/suspend") + end + + def test_get_refuses_a_match_while_another_metro_is_unreachable + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + next FakeCloud.failure(503) if call.metro == "dal" + + ok(instances: [{ uuid: "u-#{call.metro}", name: "web" }]) + end + err = assert_raises(Unikraft::Cloud::MetroFanoutError) { ukc.instances.get(name: "web").suspend } + + assert_equal ["fra"], err.results.map(&:metro) + assert_equal(["dal"], err.failures.map { |f| f[:metro] }) + assert_equal 0, @cloud.paths.count("/v1/instances/suspend") + end + + def test_a_failed_lookup_entry_counts_as_absent + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + next ok(instances: [{ uuid: "u-fra", name: "web" }]) if call.metro == "fra" + + { status: "partial_success", data: { instances: [{ status: "error", error: 8 }] } } + end + + assert_equal "fra", ukc.instances.get(name: "web").metro + end + + def test_a_uuid_in_several_metros_is_ambiguous_too + ukc = everywhere(%i[fra dal]) + err = assert_raises(Unikraft::Cloud::AmbiguousRefError) { ukc.instances.get(uuid: "u").metro } + + assert_equal %w[dal fra], err.metros.sort + assert_includes err.message, 'get(uuid: "u", metro: :' + end + + def test_a_qualified_ref_needs_no_lookup + ukc = everywhere(%i[fra dal sin]) + suspended = ukc.instances.get(name: "web", metro: :dal).suspend + + assert_equal "dal", suspended.metro + assert_equal ["https://api.dal.unikraft.cloud/v1/instances/suspend"], @cloud.calls.map(&:url) + assert_equal [{ "name" => "web" }], @cloud.calls.first.body + end + + def test_where_acts_on_every_match + ukc = everywhere(%i[fra dal sin]) + results = ukc.instances.where(name: "web").suspend + + assert_equal %w[dal fra sin], results.map(&:metro).sort + assert_equal 3, @cloud.paths.count("/v1/instances/suspend") + end + + def test_where_is_enumerable_and_located_once + ukc = everywhere(%i[fra dal]) + web = ukc.instances.where(name: "web") + + assert_equal 2, web.size + assert_equal %w[dal fra], web.metros.sort + assert_equal %w[u-dal u-fra], web.map(&:uuid).sort + assert_equal 1, @cloud.paths.count("/v1/metros") + assert_equal 2, @cloud.paths.count("/v1/instances") + end + + def test_where_applies_a_staged_edit_everywhere + ukc = everywhere(%i[fra dal]) + ukc.instances.where(name: "web").edit.set(memory_mb: 512).apply + patches = @cloud.calls.select { |c| c.verb == "PATCH" } + + assert_equal 2, patches.size + assert_equal [{ "name" => "web", "prop" => "memory_mb", "op" => "set", "value" => 512 }], + patches.first.body + end + + def test_where_keeps_the_successes_on_partial_failure + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + next FakeCloud.failure(503) if call.path.end_with?("suspend") && call.metro == "dal" + + ok(instances: [{ uuid: "u-#{call.metro}", name: "web" }]) + end + err = assert_raises(Unikraft::Cloud::MetroFanoutError) { ukc.instances.where(name: "web").suspend } + + assert_equal(["dal"], err.failures.map { |f| f[:metro] }) + assert_equal ["fra"], err.results.map(&:metro) + end + + def test_where_with_one_metro_needs_no_lookup + ukc = everywhere(%i[fra dal], metro: :fra) + ukc.instances.where(name: "web").suspend + + assert_equal ["https://api.fra.unikraft.cloud/v1/instances/suspend"], @cloud.calls.map(&:url) + end + + # --- updating ------------------------------------------------------------ + + def body = @cloud.calls.first.body + + def test_update_infers_set_and_nil_removes + ukc = client(metro: :fra) { instance } + ukc.instances.get(name: "web").update(memory_mb: 512, tags: nil) + + assert_equal "PATCH", @cloud.calls.first.verb + assert_equal [{ "name" => "web", "prop" => "memory_mb", "op" => "set", "value" => 512 }, + { "name" => "web", "prop" => "tags", "op" => "del" }], body + end + + def test_update_accepts_raw_triples_and_the_shorthand + ukc = client(metro: :fra) { instance } + ukc.instances.update({ name: "web" }, [{ prop: "memory_mb", op: "set", value: 512 }]) + ukc.instances.update(name: "web", image: { url: "nginx:1.27" }) + + assert_equal [{ "name" => "web", "prop" => "memory_mb", "op" => "set", "value" => 512 }], body + assert_equal [{ "name" => "web", "prop" => "image", "op" => "set", + "value" => { "url" => "nginx:1.27" } }], @cloud.calls.last.body + end + + def test_update_keywords_never_patch_call_options + ukc = client(metro: :fra) { instance } + ukc.instances.update(name: "web", memory_mb: 512, timeout: 10, headers: { "X-A" => "1" }) + ukc.instances.get(name: "web").update(vcpus: 2, timeout: 5) + + assert_equal [{ "name" => "web", "prop" => "memory_mb", "op" => "set", "value" => 512 }], + @cloud.calls[0].body + assert_equal({ timeout: 10, headers: { "X-A" => "1" } }, + @cloud.calls[0].options.except(:base_url)) + assert_equal 5, @cloud.calls[1].options[:timeout] + assert_equal 1, @cloud.calls[1].body.size + end + + def test_edit_chains_or_takes_a_block + ukc = client(metro: :fra) { instance } + updated = ukc.instances.get(name: "web").edit + .set(memory_mb: 512) + .add(env: { LOG_LEVEL: "debug" }, tags: ["prod"]) + .remove(env: ["OLD_FLAG"], schedules: nil) + .apply + ukc.instances.edit(name: "web") { |e| e.set(vcpus: 2) } + + assert_equal "fra", updated.metro + assert_equal [ + { "name" => "web", "prop" => "memory_mb", "op" => "set", "value" => 512 }, + { "name" => "web", "prop" => "env", "op" => "add", "value" => { "LOG_LEVEL" => "debug" } }, + { "name" => "web", "prop" => "tags", "op" => "add", "value" => ["prod"] }, + { "name" => "web", "prop" => "env", "op" => "del", "value" => ["OLD_FLAG"] }, + { "name" => "web", "prop" => "schedules", "op" => "del" } + ], body + assert_equal [{ "name" => "web", "prop" => "vcpus", "op" => "set", "value" => 2 }], + @cloud.calls.last.body + assert_raises(ArgumentError) { ukc.instances.edit(name: "web").apply } + end + + def test_chaining_continues_after_an_edit + ukc = client(metro: :fra) { instance(state: "running") } + ukc.instances.edit(name: "web").set(memory_mb: 512).apply.wait + + assert_equal %w[/v1/instances /v1/instances/wait], @cloud.paths + end + + def test_an_edit_goes_to_the_metro_holding_the_instance + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + next web_in("dal", call) if call.verb == "GET" + + instance + end + ukc.instances.get(name: "web").edit { |e| e.add(tags: ["prod"]) } + + patches = @cloud.calls.select { |c| c.verb == "PATCH" } + + assert_equal ["api.dal.unikraft.cloud"], patches.map(&:host) + end + + def test_the_client_is_shared_across_threads + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + + ok(instances: [{ uuid: "u-#{call.metro}" }]) + end + counts = Array.new(8) { Thread.new { ukc.instances.count } }.map(&:value) + + assert_equal [2], counts.uniq + assert_equal 1, @cloud.paths.count("/v1/metros") + end +end From 59793e99a093d7a0055218c3e6dc687f2edcd724 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:16:34 -0800 Subject: [PATCH 24/30] feat(volumes): Add the idiomatic volumes client ukc.volumes shares the collection verbs and adds attach and detach, on a handle, as shorthands, and across every match of where. Their keywords are the API's own (attach_to:, at:, readonly:, from:); the instance ref in attach_to: or from: may be a Hash or a Ref, and only its identifier reaches the wire. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/client.rb | 3 + lib/unikraft/cloud/resources/volumes.rb | 93 +++++++++++++++++++++++++ test/unit/volumes_test.rb | 78 +++++++++++++++++++++ 4 files changed, 175 insertions(+) create mode 100644 lib/unikraft/cloud/resources/volumes.rb create mode 100644 test/unit/volumes_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 2060725..8143f14 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -22,4 +22,5 @@ require_relative "cloud/core/handle_set" require_relative "cloud/core/resource" require_relative "cloud/resources/instances" +require_relative "cloud/resources/volumes" require_relative "cloud/client" diff --git a/lib/unikraft/cloud/client.rb b/lib/unikraft/cloud/client.rb index fb76aa5..6bf3343 100644 --- a/lib/unikraft/cloud/client.rb +++ b/lib/unikraft/cloud/client.rb @@ -20,6 +20,8 @@ class Scope attr_reader :scope # @return [Resources::Instances] instances (microVMs) attr_reader :instances + # @return [Resources::Volumes] persistent volumes + attr_reader :volumes # @api private def initialize(session, scope, transport = session.transport) @@ -27,6 +29,7 @@ def initialize(session, scope, transport = session.transport) @scope = scope @transport = transport @instances = Resources::Instances.new(session, scope, transport) + @volumes = Resources::Volumes.new(session, scope, transport) end def inspect = "#<#{self.class.name} scope=#{@scope.inspect}>" diff --git a/lib/unikraft/cloud/resources/volumes.rb b/lib/unikraft/cloud/resources/volumes.rb new file mode 100644 index 0000000..6d023a8 --- /dev/null +++ b/lib/unikraft/cloud/resources/volumes.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "../core/resource" +require_relative "../api/platform" + +module Unikraft + module Cloud + module Resources + # A handle on one volume (see {Core::Handle}). + # + # @example + # ukc.volumes.get(name: "data").attach(attach_to: { name: "web" }, at: "/data") + class VolumeHandle < Core::Handle + # Attach the volume to an instance. + # + # @param spec [Hash] the attachment, with the API's keys: + # `attach_to:` (an instance ref), `at:` (the mount point), + # `readonly:`; plus `headers:`/`timeout:` for the call + # @return [VolumeHandle] carrying what the endpoint reported + def attach(**spec) = volume_op(:attach_volumes, :attach_to, spec) + + # Detach the volume, from every instance or, with `from:` (an + # instance ref), one. + # + # @return [VolumeHandle] + def detach(**spec) = volume_op(:detach_volumes, :from, spec) + + attributes_of API::Platform::Models::Volume + + private + + # Send the operation with its instance ref as the wire carries it: + # the identifier alone, whatever form the ref was given in. + def volume_op(operation, key, spec) + call = spec.slice(:headers, :timeout) + body = wire(call).merge(spec.except(*call.keys)) + body[key] = same_metro(Core::Ref.coerce(body[key])).wire if body[key] + mutate(operation, [body], **call) + end + + # The wire drops the instance's metro, so one elsewhere would name + # a different instance in this volume's metro. A URL metro matches + # by its normalized base URL (`/v1` or not). + def same_metro(ref) + return ref if ref.metro.nil? || ref.metro == metro + return ref if Core::Metro.url?(ref.metro) && + Core::Metro.base_url(ref.metro) == location.base_url + + raise ArgumentError, "instance #{ref} is not in this volume's metro (#{metro})" + end + end + + # Every volume matching one ref, one per metro. + class VolumeSet < Core::HandleSet + forward :attach, :detach + end + + # Persistent volumes. Enumerable over every volume in scope. + # + # @example + # ukc.metro(:fra).volumes.create(name: "data", size_mb: 1024) + # ukc.volumes.update(name: "data", size_mb: 2048) + class Volumes < Core::Resource + API_CLASS = API::Platform::VolumesApi + HANDLE = VolumeHandle + SET = VolumeSet + SPEC = Spec.new(noun: "volume", key: :volumes, list: :get_volumes, + create: :create_volume, delete: :delete_volumes, + update: :update_volumes) + + # Shorthand for `get(ref).attach(...)`. + # + # @example + # ukc.volumes.attach(name: "data", attach_to: { name: "web" }, at: "/data") + # @return [VolumeHandle] + def attach(ref = nil, **kwargs) + handle, spec = on(ref, kwargs) + handle.attach(**spec) + end + + # Shorthand for `get(ref).detach(...)`. + # @return [VolumeHandle] + def detach(ref = nil, **kwargs) + handle, spec = on(ref, kwargs) + handle.detach(**spec) + end + end + end + end +end diff --git a/test/unit/volumes_test.rb b/test/unit/volumes_test.rb new file mode 100644 index 0000000..c40ac2d --- /dev/null +++ b/test/unit/volumes_test.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/fake_cloud" + +class VolumesTest < Minitest::Test + include FakeCloud::Helpers + + def volume = ok(volumes: [{ uuid: "v1", name: "data", size_mb: 1024 }]) + + def test_attach_chains_off_a_get_in_one_request + ukc = client(metro: :fra) { volume } + ukc.volumes.get(name: "data").attach(attach_to: { name: "web" }, at: "/data") + + assert_equal ["/v1/volumes/attach"], @cloud.paths + assert_equal [{ "name" => "data", "attach_to" => { "name" => "web" }, "at" => "/data" }], + @cloud.calls.first.body + end + + def test_detach_shorthand + ukc = client(metro: :fra) { volume } + ukc.volumes.detach(name: "data", from: { name: "web" }, timeout: 5) + + assert_equal [{ "name" => "data", "from" => { "name" => "web" } }], @cloud.calls.first.body + assert_equal 5, @cloud.calls.first.options[:timeout] + end + + def test_instance_refs_reach_the_wire_as_identifiers + ukc = client(metro: :fra) { volume } + ref = Unikraft::Cloud::Core::Ref.new(uuid: "i1", metro: :fra) + ukc.volumes.get(name: "data").attach(attach_to: ref, at: "/data") + ukc.volumes.detach(name: "data", from: { "name" => "web", "metro" => "fra" }) + + assert_equal({ "uuid" => "i1" }, @cloud.calls[0].body.first["attach_to"]) + assert_equal({ "name" => "web" }, @cloud.calls[1].body.first["from"]) + end + + def test_a_url_metro_matches_with_or_without_v1 + url = "https://api.staging.internal/v1" + ukc = client(metro: url) { volume } + ukc.volumes.get(name: "data").attach(attach_to: { name: "web", metro: url }, at: "/d") + + assert_equal({ "name" => "web" }, @cloud.calls.first.body.first["attach_to"]) + end + + def test_an_instance_in_another_metro_is_refused + ukc = client(metro: :fra) { volume } + data = ukc.volumes.get(name: "data") + + assert_raises(ArgumentError) { data.attach(attach_to: { name: "web", metro: :dal }, at: "/d") } + assert_raises(ArgumentError) { data.detach(from: { name: "web", metro: :dal }) } + assert_empty @cloud.calls + end + + def test_update_and_attributes + ukc = client(metro: :fra) { volume } + ukc.volumes.get(name: "data").update(size_mb: 2048) + + assert_equal [{ "name" => "data", "prop" => "size_mb", "op" => "set", "value" => 2048 }], + @cloud.calls.first.body + assert_equal 1024, ukc.volumes.get(name: "data").size_mb + end + + def test_a_qualified_ref_goes_straight_to_its_metro + ukc = client { volume } + ukc.volumes.get(name: "data", metro: :sin).update(size_mb: 4096) + + assert_equal ["api.sin.unikraft.cloud"], @cloud.calls.map(&:host) + refute @cloud.calls.first.body.first.key?("metro") + end + + def test_list_and_where + ukc = everywhere(%i[fra dal], key: :volumes) + + assert_equal %w[dal fra], ukc.volumes.map(&:metro).sort + assert_equal 2, ukc.volumes.where(name: "web").detach.size + end +end From b3f794b0cad982df091926d9a726d63136b60b38 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:17:00 -0800 Subject: [PATCH 25/30] feat(services): Add the idiomatic service groups client ukc.services covers service groups with the shared verbs: create, get, where, list, update, edit and delete, each handle reading the group's attributes lazily. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/client.rb | 4 ++ .../cloud/resources/service_groups.rb | 36 +++++++++++++++ test/unit/service_groups_test.rb | 44 +++++++++++++++++++ 4 files changed, 85 insertions(+) create mode 100644 lib/unikraft/cloud/resources/service_groups.rb create mode 100644 test/unit/service_groups_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 8143f14..238462b 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -23,4 +23,5 @@ require_relative "cloud/core/resource" require_relative "cloud/resources/instances" require_relative "cloud/resources/volumes" +require_relative "cloud/resources/service_groups" require_relative "cloud/client" diff --git a/lib/unikraft/cloud/client.rb b/lib/unikraft/cloud/client.rb index 6bf3343..c8254c3 100644 --- a/lib/unikraft/cloud/client.rb +++ b/lib/unikraft/cloud/client.rb @@ -22,6 +22,9 @@ class Scope attr_reader :instances # @return [Resources::Volumes] persistent volumes attr_reader :volumes + # @return [Resources::ServiceGroups] service groups (load-balanced + # networking) + attr_reader :services # @api private def initialize(session, scope, transport = session.transport) @@ -30,6 +33,7 @@ def initialize(session, scope, transport = session.transport) @transport = transport @instances = Resources::Instances.new(session, scope, transport) @volumes = Resources::Volumes.new(session, scope, transport) + @services = Resources::ServiceGroups.new(session, scope, transport) end def inspect = "#<#{self.class.name} scope=#{@scope.inspect}>" diff --git a/lib/unikraft/cloud/resources/service_groups.rb b/lib/unikraft/cloud/resources/service_groups.rb new file mode 100644 index 0000000..878379e --- /dev/null +++ b/lib/unikraft/cloud/resources/service_groups.rb @@ -0,0 +1,36 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "../core/resource" +require_relative "../api/platform" + +module Unikraft + module Cloud + module Resources + # A handle on one service group (see {Core::Handle}): `update`, `edit` + # and `delete`. + # + # @example + # ukc.services.get(name: "web").update(soft_limit: 5, hard_limit: 20) + # ukc.services.edit(name: "web") { |e| e.remove(domains: nil) } + class ServiceGroupHandle < Core::Handle + attributes_of API::Platform::Models::ServiceGroup + end + + # Every service group matching one ref, one per metro. + class ServiceGroupSet < Core::HandleSet; end + + # Service groups (load-balanced networking), as `ukc.services`. + class ServiceGroups < Core::Resource + API_CLASS = API::Platform::ServicesApi + HANDLE = ServiceGroupHandle + SET = ServiceGroupSet + SPEC = Spec.new(noun: "service group", key: :service_groups, list: :get_service_groups, + create: :create_service_group, delete: :delete_service_groups, + update: :update_service_groups) + end + end + end +end diff --git a/test/unit/service_groups_test.rb b/test/unit/service_groups_test.rb new file mode 100644 index 0000000..9193365 --- /dev/null +++ b/test/unit/service_groups_test.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/fake_cloud" + +class ServiceGroupsTest < Minitest::Test + include FakeCloud::Helpers + + def group = ok(service_groups: [{ uuid: "sg1", name: "web", hard_limit: 10 }]) + + def test_edit_and_update + ukc = client(metro: :fra) { group } + ukc.services.get(name: "web").edit.set(hard_limit: 20).apply + ukc.services.edit(name: "web") { |e| e.remove(domains: nil) } + + assert_equal %w[/v1/services /v1/services], @cloud.paths + assert_equal [{ "name" => "web", "prop" => "hard_limit", "op" => "set", "value" => 20 }], + @cloud.calls[0].body + assert_equal [{ "name" => "web", "prop" => "domains", "op" => "del" }], @cloud.calls[1].body + end + + def test_delete_goes_to_the_qualified_metro + ukc = client { group } + ukc.services.get(name: "web", metro: :was).delete + + assert_equal ["https://api.was.unikraft.cloud/v1/services"], @cloud.calls.map(&:url) + assert_equal %w[DELETE], @cloud.verbs + assert_equal [{ "name" => "web" }], @cloud.calls.first.body + end + + def test_reads_and_creates + ukc = client(metro: :fra) { group } + + assert_equal 10, ukc.services.get(name: "web").hard_limit + assert_equal "fra", ukc.services.create(name: "web", services: []).metro + assert_equal "POST", @cloud.verbs.last + end + + def test_list_refuses_tags_it_cannot_filter_by + ukc = client { flunk "no request expected" } + + assert_raises(ArgumentError) { ukc.services.list(tags: ["prod"]) } + end +end From 8e6308305776bcabf096b547ec82f93af95e70e7 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:17:32 -0800 Subject: [PATCH 26/30] feat(certificates): Add the idiomatic certificates client ukc.certificates shares the collection verbs. A certificate is replaced rather than patched, so update takes the new chain: and pkey:, on a handle, as a shorthand and across a where, and there is no edit. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/client.rb | 3 ++ lib/unikraft/cloud/resources/certificates.rb | 57 ++++++++++++++++++++ test/unit/certificates_test.rb | 47 ++++++++++++++++ 4 files changed, 108 insertions(+) create mode 100644 lib/unikraft/cloud/resources/certificates.rb create mode 100644 test/unit/certificates_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index 238462b..b0113e3 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -24,4 +24,5 @@ require_relative "cloud/resources/instances" require_relative "cloud/resources/volumes" require_relative "cloud/resources/service_groups" +require_relative "cloud/resources/certificates" require_relative "cloud/client" diff --git a/lib/unikraft/cloud/client.rb b/lib/unikraft/cloud/client.rb index c8254c3..b794b3e 100644 --- a/lib/unikraft/cloud/client.rb +++ b/lib/unikraft/cloud/client.rb @@ -25,6 +25,8 @@ class Scope # @return [Resources::ServiceGroups] service groups (load-balanced # networking) attr_reader :services + # @return [Resources::Certificates] TLS certificates + attr_reader :certificates # @api private def initialize(session, scope, transport = session.transport) @@ -34,6 +36,7 @@ def initialize(session, scope, transport = session.transport) @instances = Resources::Instances.new(session, scope, transport) @volumes = Resources::Volumes.new(session, scope, transport) @services = Resources::ServiceGroups.new(session, scope, transport) + @certificates = Resources::Certificates.new(session, scope, transport) end def inspect = "#<#{self.class.name} scope=#{@scope.inspect}>" diff --git a/lib/unikraft/cloud/resources/certificates.rb b/lib/unikraft/cloud/resources/certificates.rb new file mode 100644 index 0000000..902b95d --- /dev/null +++ b/lib/unikraft/cloud/resources/certificates.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "../core/resource" +require_relative "../api/platform" + +module Unikraft + module Cloud + module Resources + # A handle on one certificate (see {Core::Handle}). A certificate is + # replaced rather than patched, so `update` takes the new `chain:` and + # `pkey:`, and there is no `edit`. + class CertificateHandle < Core::Handle + undef_method :edit + + # Replace the certificate chain and private key. + # + # @example + # ukc.certificates.get(name: "star").update(chain: pem, pkey: key) + # @param spec [Hash] `chain:`, `pkey:`; plus `headers:`/`timeout:` + # @return [CertificateHandle] + def update(**spec) + call = spec.slice(:headers, :timeout) + mutate(@resource.spec.update, [wire(call).merge(spec.except(*call.keys))], **call) + end + + attributes_of API::Platform::Models::Certificate + end + + # Every certificate matching one ref, one per metro. + class CertificateSet < Core::HandleSet + undef_method :edit + end + + # TLS certificates. + class Certificates < Core::Resource + API_CLASS = API::Platform::CertificatesApi + HANDLE = CertificateHandle + SET = CertificateSet + SPEC = Spec.new(noun: "certificate", key: :certificates, list: :get_certificates, + create: :create_certificate, delete: :delete_certificates, + update: :update_certificates) + + undef_method :edit + + # Shorthand for `get(ref).update(chain:, pkey:)`. + # @return [CertificateHandle] + def update(ref = nil, **kwargs) + handle, spec = on(ref, kwargs) + handle.update(**spec) + end + end + end + end +end diff --git a/test/unit/certificates_test.rb b/test/unit/certificates_test.rb new file mode 100644 index 0000000..a9d3acb --- /dev/null +++ b/test/unit/certificates_test.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/fake_cloud" + +class CertificatesTest < Minitest::Test + include FakeCloud::Helpers + + def cert = ok(certificates: [{ uuid: "c1", name: "star", common_name: "*.example.com" }]) + + def test_update_replaces_chain_and_key + ukc = client(metro: :fra) { cert } + ukc.certificates.update(name: "star", chain: "PEM", pkey: "KEY") + + assert_equal ["/v1/certificates"], @cloud.paths + assert_equal %w[PUT], @cloud.verbs + assert_equal [{ "name" => "star", "chain" => "PEM", "pkey" => "KEY" }], @cloud.calls.first.body + refute_respond_to ukc.certificates.get(name: "star"), :edit + end + + def test_inspect_redacts_the_private_key + ukc = client(metro: :fra) { ok(certificates: [{ name: "star", pkey: "KEY" }]) } + handle = ukc.certificates.get(name: "star") + handle.model + + [handle.inspect, handle.model.inspect, handle.to_s].each do |s| + refute_includes s, "KEY" + assert_includes s, "pkey=[REDACTED]" + end + end + + def test_inspect_redacts_nested_untyped_secrets + model = Unikraft::Cloud::Model.new(config: { "registry" => [{ "token" => "TOK" }] }) + + refute_includes model.inspect, "TOK" + assert_match(/"token" ?=> ?\[REDACTED\]/, model.inspect) # spacing differs before 3.4 + refute_includes Unikraft::Cloud::Model.new(headers: { "Authorization" => "B" }).inspect, '"B"' + end + + def test_delete_and_read + ukc = client { cert } + ukc.certificates.get(name: "star", metro: :sfo).delete + + assert_equal ["https://api.sfo.unikraft.cloud/v1/certificates"], @cloud.calls.map(&:url) + assert_equal "*.example.com", ukc.certificates.get(name: "star", metro: :fra).common_name + end +end From 4bfafbcf63b53a5e62c5ec67a2825e9285dea9a6 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:18:00 -0800 Subject: [PATCH 27/30] feat(users): Add quotas to the idiomatic client ukc.users.quotas reads the user's quotas (or, with uuid:, another user's) in every metro in scope, tags each with its metro, and keeps the successes on a MetroFanoutError when some metros fail. Signed-off-by: Alexander Jung --- lib/unikraft/cloud.rb | 1 + lib/unikraft/cloud/client.rb | 3 ++ lib/unikraft/cloud/resources/users.rb | 39 ++++++++++++++++++++++++++ test/unit/users_test.rb | 40 +++++++++++++++++++++++++++ 4 files changed, 83 insertions(+) create mode 100644 lib/unikraft/cloud/resources/users.rb create mode 100644 test/unit/users_test.rb diff --git a/lib/unikraft/cloud.rb b/lib/unikraft/cloud.rb index b0113e3..ff243f4 100644 --- a/lib/unikraft/cloud.rb +++ b/lib/unikraft/cloud.rb @@ -25,4 +25,5 @@ require_relative "cloud/resources/volumes" require_relative "cloud/resources/service_groups" require_relative "cloud/resources/certificates" +require_relative "cloud/resources/users" require_relative "cloud/client" diff --git a/lib/unikraft/cloud/client.rb b/lib/unikraft/cloud/client.rb index b794b3e..68ede2b 100644 --- a/lib/unikraft/cloud/client.rb +++ b/lib/unikraft/cloud/client.rb @@ -27,6 +27,8 @@ class Scope attr_reader :services # @return [Resources::Certificates] TLS certificates attr_reader :certificates + # @return [Resources::Users] users and quotas + attr_reader :users # @api private def initialize(session, scope, transport = session.transport) @@ -37,6 +39,7 @@ def initialize(session, scope, transport = session.transport) @volumes = Resources::Volumes.new(session, scope, transport) @services = Resources::ServiceGroups.new(session, scope, transport) @certificates = Resources::Certificates.new(session, scope, transport) + @users = Resources::Users.new(session, scope, transport) end def inspect = "#<#{self.class.name} scope=#{@scope.inspect}>" diff --git a/lib/unikraft/cloud/resources/users.rb b/lib/unikraft/cloud/resources/users.rb new file mode 100644 index 0000000..9f5bc77 --- /dev/null +++ b/lib/unikraft/cloud/resources/users.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. + +require_relative "../core/resource" +require_relative "../api/platform" + +module Unikraft + module Cloud + module Resources + # Users and quotas. Quotas are per metro, so reading them fans out + # across the scope and tags each entry with its metro. + class Users < Core::Scoped + API_CLASS = API::Platform::UsersApi + + # The quotas of the authenticated user, or of the user `uuid`, in + # every metro in scope. + # + # @example + # ukc.users.quotas.each { |q| puts "#{q.metro} #{q.used.inspect}" } + # @param uuid [String, nil] + # @param opts [Hash] `metros:`, `base_url:`, `headers:`, `timeout:` + # @return [Array] + def quotas(uuid: nil, **opts) + endpoints = endpoints(check_options!(opts)) + read = lambda do |endpoint| + call = call_options(endpoint, opts) + res = uuid ? api.get_user_by_uuid(uuid:, **call) : api.get_user(**call) + Core::Response.list(res, :quotas).map { |q| q.with_metro(endpoint.metro) } + end + return read.call(endpoints.first) if endpoints.size == 1 + + Core::Fanout.all(endpoints, flat: true, &read) + end + end + end + end +end diff --git a/test/unit/users_test.rb b/test/unit/users_test.rb new file mode 100644 index 0000000..29d8b92 --- /dev/null +++ b/test/unit/users_test.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +require_relative "../test_helper" +require_relative "../support/fake_cloud" + +class UsersTest < Minitest::Test + include FakeCloud::Helpers + + def test_quotas_are_tagged_with_their_metro + ukc = client(metro: :fra) { ok(quotas: [{ uuid: "q1" }]) } + quotas = ukc.users.quotas + + assert_equal([%w[q1 fra]], quotas.map { |q| [q.uuid, q.metro] }) + assert_equal "/v1/users/quotas", @cloud.paths.last + ukc.users.quotas(uuid: "u1") + + assert_equal "/v1/users/u1/quotas", @cloud.paths.last + end + + def test_quotas_merge_every_metro + ukc = client do |call| + next FakeCloud.metros(:fra, :dal) if call.path == "/v1/metros" + + ok(quotas: [{ uuid: "q-#{call.metro}" }]) + end + + assert_equal %w[dal:q-dal fra:q-fra], ukc.users.quotas.map { |q| "#{q.metro}:#{q.uuid}" }.sort + end + + def test_quotas_report_failed_metros + ukc = client do |call| + next FakeCloud.failure(503) if call.metro == "dal" + + ok(quotas: [{ uuid: "q" }]) + end + err = assert_raises(Unikraft::Cloud::MetroFanoutError) { ukc.users.quotas(metros: %i[fra dal]) } + + assert_equal ["fra"], err.results.map(&:metro) + end +end From fd0b994d194d79f6c92f031a4d76feba71d444e8 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:18:36 -0800 Subject: [PATCH 28/30] test: Add live end-to-end tests for the porcelain test/e2e/live_test.rb runs under rake test:e2e against the account in UKC_TOKEN and the deployment in UKC_METRO (the internal staging one by default, as in the JS SDK): it lists across the scope, reads quotas, and takes an instance through create, wait, logs, get, update and reload before deleting it. Signed-off-by: Alexander Jung --- test/e2e/live_test.rb | 64 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 test/e2e/live_test.rb diff --git a/test/e2e/live_test.rb b/test/e2e/live_test.rb new file mode 100644 index 0000000..1e29358 --- /dev/null +++ b/test/e2e/live_test.rb @@ -0,0 +1,64 @@ +# frozen_string_literal: true + +# The porcelain against a live account. Run with `bundle exec rake test:e2e`; +# it needs UKC_TOKEN. UKC_METRO picks the deployment (a metro code or a URL; +# the internal staging deployment by default) and UKC_E2E_IMAGE the image. + +require_relative "../test_helper" +require "English" +require "securerandom" + +class LiveTest < Minitest::Test + # Tracks the prod-staging platform branch, where a platform fix can be + # checked before the OpenAPI specification catches up with it. + METRO = "http://api.ukp-staging.apw.unikraft.internal" + IMAGE = "nginx:latest" + + def env(name) + value = ENV.fetch(name, nil) + value unless value.nil? || value.empty? + end + + def setup + skip "UKC_TOKEN is missing or empty" unless env("UKC_TOKEN") + @ukc = Unikraft::Cloud.new(metro: env("UKC_METRO") || METRO) + end + + def teardown + @ukc&.close + end + + def test_lists_every_instance_in_scope + instances = @ukc.instances.list.first(5) + + assert(instances.all? { |i| i.metro.is_a?(String) }) + refute_empty @ukc.users.quotas + end + + def test_instance_lifecycle + name = "ruby-sdk-e2e-#{SecureRandom.hex(4)}" + scope = @ukc.metro(@ukc.scope.first) + created = scope.instances.create(name:, image: env("UKC_E2E_IMAGE") || IMAGE, + memory_mb: 256, autostart: true) + running = created.wait(state: :running, within: 60) + + assert_equal "running", running.state + assert_kind_of String, running.logs(offset: -4096).output.to_s + web = scope.instances.get(name:) + + assert_equal created.uuid, web.uuid + assert_predicate web, :running? + web.update(memory_mb: 512) + + assert_equal 512, web.reload.memory_mb + ensure + # Always try: a create can succeed remotely yet raise here (a lost + # reply). Absent is fine, and a cleanup failure never masks the test's. + failure = $ERROR_INFO + begin + scope&.instances&.delete(name:) + rescue Unikraft::Cloud::Error => e + raise unless e.status == 404 || failure + end + end +end From 5f11953c5c49e487ea201d4da2fdbb7556401013 Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:19:30 -0800 Subject: [PATCH 29/30] docs: Add the quickstart, update and plumbing examples Port the JS SDK's examples to Ruby: create in one metro and chain wait and logs off the handle, update with keywords and staged edits in block and chained form, and call the plumbing directly, aiming a call at each discovered metro with base_url:. Signed-off-by: Alexander Jung --- examples/plumbing.rb | 39 +++++++++++++++++++++++++++++++++++ examples/quickstart.rb | 47 ++++++++++++++++++++++++++++++++++++++++++ examples/update.rb | 38 ++++++++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+) create mode 100644 examples/plumbing.rb create mode 100644 examples/quickstart.rb create mode 100644 examples/update.rb diff --git a/examples/plumbing.rb b/examples/plumbing.rb new file mode 100644 index 0000000..218609b --- /dev/null +++ b/examples/plumbing.rb @@ -0,0 +1,39 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# Using the low-level "plumbing" API directly. Every method returns the raw +# response envelope exactly as the OpenAPI specification describes it, and +# each client talks to exactly one metro. Reach for this when you need a field +# or an operation the idiomatic layer does not expose yet. +# +# UKC_TOKEN=... ruby -Ilib examples/plumbing.rb + +require "unikraft/cloud" + +token = ENV.fetch("UKC_TOKEN") + +# Every platform resource behind one transport... +platform = Unikraft::Cloud::API::Platform.new(base_url: "https://api.fra.unikraft.cloud", token:) + +# ...and the control plane, which is global rather than metro-scoped. +controlplane = Unikraft::Cloud::API::ControlPlane.new( + base_url: Unikraft::Cloud::CONTROLPLANE_BASE_URL, token: +) + +res = platform.instances.get_instances(count: 10, details: true) +puts "status: #{res.status}, op_time_us: #{res[:op_time_us]}" +res.data&.instances&.each { |inst| puts "- #{inst.name}" } + +quotas = platform.users.get_user +p quotas.data&.quotas + +# Ask the control plane where the metros are, then aim a single call at one of +# them with a per-call `base_url:`: the fan-out the idiomatic layer does for you. +controlplane.metros.list_metros.data&.metros&.each do |metro| + # Endpoints may end in /v1, which the operation's path already carries. + base_url = Unikraft::Cloud::Core::Metro.base_url(metro.endpoint) + there = platform.instances.get_instances(count: 1, base_url:) + puts "#{metro.iata_code}: #{there.data&.instances&.size || 0} instance(s)" +end diff --git a/examples/quickstart.rb b/examples/quickstart.rb new file mode 100644 index 0000000..1e5d841 --- /dev/null +++ b/examples/quickstart.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# Idiomatic quickstart. Run with: +# UKC_TOKEN=... ruby -Ilib examples/quickstart.rb + +require "unikraft/cloud" + +# The token comes from UKC_TOKEN; `open` closes the client after the block. +Unikraft::Cloud.open do |ukc| + # Creating a resource happens in one metro. Name it, and every operation on + # that scope needs no lookup. + fra = ukc.metro(:fra) + + instance = fra.instances.create( + image: "nginx:latest", + memory_mb: 256, + autostart: true, + service_group: { + services: [{ port: 443, handlers: %w[tls http], destination_port: 80 }] + } + ) + puts "created #{instance.name} (#{instance.uuid}) in #{instance.metro}" + + # Mutations run at once and return a handle, so calls chain: wait for the + # instance to come up, then read the tail of its console log. + logs = instance.wait(state: :running, within: 30).logs(offset: -4096) + puts logs.output.to_s.unpack1("m") + + # Without a metro, the client is account-wide: every metro is asked in + # parallel and the pages are merged as they arrive. + ukc.instances.list(details: true) do |inst| + puts "- #{inst.metro}/#{inst.name}: #{inst.state}" + end + + # A handle resolves to the metro that actually holds the instance, so the + # suspend is sent there and nowhere else. + ukc.instances.get(name: instance.name).suspend + + # Bulk operations take one ref or an Array of them. + fra.instances.delete([{ uuid: instance.uuid }]) +rescue Unikraft::Cloud::Error => e + warn "API error (#{e.status || "?"}): #{e.message}" + exit 1 +end diff --git a/examples/update.rb b/examples/update.rb new file mode 100644 index 0000000..d486e12 --- /dev/null +++ b/examples/update.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026, Unikraft GmbH. +# +# Changing an instance's properties. Run with: +# UKC_TOKEN=... ruby -Ilib examples/update.rb + +require "unikraft/cloud" + +ukc = Unikraft::Cloud.new +web = ukc.metro(:fra).instances.get(name: "web") + +begin + # Keyword arguments: a value sets the property, nil removes it, and + # anything omitted is left alone. One request, whatever you pass. + updated = web.update(memory_mb: 512, vcpus: 2, env: { LOG_LEVEL: "debug" }, autokill: nil) + puts "#{updated.name} in #{updated.metro}: #{updated.status}" + + # When `set` is not what you mean (merge into a property, or remove single + # members), stage the operations and apply them together at the block's end. + web.edit do |e| + e.set(hostname: "web-1") + e.add(env: { FEATURE_X: "1" }, tags: ["prod"]) + e.remove(env: ["LOG_LEVEL"], tags: ["staging"]) + end + + # The chained form: `apply` returns a handle, so the chain continues. + web.edit.set(memory_mb: 1024).apply.wait(state: :running) + + # The raw triples remain available for anything keywords do not cover. + ukc.metro(:fra).instances.update({ name: "web" }, [{ prop: "memory_mb", op: "set", value: 256 }]) +rescue Unikraft::Cloud::Error => e + warn "API error (#{e.status || "?"}): #{e.message}" + exit 1 +ensure + ukc.close +end From 7c9f496ddb5049f38d9c81020e83d7593a28a2ab Mon Sep 17 00:00:00 2001 From: Alexander Jung Date: Tue, 3 Nov 2026 16:21:18 -0800 Subject: [PATCH 30/30] docs: Add the README Port the JS SDK's README to Ruby: installation, quickstart, the client options and its thread-safe, long-lived use with close and Unikraft::Cloud.open, the two layers, metros and the fan-out rules, names across metros, partial failure, lazy Enumerable lists, handles and why mutations run at once, updating and staged edits, refs, the idiomatic methods, errors and waiting, self-hosted deployments, runtime support, proxy debugging through Net::HTTP and SSL_CERT_FILE, contributing and the license. Signed-off-by: Alexander Jung --- README.md | 587 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 587 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..019d79c --- /dev/null +++ b/README.md @@ -0,0 +1,587 @@ +# `unikraft-cloud` + +The official Ruby SDK for the [Unikraft Cloud][ukc] API. + +## Installation + +```sh +gem install unikraft-cloud +``` + +or, with Bundler, in your `Gemfile`: + +```ruby +gem "unikraft-cloud" +``` + +## Quickstart + +```ruby +require "unikraft/cloud" + +ukc = Unikraft::Cloud.new(token: ENV["UKC_TOKEN"]) + +# By default the client is account-wide: every metro is asked in parallel and +# the results are merged, each tagged with the metro it came from. +ukc.instances.list(details: true) do |inst| + puts "#{inst.metro} #{inst.name} #{inst.state}" +end + +# Creating a resource happens in one metro, so name it. +fra = ukc.metro(:fra) +instance = fra.instances.create( + image: "nginx:latest", + autostart: true, + memory_mb: 256, + service_group: { + services: [{ port: 443, handlers: %w[tls http], destination_port: 80 }] + } +) + +# Operations chain off a handle, so a ref is written once. +instance.wait(state: :running) +ukc.instances.get(name: instance.name).suspend +fra.instances.delete(uuid: instance.uuid) +``` + +## Authentication + +Pass a bearer `token:` to `Unikraft::Cloud.new`, or set the `UKC_TOKEN` +environment variable. Create a token in the +[Unikraft Cloud dashboard][dashboard]. + +## The client + +`Unikraft::Cloud.new(**options)` returns a `Unikraft::Cloud::Client`. Every +option is optional: + +| Option | Default | Meaning | +| -------------------- | ------------------------ | -------------------------------------------------------------------------- | +| `token:` | `UKC_TOKEN` | Bearer token. | +| `metro:` | `UKC_METRO` | One metro (`:fra`) or a full `http(s)://` URL. The target of `create`. | +| `metros:` | `:all`, or `[metro]` | The default scope of reads and bulk operations: `:all`, a metro, or a list. | +| `base_url:` | | An explicit platform API URL; overrides `metro:`. | +| `control_plane_url:` | the global control plane | Where metro discovery and `ukc.api.controlplane` go. | +| `headers:` | `{}` | Extra headers sent with every request. | +| `timeout:` | `60` | Seconds per connect and read; `nil` waits without limit. | +| `proxy_from_env:` | `true` | Honour `http_proxy`/`https_proxy`/`no_proxy`. | +| `user_agent:` | `unikraft-cloud-ruby/…` | The `User-Agent` header. | +| `transport:` | | Builds the transport from the transport keywords; see [Runtime support](#runtime-support). | + +The client is thread-safe and meant to be long-lived: build one and share it +across threads, rather than one per request. Metro discovery and connections +are shared by everything that comes from it. `close` closes its connections; +a later call reopens what it needs. For a script, the block form closes the +client for you and returns the block's value: + +```ruby +count = Unikraft::Cloud.open(metro: :fra) do |ukc| + ukc.instances.count +end +``` + +## The two layers: porcelain and plumbing + +The SDK is explicitly two layers, and you choose per call which one you are in: + +| Layer | Where | What you get | +| ------------- | ------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| **Porcelain** | `ukc.instances`, `ukc.volumes`, … | Short verbs, no envelope, auto-pagination, metro fan-out, chainable handles | +| **Plumbing** | `Unikraft::Cloud::API::Platform`, `Unikraft::Cloud::API::ControlPlane` | The OpenAPI specification as written: `operationId` methods, raw envelope, one metro per call | + +The porcelain layer **holds** a plumbing client rather than inheriting from +one, so the two never blur together, and the raw client is always one method +away: + +```ruby +# Porcelain: unwrapped, metro-aware. +inst = ukc.instances.get(name: "web") + +# Plumbing, from the same client and credentials. +res = ukc.api.platform.instances.get_instances(count: 10, details: true) +res.status # => "success" +res.data.instances + +# Plumbing, per resource (the escape hatch for anything not wrapped yet). +ukc.instances.api.get_instance_logs(name: ["web"]) + +# Plumbing, standalone: no porcelain involved. +api = Unikraft::Cloud::API::Platform.new( + base_url: "https://api.fra.unikraft.cloud", token: ENV["UKC_TOKEN"] +) +api.instances.get_instances(count: 10) +``` + +Plumbing clients are metro-scoped by construction: they talk to whatever +`base_url:` names, and a single call can be redirected with `base_url:`. +Fanning out across metros is the porcelain layer's job. + +### Two APIs: platform and control plane + +Both Unikraft Cloud APIs defined by our [OpenAPI][openapi] specification are +wrapped: + +- **Platform**: metro-scoped resources (instances, volumes, services, + certificates, autoscale, images). Wrapped idiomatically at the top level; + raw under `Unikraft::Cloud::API::Platform` and `ukc.api.platform`. +- **Control plane**: the global (non-metro) API for the account, metros, + images and self-hosted nodes. Raw only, under + `Unikraft::Cloud::API::ControlPlane` and `ukc.api.controlplane`. + +```ruby +ukc.api.controlplane.metros.list_metros.data.metros.each do |metro| + puts "#{metro.iata_code} #{metro.endpoint}" +end +``` + +## Metros: one account, many regions + +The platform API is per metro, but an account's instances are spread across +them. The porcelain layer treats **the metros in scope** as one namespace: +reads fan out concurrently and are merged, and every result carries the +`metro` it came from. + +```ruby +ukc = Unikraft::Cloud.new(token: ENV["UKC_TOKEN"]) + +# Every metro the account can reach (discovered once, then cached). +ukc.instances.each { |inst| puts "#{inst.metro} #{inst.name}" } + +# Explicit scopes; these also skip metro discovery entirely. +ukc.metro(:fra).instances.to_a # one metro +ukc.metros(:fra, :dal).instances.to_a # several +ukc.instances.list(metros: %i[fra dal]).to_a # just this call +ukc.instances.list(metros: :all).to_a # back to everything + +# What the account can reach. +ukc.available_metros.each { |m| puts "#{m.metro} #{m.base_url}" } +``` + +Metros are Symbols or Strings, whichever you have. Set the default scope at +construction, too: + +```ruby +Unikraft::Cloud.new # all metros (default) +Unikraft::Cloud.new(metro: :fra) # one metro +Unikraft::Cloud.new(metros: %i[fra dal]) # several +``` + +`UKC_METRO` acts like `metro:`: setting it pins the client to that metro. +With both `metro:` and `metros:`, `metros:` is the scope and `metro:` stays +the target of `create`. + +| Code | Location | +| ----- | ------------------- | +| `fra` | Frankfurt, DE | +| `dal` | Dallas, TX, USA | +| `sin` | Singapore | +| `was` | Washington, DC, USA | +| `sfo` | San Francisco, USA | + +Metro discovery asks the control plane and trusts the endpoint it reports, so +new metros work without an SDK upgrade. `Unikraft::Cloud::KNOWN_METROS` lists +the ones known when this version was published. + +### Rules the fan-out follows + +- **Reads** cover the whole scope. Pages are interleaved in arrival order, so + a slow metro never holds up a fast one, and each metro fetches its next + page only as the last one is used up. Leaving early (`first`, `break`) + stops the metros still in flight. An external enumerator (`next`) left + midway cannot stop them; they stay parked, sending nothing, so prefer + `each`, `first` or `lazy`. +- **A name identifies a resource within a metro.** The same name can exist in + several metros at once, usually because you deployed the same thing + everywhere, so a name plus a wide scope may match more than one resource. + See [Names across metros](#names-across-metros). +- **`create` never fans out.** It needs one metro: `create(metro: :dal, ...)`, + the scope's, or the default metro (`metro:` / `UKC_METRO` / `fra`) when + the scope is wider. A scope of several named metros must include the + default; otherwise `create` raises `kind: :config` rather than guess. +- **Bulk operations are bounded by the scope.** Refs are located first and one + call goes to each metro that matched, so `delete(name: "web")` under a wide + scope deletes every `web` in scope. Narrow the scope or qualify the ref to + act on one. +- **The control plane is global**, so it is unaffected by scope. + +### Names across metros + +Names are scoped to a metro, so the same name can name a different resource +in every metro. Three ways to say what you mean: + +```ruby +# 1. Qualify the ref. No search, no discovery: one request. +ukc.instances.get(name: "web", metro: :fra).suspend + +# 2. Narrow the scope, which qualifies every ref through it. +ukc.metro(:fra).instances.get(name: "web").suspend + +# 3. Address every metro holding it, on purpose. +ukc.instances.where(name: "web").suspend # one result per metro +``` + +`uuid:` refs rarely need qualifying: a UUID identifies one resource wherever +it lives. + +`get` insists on exactly one match, because the next thing you write might be +a mutation. When a ref matches in several metros it raises an +`AmbiguousRefError` carrying the matches, so recovering costs no further +requests: + +```ruby +begin + ukc.instances.get(name: "web").suspend +rescue Unikraft::Cloud::AmbiguousRefError => e + e.metros # => ["fra", "dal", "sin"] + e.matches # the instances themselves, each tagged with #metro +end +``` + +`where` is the deliberate plural. It locates the matches once, is Enumerable +over them, and runs each operation in the metro that holds each one: + +```ruby +web = ukc.instances.where(name: "web") + +web.metros # => ["fra", "dal", "sin"] +web.size # => 3 +web.each { |inst| puts inst.state } # the instances +web.suspend # one result per metro +web.edit { |e| e.set(memory_mb: 512) } +``` + +Set operations return Arrays and follow the same partial-failure rule as +reads: the successes ride on the raised `MetroFanoutError` as `results`. +`where` exists on instances, volumes, services and certificates. + +### Partial failure + +A metro that is unreachable does not throw away the rest of the answer. +Healthy metros are drained first, then a `MetroFanoutError` naming the +failures is raised: + +```ruby +begin + ukc.instances.each { |inst| puts inst.name } # fra, dal, was delivered +rescue Unikraft::Cloud::MetroFanoutError => e + e.message # => "1 of 4 metros failed: sin (503)" + e.failures # => [{ metro: "sin", error: # }] +end +``` + +For a bulk operation, which cannot yield as it goes, the results that did +succeed are attached to the raised error as `results`. + +## Lists are lazy Enumerables + +`list` returns an `Enumerator` that pages through every metro in scope on +demand, or takes a block (and then returns the client, like `each`). +`tags:` filters instances and volumes, which the API filters by tag. Each +resource client is itself `Enumerable` over +every resource in scope (with details), so the usual methods just work: + +```ruby +ukc.instances.list(details: true, tags: ["prod"]).each { |i| puts i.name } +ukc.instances.list(page_size: 50).first(10) + +ukc.instances.select { |i| i.state == "running" } +ukc.instances.count +ukc.volumes.map(&:size_mb).sum +``` + +Results are models: one reader per field, `#[]` for any key, `#to_h`, and +pattern matching, including the `metro` tag: + +```ruby +case ukc.instances.first +in { state: "running", metro: "fra" } then puts "running in Frankfurt" +in { name: } then puts "#{name} is elsewhere" +end +``` + +## Chainable handles + +Single-resource operations return a **handle**: a reference to one resource in +one metro. `get` sends nothing; reading an attribute resolves the handle once +and memoizes the resource: + +```ruby +web = ukc.instances.get(name: "web") # no request yet +web.state # => "running" (located and read once) +web.running? # => true (no further request) +web.reload # read again, in place +``` + +Ruby has no `await`, and a lazy mutation that nobody forced would silently +never run. So mutations run **immediately** and return a new handle carrying +what that endpoint reported, at the same location, so calls still chain: + +```ruby +ukc.instances.get(name: "web").suspend.state # => "standby" +ukc.instances.get(name: "web").update(memory_mb: 512) + +ukc.metro(:fra).instances + .create(image: "nginx:latest") + .wait(state: :running, within: 30) + .logs(offset: -4096) + +ukc.volumes.get(name: "data").attach(attach_to: { name: "web" }, at: "/data") +``` + +Each step runs once. What locating costs depends on the scope: + +| Ref and scope | `get(...).suspend` | +| --------------------------------- | ----------------------------------------------------------------- | +| `name:` and `metro:`, any scope | 1 request: the suspend. The ref says where. | +| `name:`, one metro in scope | 1 request: the scope says where. | +| `name:`, many metros | Locate first (one concurrent read per metro), then suspend where it lives, or raise `AmbiguousRefError` if several match. | + +Handles also answer where they landed, and a mutating step carries what its +endpoint reports (`suspend` reports `uuid`, `name`, `state` and +`previous_state`, not a full instance; read it with `handle[:previous_state]`, +and a declared attribute the reply leaves out, such as `memory_mb`, is read +once from the platform on first use): + +```ruby +web = ukc.instances.get(name: "web") +web.metro # => "dal" +web.location # => # +web.to_h # the resource as a Hash +``` + +A handle is meant for one thread; the client behind it is shared. + +Every idiomatic method is also available in non-chained form, the ref keys +(`name:`, `uuid:`, `metro:`) locating the resource and the rest going to the +operation: `ukc.instances.logs(name: "web", offset: -4096)` is exactly +`get(name: "web").logs(offset: -4096)`. `start`, `stop`, `suspend` and +`delete` on the collection are bulk operations instead; see [Refs](#refs). + +## Updating a resource + +The API models an update as a list of `{ prop:, op:, value: }` triples. That +is the plumbing. Idiomatically you pass **keyword arguments** and the op is +worked out for you: a value sets the property, `nil` removes it, and an +omitted property is left alone, following JSON Merge Patch: + +```ruby +ukc.instances.get(name: "web").update(memory_mb: 512, vcpus: 2) +ukc.instances.get(name: "web").update(env: { LOG_LEVEL: "debug" }) +ukc.instances.get(name: "web").update(autokill: nil) # remove it +ukc.volumes.get(name: "data").update(size_mb: 2048) +ukc.services.get(name: "web").update(soft_limit: 5, hard_limit: 20) +``` + +`image` takes the same string shorthand as `create`. `headers:` and +`timeout:` are always call options, never properties: +`update(memory_mb: 512, timeout: 10)`. + +When `set` is not what you mean (merging into a property, or removing +individual members), stage the operations with `edit` and send them as one +request, from a block or chained: + +```ruby +ukc.instances.get(name: "web").edit do |e| + e.set(memory_mb: 512) + e.add(env: { LOG_LEVEL: "debug" }, tags: ["prod"]) + e.remove(env: ["OLD_FLAG"], tags: ["staging"]) +end + +ukc.instances.get(name: "web").edit + .set(memory_mb: 512) + .remove(env: ["OLD_FLAG"]) + .apply + +# `nil` in remove removes the property outright, not just some members. +ukc.services.edit(name: "web") { |e| e.remove(domains: nil) } +``` + +`remove` is the API's `del`. The block form applies when the block returns; +the chained form applies on `apply`. Both return a handle like any other +operation, so chaining continues: + +```ruby +ukc.metro(:fra).instances + .edit(name: "web") + .set(memory_mb: 1024) + .apply + .wait(state: :running) +``` + +Both forms are one request, and both are available without a handle +(`ukc.instances.update(name: "web", memory_mb: 512)`, +`ukc.instances.edit(name: "web")`). The raw triples still work as an escape +hatch: +`ukc.instances.update({ name: "web" }, [{ prop: "memory_mb", op: "set", value: 512 }])`. + +## Refs + +Every operation on an existing resource takes a **ref**: either `name:` or +`uuid:`, never both (passing both raises `ArgumentError`). The API validates +each identifier it is given, so a name sent in the `uuid` filter fails with +`Invalid uuid ''`: the ref makes you state which kind you hold, and only +that field is sent. + +```ruby +ukc.instances.get(name: "web") +ukc.instances.get(uuid: "550e8400-e29b-41d4-a716-446655440000") + +# A name belongs to a metro, so it can be qualified; see "Names across metros". +ukc.instances.get(name: "web", metro: :fra) + +# Bulk operations take one ref, as keywords or a Hash, or an Array of them. +ukc.instances.stop(name: "web") +ukc.instances.stop([{ name: "web" }, { uuid: "550e8400-e29b-41d4-a716-446655440000" }]) +``` + +## Idiomatic methods + +| Resource | Methods | +| ------------------ | --------------------------------------------------------------------------------------------------------- | +| `ukc.instances` | `create`, `get`, `where`, `list`, `each` (Enumerable), `update`, `edit`, `delete`, `start`, `stop`, `suspend`, `wait`, `logs`, `metrics`, `history` | +| `ukc.volumes` | `create`, `get`, `where`, `list`, `each`, `update`, `edit`, `delete`, `attach`, `detach` | +| `ukc.services` | `create`, `get`, `where`, `list`, `each`, `update`, `edit`, `delete` | +| `ukc.certificates` | `create`, `get`, `where`, `list`, `each`, `update`, `delete` | +| `ukc.users` | `quotas`, `quotas(uuid:)` | + +Handles add the per-resource operations: `reload`, `start`, `stop`, +`suspend`, `delete`, `update`, `edit`, `wait`, `logs`, `metrics`, `history` +and the state predicates (`running?`, `stopped?`, `standby?`, …) on an +instance; `attach`, `detach`, `update`, `edit`, `delete` on a volume; +`update`, `edit` and `delete` on a service group; `update` (with `chain:` and +`pkey:`) and `delete` on a certificate. Every handle has `metro`, `location`, +`model`, `to_h`, `[]` and a reader per attribute. + +Anything not listed (autoscale, the image registry, node information, the +whole control plane) is reachable raw via `ukc.api.platform` and +`ukc.api.controlplane`: + +```ruby +ukc.api.platform.autoscale.get_autoscale_configurations(name: ["web"]) +ukc.api.platform.images.get_images +``` + +See [`examples/`](./examples) for complete programs. + +## Errors + +Any network failure or non-2xx response raises a `Unikraft::Cloud::Error`: + +```ruby +begin + ukc.metro(:fra).instances.get(name: "does-not-exist").state +rescue Unikraft::Cloud::Error => e + warn [e.kind, e.status, e.message, e.errors].inspect +end +``` + +`e.kind` says which layer failed: + +| `kind` | Meaning | +| ---------- | -------------------------------------------------------------------------------------------------------------------- | +| `:http` | The server answered with a non-2xx status. `e.status` and `e.errors` carry the detail. | +| `:network` | The request never got an answer: a refused connection, a reset, a DNS miss, an unreachable proxy. | +| `:parse` | The server answered, but the body is not the JSON the operation expects. | +| `:fanout` | A multi-metro operation that partly failed, or an unusable scope; see `MetroFanoutError` above. | +| `:config` | The call could never be sent as configured: two options that contradict each other, or a body on a `GET`. | +| `:timeout` | A wait ran out of time. It carries no `status`, because no single request failed; the last failure is in `e.cause`. | + +`AmbiguousRefError` and `MetroFanoutError` are subclasses, so one +`rescue Unikraft::Cloud::Error` covers everything the SDK raises. An invalid +argument, such as a ref with both `name:` and `uuid:`, raises `ArgumentError` +instead. + +### Waiting + +The transport sends each request exactly once. It has no retries, and nothing +in the SDK retries a call you made. + +Waiting is a separate, explicit step, and it takes one of two shapes: + +- **The server waits.** `instance.wait(state: :running, within: 30)` + forwards the state and the deadline (in seconds; `-1` waits indefinitely) + to the platform, which holds the connection open. One request; the read + timeout of that request is stretched to outlive the wait. `timeout:` is + the HTTP timeout, as on every other call. +- **The SDK polls.** Where the platform has nothing to hold open, the SDK + asks again on a schedule. `Unikraft::Cloud::Core::Ready.wait_until_ready` + owns that loop: the delay doubles from 100 ms to 2 s with jitter, and the + deadline is 60 s. Only a failure that can still change is worth another + probe: a network fault, or a `404`/`502`/`503`/`504`. A `401` or a `403` is + raised at once, so a rejected token reports itself instead of timing out. + +Both raise on failure rather than returning. A poll that runs out of time +raises `kind: :timeout`. + +## Self-hosted and staging deployments + +`metro:` (and `UKC_METRO`) also accepts a full `http(s)://` base URL, which is +used verbatim instead of being expanded into +`https://api..unikraft.cloud`. A trailing `/v1` is dropped, since every +operation path already carries it: + +```sh +export UKC_METRO=https://api.staging.example.internal +``` + +A named endpoint is the only endpoint there is: no metro discovery is +attempted and no hostnames are invented, whatever the scope says. Point the +control plane at a matching deployment with `control_plane_url:`: + +```ruby +ukc = Unikraft::Cloud.new( + token: ENV["UKC_TOKEN"], + metro: "https://api.staging.example.internal", + control_plane_url: "https://controlplane.staging.example.internal" +) +``` + +## Runtime support + +The SDK needs Ruby 3.3 or later (CI covers 3.3, 3.4 and 4.0) and has no +runtime dependencies: it uses `net/http`, `json` and `uri` from the standard +library. + +To customise the transport (a different HTTP stack, instrumentation, or a fake +in tests), pass `transport:`, a callable that receives the transport keywords +(`base_url:`, `token:`, `headers:`, `timeout:`, `proxy_from_env:`, +`user_agent:`) and returns an object with `request`, `bytes` and `stream`, as +`Unikraft::Cloud::Core::ApiClient` has: + +```ruby +ukc = Unikraft::Cloud.new( + transport: ->(**config) { Unikraft::Cloud::Core::ApiClient.new(**config) } +) +``` + +## Debugging with a proxy (MITM) + +The client honours the standard proxy environment variables through +`Net::HTTP`, so you can route traffic through a man-in-the-middle proxy such +as [mitmproxy](https://mitmproxy.org), Charles, or Proxyman without any code +change: + +```sh +export https_proxy=http://127.0.0.1:8080 +export SSL_CERT_FILE=~/.mitmproxy/mitmproxy-ca-cert.pem # trust the proxy CA +ruby your_script.rb +``` + +`http_proxy`, `https_proxy` and `no_proxy` are recognised, in lower- or +upper-case. `SSL_CERT_FILE` replaces OpenSSL's default trust store for the +process, which is what lets it trust the proxy's certificate; unset it when +you are done. Opt out of the proxy variables per client with +`Unikraft::Cloud.new(proxy_from_env: false)`. + +## Contributing + +The plumbing layer is generated; see [CONTRIBUTING.md](./CONTRIBUTING.md) for +how to regenerate it and work on the SDK. + +## License + +BSD-3-Clause. See [LICENSE.md](./LICENSE.md). + +[ukc]: https://unikraft.com +[openapi]: https://github.com/unikraft-cloud/openapi +[dashboard]: https://console.unikraft.cloud