unikraft-cloud 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.md +28 -0
  3. data/README.md +587 -0
  4. data/lib/unikraft/cloud/api/controlplane/auth.gen.rb +83 -0
  5. data/lib/unikraft/cloud/api/controlplane/images.gen.rb +51 -0
  6. data/lib/unikraft/cloud/api/controlplane/metros.gen.rb +45 -0
  7. data/lib/unikraft/cloud/api/controlplane/models.gen.rb +865 -0
  8. data/lib/unikraft/cloud/api/controlplane/node_activation_service.gen.rb +79 -0
  9. data/lib/unikraft/cloud/api/controlplane/node_service.gen.rb +276 -0
  10. data/lib/unikraft/cloud/api/controlplane/resources.gen.rb +12 -0
  11. data/lib/unikraft/cloud/api/controlplane.rb +49 -0
  12. data/lib/unikraft/cloud/api/platform/audit.gen.rb +55 -0
  13. data/lib/unikraft/cloud/api/platform/autoscale.gen.rb +231 -0
  14. data/lib/unikraft/cloud/api/platform/certificates.gen.rb +168 -0
  15. data/lib/unikraft/cloud/api/platform/images.gen.rb +109 -0
  16. data/lib/unikraft/cloud/api/platform/instances.gen.rb +873 -0
  17. data/lib/unikraft/cloud/api/platform/models.gen.rb +6456 -0
  18. data/lib/unikraft/cloud/api/platform/node.gen.rb +45 -0
  19. data/lib/unikraft/cloud/api/platform/resources.gen.rb +16 -0
  20. data/lib/unikraft/cloud/api/platform/services.gen.rb +172 -0
  21. data/lib/unikraft/cloud/api/platform/users.gen.rb +134 -0
  22. data/lib/unikraft/cloud/api/platform/volumes.gen.rb +430 -0
  23. data/lib/unikraft/cloud/api/platform.rb +64 -0
  24. data/lib/unikraft/cloud/api.rb +45 -0
  25. data/lib/unikraft/cloud/client.rb +186 -0
  26. data/lib/unikraft/cloud/core/base64.rb +36 -0
  27. data/lib/unikraft/cloud/core/errors.rb +96 -0
  28. data/lib/unikraft/cloud/core/fanout.rb +150 -0
  29. data/lib/unikraft/cloud/core/handle.rb +214 -0
  30. data/lib/unikraft/cloud/core/handle_set.rb +105 -0
  31. data/lib/unikraft/cloud/core/http.rb +361 -0
  32. data/lib/unikraft/cloud/core/metro.rb +75 -0
  33. data/lib/unikraft/cloud/core/pagination.rb +43 -0
  34. data/lib/unikraft/cloud/core/patch.rb +113 -0
  35. data/lib/unikraft/cloud/core/pool.rb +97 -0
  36. data/lib/unikraft/cloud/core/ready.rb +145 -0
  37. data/lib/unikraft/cloud/core/ref.rb +95 -0
  38. data/lib/unikraft/cloud/core/resource.rb +399 -0
  39. data/lib/unikraft/cloud/core/response.rb +96 -0
  40. data/lib/unikraft/cloud/core/session.rb +182 -0
  41. data/lib/unikraft/cloud/core/url.rb +34 -0
  42. data/lib/unikraft/cloud/model.rb +194 -0
  43. data/lib/unikraft/cloud/resources/certificates.rb +57 -0
  44. data/lib/unikraft/cloud/resources/instances.rb +172 -0
  45. data/lib/unikraft/cloud/resources/service_groups.rb +36 -0
  46. data/lib/unikraft/cloud/resources/users.rb +39 -0
  47. data/lib/unikraft/cloud/resources/volumes.rb +93 -0
  48. data/lib/unikraft/cloud/version.rb +11 -0
  49. data/lib/unikraft/cloud.rb +29 -0
  50. metadata +89 -0
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SPDX-License-Identifier: BSD-3-Clause
4
+ # Copyright (c) 2026, Unikraft GmbH.
5
+ #
6
+ # Acting on every metro that holds a name. Names are unique within a metro,
7
+ # not across them, so one name can legitimately refer to a resource in every
8
+ # metro. `where(name: ...)` addresses all of them at once, on purpose.
9
+
10
+ require_relative "fanout"
11
+ require_relative "patch"
12
+
13
+ module Unikraft
14
+ module Cloud
15
+ module Core
16
+ # Every resource matching one ref, one per metro. Enumerable over the
17
+ # resources; each operation runs in every metro concurrently and
18
+ # returns an Array with one result per metro. When some metros fail,
19
+ # the successes ride on the {MetroFanoutError} as `results`.
20
+ #
21
+ # The matches are located once, on first use.
22
+ #
23
+ # @example
24
+ # web = ukc.instances.where(name: "web")
25
+ # web.metros # => ["fra", "dal"]
26
+ # web.map(&:state) # => ["running", "standby"]
27
+ # web.suspend # => [handle, handle]
28
+ class HandleSet
29
+ include Enumerable
30
+
31
+ class << self
32
+ # Expose a handle operation on the set.
33
+ #
34
+ # @param names [Array<Symbol>]
35
+ def forward(*names)
36
+ names.each do |name|
37
+ define_method(name) do |*args, **kw, &block|
38
+ fan(kw) { |handle| handle.public_send(name, *args, **kw, &block) }
39
+ end
40
+ end
41
+ end
42
+ end
43
+
44
+ # @api private
45
+ def initialize(noun, &locate)
46
+ @noun = noun
47
+ @locate = locate
48
+ end
49
+
50
+ # @param call [Hash] `headers:`/`timeout:` for the lookup, over
51
+ # those given to `where`; only the first use locates
52
+ # @return [Array<Handle>] one per metro holding a match
53
+ def handles(**call)
54
+ @handles ||= @locate.call(call.slice(:headers, :timeout)).freeze
55
+ end
56
+
57
+ # Yield each match's resource.
58
+ #
59
+ # @yieldparam resource [Model]
60
+ def each(&)
61
+ return enum_for(:each) { size } unless block_given?
62
+
63
+ handles.each { |handle| yield handle.model }
64
+ self
65
+ end
66
+
67
+ # @return [Array<String>] the metros holding a match
68
+ def metros = handles.map(&:metro)
69
+
70
+ # @return [Integer] how many metros hold a match
71
+ def size = handles.size
72
+ alias length size
73
+
74
+ forward :delete, :update
75
+
76
+ # Read every match again, in place.
77
+ #
78
+ # @return [self]
79
+ def reload(**call)
80
+ fan(call) { |handle| handle.reload(**call) }
81
+ self
82
+ end
83
+
84
+ # Stage changes once and apply them to every match.
85
+ #
86
+ # @return [Patch::Editor, Array<Handle>]
87
+ def edit(**call)
88
+ editor = Patch::Editor.new(@noun) do |items|
89
+ fan(call) { |handle| handle.update(items, **call) }
90
+ end
91
+ return editor unless block_given?
92
+
93
+ yield editor
94
+ editor.apply
95
+ end
96
+
97
+ def inspect = "#<#{self.class.name} #{@handles ? metros.inspect : "(not located)"}>"
98
+
99
+ private
100
+
101
+ def fan(call = {}, &) = Fanout.all(handles(**call), &)
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,361 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SPDX-License-Identifier: BSD-3-Clause
4
+ # Copyright (c) 2026, Unikraft GmbH.
5
+ #
6
+ # Shared, spec-independent HTTP transport for the generated plumbing clients
7
+ # and the plugin gems.
8
+
9
+ require "json"
10
+ require "net/http"
11
+ require "openssl"
12
+ require "uri"
13
+
14
+ require_relative "errors"
15
+ require_relative "pool"
16
+ require_relative "url"
17
+ require_relative "../version"
18
+
19
+ module Unikraft
20
+ module Cloud
21
+ module Core
22
+ # Transport for one base URL. Performs authenticated requests and
23
+ # returns the parsed response envelope. Raises {Unikraft::Cloud::Error}
24
+ # on network failures and non-2xx responses. It never retries, except
25
+ # to resend an idempotent request once when a reused keep-alive
26
+ # connection turns out stale (see CONTRIBUTING.md).
27
+ #
28
+ # Connections are kept alive and reused across calls, also from
29
+ # several threads at once; see {#close} and CONTRIBUTING.md,
30
+ # "Connection reuse".
31
+ #
32
+ # It satisfies the duck-typed transport the plugin gems
33
+ # (`unikraft-cloud-plugin-<name>-api`) take: `request`, `bytes` and
34
+ # `stream`, each with the keywords `method:`, `path:`, `query:`,
35
+ # `body:`, `headers:`, plus the per-call `base_url:` and `timeout:`.
36
+ # A change to one of those signatures is a breaking change for every
37
+ # plugin gem; see CONTRIBUTING.md, "The transport contract".
38
+ #
39
+ # Proxies come from the environment (`http_proxy`, `https_proxy`,
40
+ # `no_proxy`, any case) through Net::HTTP, unless `proxy_from_env:` is
41
+ # false.
42
+ #
43
+ # @example
44
+ # client = Unikraft::Cloud::Core::ApiClient.new(
45
+ # base_url: "https://api.fra.unikraft.cloud", token: ENV["UKC_TOKEN"]
46
+ # )
47
+ # client.request(method: :get, path: "/v1/instances", query: { count: 10 })
48
+ class ApiClient
49
+ # Seconds to wait for a connection and for each read, by default.
50
+ DEFAULT_TIMEOUT = 60
51
+
52
+ # Methods that must not carry a body.
53
+ BODYLESS = %w[GET HEAD].freeze
54
+
55
+ # Separator between two server-sent events.
56
+ SSE_EVENT_BOUNDARY = /\r\n\r\n|\n\n|\r\r/
57
+
58
+ # What Net::HTTP raises when a request never gets an answer.
59
+ NETWORK_ERRORS = [
60
+ IOError, SocketError, SystemCallError, Timeout::Error,
61
+ OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::ProtocolError
62
+ ].freeze
63
+
64
+ # On a reused connection and before any response: the server
65
+ # closed the connection while it sat idle (EOFError is an IOError).
66
+ STALE_ERRORS = [IOError, Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED].freeze
67
+
68
+ # Methods safe to resend after a stale connection (RFC 9110): the
69
+ # server may have read the first copy before it hung up.
70
+ IDEMPOTENT = %w[GET HEAD PUT DELETE OPTIONS].freeze
71
+
72
+ # A reused connection turned out stale; resend on a fresh one.
73
+ class StaleConnection < StandardError; end
74
+ private_constant :StaleConnection
75
+
76
+ # @return [String] the base URL, without trailing slashes
77
+ attr_reader :base_url
78
+ # @return [String, nil] the bearer token
79
+ attr_reader :token
80
+ # @return [Hash{String => String}] headers sent with every request
81
+ attr_reader :headers
82
+ # @return [Numeric, nil] the default timeout in seconds
83
+ attr_reader :timeout
84
+
85
+ # @param base_url [String] e.g. `https://api.fra.unikraft.cloud`
86
+ # @param token [String, nil] bearer token
87
+ # @param headers [Hash{String => String}] default headers
88
+ # @param user_agent [String, nil] overrides the SDK's User-Agent
89
+ # @param timeout [Numeric, nil] seconds per connect and read; nil
90
+ # waits without limit
91
+ # @param proxy_from_env [Boolean] honour the proxy env variables
92
+ def initialize(base_url:, token: nil, headers: {}, user_agent: nil,
93
+ timeout: DEFAULT_TIMEOUT, proxy_from_env: true)
94
+ @base_url = URL.strip_trailing_slashes(base_url)
95
+ @token = token
96
+ @headers = { "User-Agent" => user_agent || "unikraft-cloud-ruby/#{VERSION}" }
97
+ headers&.each { |k, v| @headers[k.to_s] = v.to_s }
98
+ @timeout = timeout
99
+ @proxy_from_env = proxy_from_env
100
+ @pool = Pool.new
101
+ end
102
+
103
+ # Leaves out the token and headers, so echoing what holds it is safe.
104
+ def inspect = "#<#{self.class.name} base_url=#{@base_url.inspect}>"
105
+
106
+ # Close the idle connections. Calls made afterwards open new ones,
107
+ # so this is safe to call at any time, and more than once.
108
+ #
109
+ # @return [nil]
110
+ def close = @pool.close
111
+
112
+ # Perform a request and return its parsed JSON body (symbol keys).
113
+ #
114
+ # @param method [String, Symbol] HTTP method
115
+ # @param path [String] path below the base URL, already escaped
116
+ # @param query [Hash, nil] query parameters; arrays repeat the key and
117
+ # nil values are left out
118
+ # @param body [Object, nil] JSON body; refused on GET and HEAD
119
+ # @param headers [Hash, nil] merged over the defaults for this call
120
+ # @param options [Hash] `base_url:` and `timeout:` for this call
121
+ # @return [Hash, Array, nil] the parsed body, or nil when empty
122
+ # @raise [Unikraft::Cloud::Error]
123
+ def request(method:, path:, query: nil, body: nil, headers: nil, **options)
124
+ perform("application/json", method:, path:, query:, body:, headers:,
125
+ **options) do |res, url|
126
+ text = res.body.to_s
127
+ parsed = text.empty? ? nil : parse_json(text, res, url)
128
+ raise http_error(res, parsed, text) unless res.is_a?(Net::HTTPSuccess)
129
+
130
+ parsed
131
+ end
132
+ end
133
+
134
+ # Perform a request whose success response is an unenveloped
135
+ # `application/octet-stream` body, and return it verbatim.
136
+ #
137
+ # @param (see #request)
138
+ # @return [String] the body, binary
139
+ # @raise [Unikraft::Cloud::Error]
140
+ def bytes(method:, path:, query: nil, body: nil, headers: nil, **options)
141
+ perform("application/octet-stream", method:, path:, query:, body:, headers:,
142
+ **options) do |res, _|
143
+ raise http_error(res, *lenient_json(res.body.to_s)) unless res.is_a?(Net::HTTPSuccess)
144
+
145
+ res.body.to_s.b
146
+ end
147
+ end
148
+
149
+ # Perform a request whose response is a `text/event-stream`, and yield
150
+ # each event's JSON payload (symbol keys) as it arrives. Returns when
151
+ # the server closes the stream; `break` out of the block to stop early
152
+ # (that closes the connection).
153
+ #
154
+ # @param (see #request)
155
+ # @yieldparam event [Hash, Array] one event's parsed `data`
156
+ # @return [Enumerator, nil] an Enumerator when no block is given
157
+ # @raise [Unikraft::Cloud::Error]
158
+ def stream(method:, path:, query: nil, body: nil, headers: nil, **options, &block)
159
+ unless block
160
+ return enum_for(:stream, method: method, path: path, query: query, body: body,
161
+ headers: headers, **options)
162
+ end
163
+
164
+ perform("text/event-stream", method:, path:, query:, body:, headers:,
165
+ **options) do |res, url|
166
+ raise http_error(res, *lenient_json(res.body.to_s)) unless res.is_a?(Net::HTTPSuccess)
167
+
168
+ read_events(res, url, &block)
169
+ end
170
+ nil
171
+ end
172
+
173
+ private
174
+
175
+ # Build and send one request, and hand the response to the block (a
176
+ # stream while it can still be read from the connection).
177
+ def perform(accept, method:, path:, query:, body:, headers:, **options)
178
+ options = call_options(options)
179
+ verb = method.to_s.upcase
180
+ if !body.nil? && BODYLESS.include?(verb)
181
+ raise Error.new("A #{verb} request cannot carry a body; pass the filters as query " \
182
+ "parameters instead", kind: :config)
183
+ end
184
+
185
+ url = URL.strip_trailing_slashes(options.fetch(:base_url) || @base_url) +
186
+ path.to_s + encode_query(query)
187
+ uri = URI(url)
188
+ req = build_request(verb, uri, body, headers, accept)
189
+ fresh = connection(uri)
190
+ via_proxy = fresh.proxy?
191
+ begin
192
+ exchange(fresh, req, options.fetch(:timeout)) { |res| yield res, url }
193
+ rescue *NETWORK_ERRORS => e
194
+ raise network_error(url, e, via_proxy)
195
+ end
196
+ end
197
+
198
+ # Send req on an idle connection if there is one, else on fresh.
199
+ def exchange(fresh, req, timeout, &)
200
+ # Connections are interchangeable when all of these match.
201
+ key = [fresh.use_ssl?, fresh.address, fresh.port, fresh.proxy_address,
202
+ fresh.proxy_port, fresh.proxy_user, fresh.proxy_pass]
203
+ idle = @pool.checkout(key)
204
+ attempt(key, idle || fresh, req, timeout, reused: !idle.nil?, &)
205
+ rescue StaleConnection
206
+ attempt(key, fresh, req, timeout, reused: false, &)
207
+ end
208
+
209
+ # Send req on http and yield the response: a stream while it is
210
+ # still being read, anything else once its body is in. Puts http
211
+ # back in the pool only after a clean, complete exchange.
212
+ #
213
+ # Raises StaleConnection, for one resend on a fresh connection, only
214
+ # when an IDEMPOTENT request on a reused connection fails with a
215
+ # STALE_ERRORS error before any response arrived: most likely the
216
+ # server closed it while idle. Anything else propagates as is.
217
+ def attempt(key, http, req, timeout, reused:)
218
+ stream = req["Accept"] == "text/event-stream"
219
+ responded = done = false
220
+ configure(http, timeout)
221
+ http.start unless http.started?
222
+ result = nil
223
+ res = http.request(req) do |r|
224
+ responded = true
225
+ result = yield r if stream
226
+ end
227
+ done = true
228
+ stream ? result : yield(res)
229
+ rescue *STALE_ERRORS
230
+ raise if responded || !reused || !IDEMPOTENT.include?(req.method)
231
+
232
+ raise StaleConnection
233
+ ensure
234
+ if done && !/\bclose\b/i.match?(res["connection"].to_s)
235
+ @pool.checkin(key, http)
236
+ else
237
+ @pool.discard(http)
238
+ end
239
+ end
240
+
241
+ def call_options(options)
242
+ unknown = options.keys - %i[base_url timeout]
243
+ raise ArgumentError, "unknown keyword(s): #{unknown.join(", ")}" unless unknown.empty?
244
+
245
+ { base_url: options[:base_url], timeout: options.fetch(:timeout, @timeout) }
246
+ end
247
+
248
+ def build_request(verb, uri, body, headers, accept)
249
+ req = Net::HTTPGenericRequest.new(verb, !body.nil?, verb != "HEAD", uri)
250
+ req["Accept"] = accept
251
+ @headers.each { |k, v| req[k] = v }
252
+ req["Authorization"] = "Bearer #{@token}" if @token
253
+ headers&.each { |k, v| req[k.to_s] = v.to_s }
254
+ unless body.nil?
255
+ req["Content-Type"] = "application/json"
256
+ req.body = JSON.generate(body)
257
+ end
258
+ req
259
+ end
260
+
261
+ def connection(uri)
262
+ proxy = @proxy_from_env ? :ENV : nil
263
+ http = Net::HTTP.new(uri.host, uri.port, proxy)
264
+ http.use_ssl = uri.scheme == "https"
265
+ http
266
+ end
267
+
268
+ # Set every time: the connection may come from the pool.
269
+ def configure(http, timeout)
270
+ http.open_timeout = timeout
271
+ http.read_timeout = timeout
272
+ http.write_timeout = timeout
273
+ http.keep_alive_timeout = @pool.keep_alive
274
+ http.max_retries = 0 # Net::HTTP would resend idempotent requests
275
+ end
276
+
277
+ # Serialise a query hash in form/explode style.
278
+ def encode_query(query)
279
+ return "" if query.nil?
280
+
281
+ pairs = query.each_with_object([]) do |(key, value), out|
282
+ next if value.nil?
283
+
284
+ Array(value).each { |item| out << [key.to_s, item.to_s] unless item.nil? }
285
+ end
286
+ pairs.empty? ? "" : "?#{URI.encode_www_form(pairs)}"
287
+ end
288
+
289
+ def parse_json(text, res, url)
290
+ JSON.parse(text, symbolize_names: true)
291
+ rescue JSON::ParserError => e
292
+ unless res.is_a?(Net::HTTPSuccess)
293
+ raise Error.new("HTTP #{res.code} #{res.message}".strip,
294
+ kind: :http, status: res.code.to_i, body: text, cause: e)
295
+ end
296
+
297
+ raise Error.new("Failed to parse response body from #{url}",
298
+ kind: :parse, status: res.code.to_i, body: text, cause: e)
299
+ end
300
+
301
+ # Decode an error body that may or may not be an envelope.
302
+ def lenient_json(text)
303
+ parsed = text.empty? ? nil : JSON.parse(text, symbolize_names: true)
304
+ [parsed, text]
305
+ rescue JSON::ParserError
306
+ [nil, text]
307
+ end
308
+
309
+ def http_error(res, parsed, text)
310
+ envelope = parsed.is_a?(Hash) ? parsed : {}
311
+ message = envelope[:message] || "HTTP #{res.code} #{res.message}".strip
312
+ Error.new(message, kind: :http, status: res.code.to_i,
313
+ errors: envelope[:errors], body: parsed.nil? ? text : parsed)
314
+ end
315
+
316
+ def network_error(url, cause, via_proxy)
317
+ via = via_proxy ? " (through the proxy set in http_proxy/https_proxy)" : ""
318
+ Error.new("Request to #{url} failed#{via}: #{cause.class}: #{cause.message}",
319
+ kind: :network, cause: cause)
320
+ end
321
+
322
+ def read_events(res, url)
323
+ buffer = +""
324
+ res.read_body do |chunk|
325
+ buffer << chunk.b
326
+ while (boundary = SSE_EVENT_BOUNDARY.match(buffer))
327
+ block = buffer[0, boundary.begin(0)]
328
+ buffer = buffer[boundary.end(0)..]
329
+ event = parse_event(block, url, res)
330
+ yield event unless event.nil?
331
+ end
332
+ end
333
+ # A last event may arrive without its trailing blank line.
334
+ event = parse_event(buffer, url, res)
335
+ yield event unless event.nil?
336
+ end
337
+
338
+ # The JSON payload of one event block: its `data:` lines joined. Nil
339
+ # for comments and keep-alives.
340
+ def parse_event(block, url, res)
341
+ values = block.dup.force_encoding(Encoding::UTF_8).split("\n").filter_map do |raw|
342
+ line = raw.chomp("\r")
343
+ next if line.start_with?(":")
344
+
345
+ field, sep, value = line.partition(":")
346
+ next unless field == "data"
347
+
348
+ sep.empty? ? "" : value.delete_prefix(" ")
349
+ end
350
+ data = values.join("\n")
351
+ return nil if data.empty?
352
+
353
+ JSON.parse(data, symbolize_names: true)
354
+ rescue JSON::ParserError => e
355
+ raise Error.new("Failed to parse event stream from #{url}",
356
+ kind: :parse, status: res.code.to_i, body: data, cause: e)
357
+ end
358
+ end
359
+ end
360
+ end
361
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SPDX-License-Identifier: BSD-3-Clause
4
+ # Copyright (c) 2026, Unikraft GmbH.
5
+
6
+ require_relative "url"
7
+ require_relative "errors"
8
+
9
+ module Unikraft
10
+ module Cloud
11
+ # The metros known when this version was published. Any other code works
12
+ # too: discovery trusts the control plane, so new metros need no upgrade.
13
+ KNOWN_METROS = %w[fra dal sin was sfo].freeze
14
+
15
+ # The metro an operation that must pick one (such as `create`) uses when
16
+ # neither `metro:` nor `UKC_METRO` names one.
17
+ DEFAULT_METRO = "fra"
18
+
19
+ # The global control-plane API. Unlike the platform API it has no metro.
20
+ CONTROLPLANE_BASE_URL = "https://controlplane.unikraft.cloud"
21
+
22
+ module Core
23
+ # A metro paired with the platform API base URL that serves it.
24
+ #
25
+ # @!attribute [r] metro
26
+ # @return [String] the metro code, or the base URL itself for an
27
+ # explicitly named endpoint
28
+ # @!attribute [r] base_url
29
+ # @return [String]
30
+ Endpoint = Data.define(:metro, :base_url)
31
+
32
+ # Turning metro codes, URLs and scopes into endpoints.
33
+ module Metro
34
+ module_function
35
+
36
+ # @param metro [String, Symbol]
37
+ # @return [Boolean] whether the value is an `http(s)://` URL
38
+ def url?(metro)
39
+ metro.to_s.match?(%r{\Ahttps?://}i)
40
+ end
41
+
42
+ # The platform API base URL of a metro: `fra` becomes
43
+ # `https://api.fra.unikraft.cloud`. A URL is used verbatim, minus
44
+ # trailing slashes and a trailing `/v1`, which every operation path
45
+ # already carries.
46
+ #
47
+ # @param metro [String, Symbol]
48
+ # @return [String]
49
+ def base_url(metro)
50
+ return "https://api.#{metro}.unikraft.cloud" unless url?(metro)
51
+
52
+ URL.strip_trailing_slashes(metro).sub(%r{/v1\z}, "")
53
+ end
54
+
55
+ # @param metro [String, Symbol]
56
+ # @return [Endpoint]
57
+ def endpoint(metro)
58
+ Endpoint.new(metro: metro.to_s, base_url: base_url(metro))
59
+ end
60
+
61
+ # Normalise a scope: `:all` (or `"all"`), one metro, or a list of them,
62
+ # as Symbols or Strings.
63
+ #
64
+ # @param scope [Symbol, String, Array<Symbol, String>]
65
+ # @return [:all, Array<String>]
66
+ def scope(scope)
67
+ list = Array(scope).flatten
68
+ return :all if list.size == 1 && list.first.to_s == "all"
69
+
70
+ list.map(&:to_s).uniq.freeze
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SPDX-License-Identifier: BSD-3-Clause
4
+ # Copyright (c) 2026, Unikraft GmbH.
5
+
6
+ module Unikraft
7
+ module Cloud
8
+ module Core
9
+ # Following a list endpoint's pages. The platform API pages with a
10
+ # `count` page size and a `from` cursor (exclusive); a page shorter than
11
+ # `count` is the last.
12
+ module Pagination
13
+ DEFAULT_PAGE_SIZE = 100
14
+
15
+ module_function
16
+
17
+ # Yield every item of every page, fetching a page only when the
18
+ # previous one is used up.
19
+ #
20
+ # @param fetch [#call] `(count, from)` -> the page, an Array
21
+ # @param page_size [Integer, nil] defaults to {DEFAULT_PAGE_SIZE}
22
+ # @param cursor [Symbol] the field of the last item the next page
23
+ # starts after
24
+ # @yieldparam item [Object]
25
+ def each(fetch:, page_size: nil, cursor: :uuid, &)
26
+ count = page_size.is_a?(Integer) && page_size.positive? ? page_size : DEFAULT_PAGE_SIZE
27
+ from = nil
28
+ loop do
29
+ page = fetch.call(count, from)
30
+ page.each(&)
31
+ return if page.size < count
32
+
33
+ last = page.last && page.last[cursor]
34
+ # No usable cursor: stop rather than loop forever.
35
+ return if last.nil? || last == from
36
+
37
+ from = last
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SPDX-License-Identifier: BSD-3-Clause
4
+ # Copyright (c) 2026, Unikraft GmbH.
5
+ #
6
+ # Updating a resource. The API models an update as a list of
7
+ # `{ prop:, op:, value: }` triples. This turns that into two idiomatic forms,
8
+ # both sent as one request:
9
+ #
10
+ # update(memory_mb: 512, autokill: nil) # ops inferred
11
+ # edit.set(...).add(...).remove(...).apply # ops stated outright
12
+
13
+ module Unikraft
14
+ module Cloud
15
+ module Core
16
+ # Patch triples from keyword arguments.
17
+ module Patch
18
+ module_function
19
+
20
+ # Turn a patch into triples. A value takes `operation`; nil removes the
21
+ # property outright (JSON Merge Patch), whichever method supplied it.
22
+ # Omitted properties are left alone.
23
+ #
24
+ # @param patch [Hash{Symbol => Object}]
25
+ # @param operation ["set", "add", "del"]
26
+ # @return [Array<Hash>]
27
+ def items(patch, operation)
28
+ patch.map do |prop, value|
29
+ value.nil? ? { prop: prop.to_s, op: "del" } : { prop: prop.to_s, op: operation, value: }
30
+ end
31
+ end
32
+
33
+ # The triples of an `update`: a patch Hash, or raw triples as an
34
+ # escape hatch.
35
+ #
36
+ # @param changes [Hash, Array<Hash>]
37
+ # @return [Array<Hash>]
38
+ def changes(changes)
39
+ list = if changes.is_a?(Array)
40
+ changes.map { |c| c.transform_keys(&:to_sym) }
41
+ else
42
+ items(changes, "set")
43
+ end
44
+ raise ArgumentError, "nothing to update" if list.empty?
45
+
46
+ list
47
+ end
48
+
49
+ # A staged edit: chain {#set}, {#add} and {#remove}, then {#apply} to
50
+ # send every change in one request, in the order written.
51
+ #
52
+ # @example
53
+ # inst.edit.set(memory_mb: 512).add(tags: ["prod"]).remove(env: ["OLD"]).apply
54
+ # inst.edit do |e|
55
+ # e.set(memory_mb: 512)
56
+ # e.remove(autokill: nil)
57
+ # end
58
+ class Editor
59
+ # @param what [String] the noun of the error message
60
+ # @yieldparam items [Array<Hash>] the triples, on {#apply}
61
+ def initialize(what, &commit)
62
+ @what = what
63
+ @commit = commit
64
+ @items = []
65
+ end
66
+
67
+ # Replace these properties' values; nil removes the property.
68
+ # @return [self]
69
+ def set(**patch) = stage(patch, "set")
70
+
71
+ # Merge into these properties, keeping what is already there.
72
+ # @return [self]
73
+ def add(**patch) = stage(patch, "add")
74
+
75
+ # Remove members from these properties (`env: ["LOG_LEVEL"]`), or
76
+ # the whole property with nil. The API calls this op `del`.
77
+ # @return [self]
78
+ def remove(**patch) = stage(patch, "del")
79
+
80
+ # @return [Array<Hash>] the triples staged so far
81
+ def changes = @items.dup.freeze
82
+
83
+ # Send every staged change as one update.
84
+ #
85
+ # @return [Object] what the update returns: a handle, or an Array
86
+ # of them for a set
87
+ # @raise [ArgumentError] when nothing was staged
88
+ def apply
89
+ if @items.empty?
90
+ raise ArgumentError, "This #{@what} edit has no changes to apply; call set, add or " \
91
+ "remove first."
92
+ end
93
+
94
+ @commit.call(changes)
95
+ end
96
+
97
+ # Values left out: any of them may be a secret (a token, credentials).
98
+ def inspect
99
+ staged = @items.map { |i| "#{i[:op]} #{i[:prop]}" }.join(", ")
100
+ "#<#{self.class.name} #{@what} #{staged}>"
101
+ end
102
+
103
+ private
104
+
105
+ def stage(patch, operation)
106
+ @items.concat(Patch.items(patch, operation))
107
+ self
108
+ end
109
+ end
110
+ end
111
+ end
112
+ end
113
+ end