# Ruby SDK

`unikraft-cloud` is the official Ruby SDK for [Unikraft Cloud](https://unikraft.com).
It covers the per-metro [platform API](/api/platform/v1) and the global control plane API.

The SDK has two layers:

* The *porcelain* layer gives results without the response envelope, reads all the pages for you, sends reads to all metros, and lets you chain operations on a resource.
* The *plumbing* layer is the OpenAPI specification as written: one method for each operation, the raw response envelope, and one metro for each call.

Use the porcelain layer for most work.
Use the [plumbing layer](#the-plumbing-layer) for the operations that the porcelain layer doesn't have.

## Installation

```sh
gem install unikraft-cloud
```

To use Bundler, add the gem to your `Gemfile`:

```ruby title="Gemfile"
gem "unikraft-cloud"
```

The SDK needs Ruby 3.3 or later.
It has no runtime dependencies: it uses `net/http`, `json` and `uri` from the Ruby standard library.

## Quickstart

```ruby title="quickstart.rb"
require "unikraft/cloud"

ukc = Unikraft::Cloud.new(token: ENV["UKC_TOKEN"])

# Read the instances of all metros, with the metro of each one.
ukc.instances.list(details: true) do |inst|
  puts "#{inst.metro} #{inst.name} #{inst.state}"
end

# Create the instance in one metro.
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 }]
  }
)

# Chain the operations on the handle.
instance.wait(state: :running)
ukc.instances.get(name: instance.name).suspend
fra.instances.delete(uuid: instance.uuid)
```

## Authentication

The client reads a bearer token from the `UKC_TOKEN` environment variable.
To give the token in your code, use the `token:` option.
Create a token in the [Unikraft Cloud console](https://console.unikraft.cloud).

## Configuration

`Unikraft::Cloud.new` returns a `Unikraft::Cloud::Client`.
All the options have a default value or aren't necessary:

| Option | Default | Description |
| --- | --- | --- |
| `token:` | `UKC_TOKEN` | The bearer token. |
| `metro:` | `UKC_METRO` | The metro of `create` and of the default scope: a metro code, such as `:fra`, or the full `http(s)://` address of an endpoint. |
| `metros:` | `:all`, or the `metro:` value | The default scope of reads and bulk operations: `:all`, one metro, or a list of metros. |
| `base_url:` | None | The address of the platform API, which overrides `metro:`. |
| `control_plane_url:` | The global control plane | The address of the control plane API, for metro discovery and for `ukc.api.controlplane`. |
| `headers:` | `{}` | The headers to add to each request. |
| `timeout:` | `60` | The time limit in seconds to connect and to read. `nil` sets no limit. |
| `proxy_from_env:` | `true` | Use the `http_proxy`, `https_proxy` and `no_proxy` environment variables. |
| `user_agent:` | `unikraft-cloud-ruby/<version>` | The `User-Agent` header. |
| `transport:` | None | A callable that makes the HTTP transport, as [Custom transport](#custom-transport) shows. |

The client is thread-safe.
Make one client and use it in all the threads of your program.
Don't make a client for each request.
All the scopes and handles of a client use the same list of metros and the same connections.

`close` closes the connections of the client.
A call after `close` opens the connections again.
In a script, use `Unikraft::Cloud.open` with a block.
It closes the client after the block, and returns the value of the block:

```ruby
count = Unikraft::Cloud.open(metro: :fra) do |ukc|
  ukc.instances.count
end
```

## Metros

The platform API has one endpoint for each [metro](/platform/metros).
By default, the client sends each read to all the metros that the account can use, at the same time, and merges the results.
Each result has a `metro` attribute, which tells the metro of the result.

```ruby
ukc = Unikraft::Cloud.new(token: ENV["UKC_TOKEN"])

# All the metros of the account.
ukc.instances.each { |inst| puts "#{inst.metro} #{inst.name}" }

# A scope that names its metros.
ukc.metro(:fra).instances.to_a               # one metro
ukc.metros(:fra, :dal).instances.to_a        # two metros
ukc.instances.list(metros: %i[fra dal]).to_a # two metros, for this call only
ukc.instances.list(metros: :all).to_a        # all the metros, for this call only

# The metros that the account can use.
ukc.available_metros.each { |m| puts "#{m.metro} #{m.base_url}" }
```

The client gets the list of metros from the control plane one time, and keeps it.
A scope that names its metros doesn't need this request.
The control plane gives the endpoint of each metro, so the client can use a new metro without an SDK update.
`Unikraft::Cloud::KNOWN_METROS` lists the metros that existed at the release of the SDK version.

Give a metro as a Symbol or as a String.
To set the default scope, give `metro:` or `metros:` when you make the client:

```ruby
Unikraft::Cloud.new                      # all the metros
Unikraft::Cloud.new(metro: :fra)         # one metro
Unikraft::Cloud.new(metros: %i[fra dal]) # two metros
```

`UKC_METRO` has the same effect as `metro:`.
If you give `metro:` and `metros:`, `metros:` sets the scope, and `create` uses `metro:`.

### How the client uses more than one metro

* A read goes to all the metros in the scope.
  The client returns the pages in the order that they arrive, so a slow metro doesn't stop the results of a fast metro.
  The client gets the next page of a metro only when you have used all the items of its last page.
* When you stop early, for example with `first` or `break`, the client stops the requests to the other metros.
  An external enumerator (`next`) can't stop them: if you don't read it to the end, it keeps one thread for each metro until the process stops.
  Thus, use `each`, `first` or `lazy`.
* `create` uses one metro.
  This metro is the `metro:` argument of the call, the metro of the scope, or the default metro of the client (`metro:`, then `UKC_METRO`, then `fra`).
  If the scope has more than one named metro, the scope must include the default metro.
  If not, `create` raises an error with `kind: :config`.
* A bulk operation finds the resources first.
  Then it sends one call to each metro that has a match.
  Thus, `delete(name: "web")` in a wide scope deletes all the `web` resources in the scope.
  To delete only one, make the scope smaller, or add `metro:` to the reference.
* The control plane is global, so the scope has no effect on it.

### Names in more than one metro

A name is unique only in one metro.
Thus, two metros can each have a resource with the same name.
You can select a resource by its name in three ways:

```ruby
# 1. Add the metro to the reference. This sends one request.
ukc.instances.get(name: "web", metro: :fra).suspend

# 2. Use a scope with one metro.
ukc.metro(:fra).instances.get(name: "web").suspend

# 3. Use the resource in all the metros that have it.
ukc.instances.where(name: "web").suspend # one result for each metro
```

A UUID identifies one resource in all the metros.
But in a scope with more than one metro, the SDK reads each metro to find a `uuid:` reference too.
To send one request, add `metro:` or use a scope with one metro.

A handle from `get` must find exactly one resource, because the next operation can change it.
`get` sends no request, so the first use of the handle finds the resource.
If the name matches resources in more than one metro, this first use raises `AmbiguousRefError`.
The error contains the matches, so you don't have to send more requests:

```ruby
begin
  ukc.instances.get(name: "web").suspend
rescue Unikraft::Cloud::AmbiguousRefError => e
  e.metros  # => ["fra", "dal", "sin"]
  e.matches # the instances, each with its metro
end
```

To use all the matches, use `where`.
`where` finds the matches one time, and it's `Enumerable` on them.
Each operation goes to the metro of each match:

```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 for each metro
web.edit { |e| e.set(memory_mb: 512) }
```

An operation on `where` returns an Array.
Instances, volumes, services and certificates have `where`.

### Partial failures

If a metro doesn't answer, the client keeps the results of the other metros.
The client first returns the results of the metros that answered.
Then it raises `MetroFanoutError`, with the metros that failed:

```ruby
begin
  ukc.instances.each { |inst| puts inst.name } # the results of fra, dal and was
rescue Unikraft::Cloud::MetroFanoutError => e
  e.message  # => "1 of 4 metros failed: sin (503)"
  e.failures # => [{ metro: "sin", error: #<Unikraft::Cloud::Error ...> }]
end
```

A bulk operation and an operation on `where` can't return results one at a time.
For these operations, the `results` attribute of the error has the results of the metros that succeeded.

## Lists

`list` returns a lazy `Enumerator`.
The enumerator gets the pages of each metro in the scope when you need them.
With a block, `list` gives each item to the block, and returns the resource client.
The `tags:` argument filters instances and volumes by tag.

Each resource client, such as `ukc.instances`, is `Enumerable` on all the resources in the scope, with their details:

```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
```

Each result is a model.
A model has a reader for each field, `#[]` for each key, and `#to_h`.
Models support pattern matching, also on the `metro` attribute:

```ruby
case ukc.instances.first
in { state: "running", metro: "fra" } then puts "running in Frankfurt"
in { name: } then puts "#{name} is in another metro"
end
```

## Chainable handles

An operation on one resource returns a *handle*: a reference to one resource in one metro.
`get` sends no request.
When you read an attribute, the handle gets the resource one time and keeps it:

```ruby
web = ukc.instances.get(name: "web") # no request
web.state                            # => "running" (find the instance and read it)
web.running?                         # => true (no request)
web.reload                           # read the instance again
```

An operation that changes a resource sends its request immediately.
It returns a new handle, at the same location, with the data that the endpoint returned.
Thus, you can chain the calls:

```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")
```

The number of requests depends on the reference and on the scope:

| Reference and scope | Requests for `get(...).suspend` |
| --- | --- |
| `name:` and `metro:`, any scope | One request: the suspend. |
| `name:`, one metro in the scope | One request: the suspend. |
| `name:`, more than one metro in the scope | One read to each metro to find the instance, then the suspend in the metro of the instance, or `AmbiguousRefError` if more than one metro has a match. |

A handle has `metro`, `location`, `model`, `to_h`, `[]`, and a reader for each attribute:

```ruby
web = ukc.instances.get(name: "web")
web.metro    # => "dal"
web.location # => #<data Location ref=..., metro="dal", base_url="https://api.dal.unikraft.cloud">
web.to_h     # the instance as a Hash
```

A handle from an operation that changes the resource has only the fields that its endpoint returns.
For example, `suspend` returns `uuid`, `name`, `state` and `previous_state`.
To read a field that the handle has no reader for, use `[]`, for example `handle[:previous_state]`.
If you read an attribute that the reply doesn't have, such as `memory_mb`, the handle gets it from the platform one time.

Use a handle in one thread only.
You can share the client between threads.

Each porcelain operation also has a form without a handle.
The reference keys (`name:`, `uuid:`, `metro:`) find the resource, and the other arguments go to the operation.
For example, `ukc.instances.logs(name: "web", offset: -4096)` is the same as `ukc.instances.get(name: "web").logs(offset: -4096)`.
On a resource client, `start`, `stop`, `suspend` and `delete` are bulk operations.
See [References](#references).

## Updating a resource

Give the properties as keyword arguments.
A value sets the property, `nil` removes it, and the update doesn't change a property that you don't give.
This is the behavior of 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 the property
ukc.volumes.get(name: "data").update(size_mb: 2048)
ukc.services.get(name: "web").update(soft_limit: 5, hard_limit: 20)
```

`headers:` and `timeout:` are always options of the call, not properties.
For example, `update(memory_mb: 512, timeout: 10)` sets a time limit of 10 seconds.

To add values to a property, or to remove some of its values, use `edit`.
`edit` collects the operations and sends them in one request.
Use a block or a chain:

```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

# With nil, remove deletes the full property.
ukc.services.edit(name: "web") { |e| e.remove(domains: nil) }
```

`remove` is the `del` operation of the API.
The block form sends the request at the end of the block.
The chain form sends the request on `apply`.
Both forms return a handle, so you can continue the chain:

```ruby
ukc.metro(:fra).instances
   .edit(name: "web")
   .set(memory_mb: 1024)
   .apply
   .wait(state: :running)
```

You can also use `update` and `edit` without a handle, for example `ukc.instances.update(name: "web", memory_mb: 512)`.
To send the raw operations of the API, give a list of `{ prop:, op:, value: }` items:

```ruby
ukc.instances.update({ name: "web" }, [{ prop: "memory_mb", op: "set", value: 512 }])
```

## References

An operation on a resource takes a *reference*: `name:` or `uuid:`, but not both.
If you give both, the SDK raises `ArgumentError`.
The SDK sends only the field that you give.
The API validates each identifier, so a name in the `uuid` field fails with an `Invalid uuid` error.

```ruby
ukc.instances.get(name: "web")
ukc.instances.get(uuid: "550e8400-e29b-41d4-a716-446655440000")

# Add the metro of the name.
ukc.instances.get(name: "web", metro: :fra)

# A bulk operation takes one reference, or an Array of references.
ukc.instances.stop(name: "web")
ukc.instances.stop([{ name: "web" }, { uuid: "550e8400-e29b-41d4-a716-446655440000" }])
```

## Resources

| Resource client | Methods |
| --- | --- |
| `ukc.instances` | `create`, `get`, `where`, `list`, `each`, `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:)` |

The handles have these operations:

| Handle | Operations |
| --- | --- |
| Instance | `reload`, `start`, `stop`, `suspend`, `delete`, `update`, `edit`, `wait`, `logs`, `metrics`, `history`, and a state predicate for each state, such as `running?`, `stopped?` and `standby?` |
| Volume | `attach`, `detach`, `update`, `edit`, `delete` |
| Service group | `update`, `edit`, `delete` |
| Certificate | `update` (with `chain:` and `pkey:`), `delete` |

The plumbing layer has the other operations, for example autoscale, the image registry, node information, and all the control plane:

```ruby
ukc.api.platform.autoscale.get_autoscale_configurations(name: ["web"])
ukc.api.platform.images.get_images
```

## The plumbing layer

The plumbing layer has a method for each `operationId` of the [OpenAPI specification](https://github.com/unikraft-cloud/openapi).
Each method returns the response envelope.
The porcelain layer contains a plumbing client, so the plumbing layer is available from the same client and with the same credentials:

```ruby
# Porcelain: no envelope, metro-aware.
inst = ukc.instances.get(name: "web")

# Plumbing, from the same client.
res = ukc.api.platform.instances.get_instances(count: 10, details: true)
res.status # => "success"
res.data.instances

# Plumbing, for one resource client.
ukc.instances.api.get_instance_logs(name: ["web"])

# Plumbing, without the porcelain layer.
api = Unikraft::Cloud::API::Platform.new(
  base_url: "https://api.fra.unikraft.cloud", token: ENV["UKC_TOKEN"]
)
api.instances.get_instances(count: 10)
```

A plumbing client uses one metro: the metro of its `base_url:`.
To send one call to a different metro, give `base_url:` to the call.

The SDK has plumbing clients for the two APIs:

* `Unikraft::Cloud::API::Platform` and `ukc.api.platform` for the platform API: instances, volumes, services, certificates, autoscale, and images in one metro.
* `Unikraft::Cloud::API::ControlPlane` and `ukc.api.controlplane` for the global control plane API: the account, the metros, images and self-hosted nodes.
  The control plane has no porcelain layer.

```ruby
ukc.api.controlplane.metros.list_metros.data.metros.each do |metro|
  puts "#{metro.iata_code} #{metro.endpoint}"
end
```

## Errors

A network failure, a response with a status that isn't 2xx, or an error in the body of a 2xx response raises `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` tells which layer failed:

| `kind` | Description |
| --- | --- |
| `:http` | The server sent a status that isn't 2xx, or an error in the body of a 2xx response, and `e.status` and `e.errors` have the details. |
| `:network` | The request got no answer, for example because of a refused connection, a reset, a DNS failure, a proxy that isn't available, or the end of the `timeout:` time limit. |
| `:parse` | The server sent a body that isn't the JSON that the operation expects. |
| `:fanout` | An operation on more than one metro failed in part, as in [Partial failures](#partial-failures), or the scope isn't correct. |
| `:config` | The SDK can't send the call with this configuration, for example because a `GET` has a body, or because `create` has a scope of metros without the default metro. |
| `:timeout` | The polling helper used all its time: the error has no `status`, because no request failed, and `e.cause` has the last failure. |

`AmbiguousRefError` and `MetroFanoutError` are subclasses of `Unikraft::Cloud::Error`.
Thus, one `rescue Unikraft::Cloud::Error` catches all the errors of the SDK.
An argument that isn't correct, such as a reference with `name:` and `uuid:`, raises `ArgumentError`.

The API can report an error in the body of a 2xx response, for each item.
For such an error, `e.status` is the HTTP status of the error code, for example `404` for a resource that doesn't exist, or `nil`.

## Waiting

The SDK sends each request one time, and doesn't send it again after a failure.
There's one exception: if the server closes a reused connection before the response, the SDK sends a `GET`, `HEAD`, `PUT`, `DELETE` or `OPTIONS` request again on a new connection.

To wait for an instance, use `wait`:

```ruby
ukc.instances.get(name: "web").wait(state: :running, within: 30)
```

`wait` sends the state and the time limit in seconds to the platform.
The platform keeps the connection open until the instance gets to the state, or until the time limit.
`-1` waits with no time limit.
This is one request, and the SDK makes the read timeout of this request longer than the wait.
The `timeout:` option is the HTTP time limit, as for all other calls.

To wait for a service that has no such endpoint, use the polling helper `Unikraft::Cloud::Core::Ready.wait_until_ready`.
The helper calls your block until the block returns without an error.
It gives the block the seconds that stay until the time limit, so that the block can use them as the `timeout:` of its request.
For example, this block waits until the instance `web` exists in `fra`:

```ruby
Unikraft::Cloud::Core::Ready.wait_until_ready(timeout: 10, what: "the web instance") do |left|
  ukc.instances.get(name: "web", metro: :fra).reload(timeout: left)
end
```

The interval between two calls starts at 100 ms and doubles to a maximum of 2 s, with a random change.
By default, the helper stops after 60 s, and raises an error with `kind: :timeout`.
It calls the block again only after a failure that can change: a network failure, or a `404`, `502`, `503` or `504` status.
It raises the other errors immediately.
Thus, a token that isn't correct causes a `401` or `403` error, and not a timeout.

## Self-hosted and staging deployments

`metro:` and `UKC_METRO` also accept the full `http(s)://` address of an endpoint.
The SDK uses the address without changes, and doesn't make a `https://api.<metro>.unikraft.cloud` address from it.
The SDK removes a `/v1` at the end of the address, because the path of each operation starts with `/v1`:

```sh
export UKC_METRO=https://api.staging.example.internal
```

With an address, the client uses only this endpoint.
It doesn't get the list of metros from the control plane, and it doesn't make other URLs, for all scopes.
To use the control plane of the same deployment, give `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"
)
```

## Custom transport

To use a different HTTP library, to add instrumentation, or to replace the HTTP transport in tests, give `transport:`.
`transport:` is a callable.
It receives the transport keywords `base_url:`, `token:`, `headers:`, `timeout:`, `proxy_from_env:` and `user_agent:`.
It returns an object with the `request`, `bytes` and `stream` methods, as `Unikraft::Cloud::Core::ApiClient` has:

```ruby
ukc = Unikraft::Cloud.new(
  transport: ->(**config) { Unikraft::Cloud::Core::ApiClient.new(**config) }
)
```

## Debugging with a proxy

The client uses the proxy environment variables through `Net::HTTP`.
Thus, to see the traffic of the SDK, you can send it through a proxy such as [mitmproxy](https://mitmproxy.org), and not change your code:

```sh
export https_proxy=http://127.0.0.1:8080
export SSL_CERT_FILE=~/.mitmproxy/mitmproxy-ca-cert.pem
ruby your_script.rb
```

The client uses `http_proxy`, `https_proxy` and `no_proxy`, in lowercase or in uppercase.
`SSL_CERT_FILE` replaces the default trusted certificates of OpenSSL for the process, so that the client trusts the certificate of the proxy.
Remove `SSL_CERT_FILE` when you're done.
To ignore the proxy variables in one client, use `Unikraft::Cloud.new(proxy_from_env: false)`.

## Source

The source of the SDK is at [github.com/unikraft-cloud/ruby-sdk](https://github.com/unikraft-cloud/ruby-sdk), and the gem is at [rubygems.org/gems/unikraft-cloud](https://rubygems.org/gems/unikraft-cloud).
See [`examples/`](https://github.com/unikraft-cloud/ruby-sdk/tree/HEAD/examples) for complete programs.

## Learn more

* [JavaScript SDK](/sdks/js): the client library for the same platform API in JavaScript and TypeScript.
* [Python SDK](/sdks/python): the client library for the same platform API in Python.
* [Go SDK](/sdks/go): the client library for the same platform API in Go.
* [Metros](/platform/metros): the regions that the SDK uses.
* [Instances](/platform/instances): create and manage the instances that the SDK controls.
* Unikraft Cloud's [REST API reference](/api/platform/v1), which the plumbing layer mirrors.
