octaspace 0.2.0 → 0.3.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 (46) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -30
  3. data/LICENSE +21 -0
  4. data/README.md +104 -289
  5. data/lib/octaspace/client.rb +40 -23
  6. data/lib/octaspace/configuration.rb +73 -14
  7. data/lib/octaspace/errors.rb +70 -39
  8. data/lib/octaspace/json_null.rb +56 -0
  9. data/lib/octaspace/middleware/url_rotator.rb +3 -3
  10. data/lib/octaspace/model.rb +115 -0
  11. data/lib/octaspace/money.rb +69 -0
  12. data/lib/octaspace/railtie.rb +1 -2
  13. data/lib/octaspace/resources/accounts.rb +8 -20
  14. data/lib/octaspace/resources/base.rb +49 -2
  15. data/lib/octaspace/resources/compute.rb +123 -0
  16. data/lib/octaspace/resources/hosting.rb +107 -0
  17. data/lib/octaspace/resources/network.rb +24 -5
  18. data/lib/octaspace/resources/render.rb +46 -0
  19. data/lib/octaspace/resources/sessions.rb +125 -10
  20. data/lib/octaspace/resources/stats.rb +57 -0
  21. data/lib/octaspace/resources/vpn.rb +48 -0
  22. data/lib/octaspace/response.rb +62 -12
  23. data/lib/octaspace/transport/base.rb +30 -30
  24. data/lib/octaspace/transport/faraday_transport.rb +157 -91
  25. data/lib/octaspace/transport/persistent_transport.rb +23 -49
  26. data/lib/octaspace/types/account.rb +17 -4
  27. data/lib/octaspace/types/hosting.rb +116 -0
  28. data/lib/octaspace/types/machines.rb +158 -0
  29. data/lib/octaspace/types/network.rb +87 -0
  30. data/lib/octaspace/types/session.rb +173 -4
  31. data/lib/octaspace/types/stats.rb +143 -0
  32. data/lib/octaspace/version.rb +1 -1
  33. data/lib/octaspace.rb +21 -19
  34. metadata +30 -35
  35. data/MIT-LICENSE +0 -22
  36. data/lib/octaspace/payload_helpers.rb +0 -53
  37. data/lib/octaspace/resources/apps.rb +0 -19
  38. data/lib/octaspace/resources/idle_jobs.rb +0 -32
  39. data/lib/octaspace/resources/nodes.rb +0 -63
  40. data/lib/octaspace/resources/services/machine_rental.rb +0 -78
  41. data/lib/octaspace/resources/services/render.rb +0 -30
  42. data/lib/octaspace/resources/services/session_proxy.rb +0 -54
  43. data/lib/octaspace/resources/services/vpn.rb +0 -30
  44. data/lib/octaspace/resources/services.rb +0 -39
  45. data/lib/octaspace/types/balance.rb +0 -11
  46. data/lib/octaspace/types/node.rb +0 -12
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OctaSpace
4
+ # Conversions for micro-USD, the integer unit of every price, charge and
5
+ # balance in the API (1 micro-USD = $0.000001).
6
+ #
7
+ # @example
8
+ # OctaSpace::Money.format(100) # => "$0.000100"
9
+ # OctaSpace::Money.to_usd(1_250_000) # => (5/4)
10
+ # OctaSpace::Money.from_usd("0.25") # => 250000
11
+ module Money
12
+ # Number of micro-USD in one dollar
13
+ MICRO_USD_PER_USD = 1_000_000
14
+
15
+ module_function
16
+
17
+ # Converts an integer amount to dollars, exactly.
18
+ # @param amount [Integer] micro-USD (or units of 10^-decimals)
19
+ # @param decimals [Integer] decimal places of the unit (6 for micro-USD)
20
+ # @return [Rational]
21
+ def to_usd(amount, decimals: 6)
22
+ Rational(integer!(amount), 10**decimals)
23
+ end
24
+
25
+ # Converts dollars to micro-USD, rounded to the nearest integer
26
+ # (e.g. for +hosting.set_prices+).
27
+ # @param usd [Integer, Rational, String, Float] a String like "0.25" is
28
+ # exact; a Float goes through its shortest decimal form
29
+ # @return [Integer]
30
+ def from_usd(usd)
31
+ value = case usd
32
+ when Integer, Rational then usd
33
+ when Float
34
+ raise ArgumentError, "not a finite dollar amount: #{usd}" unless usd.finite?
35
+
36
+ Rational(usd.to_s)
37
+ when String
38
+ text = usd.strip.delete_prefix("$")
39
+ raise ArgumentError, "not a dollar amount: #{usd.inspect}" unless text.match?(/\A-?\d+(\.\d+)?\z/)
40
+
41
+ Rational(text)
42
+ else
43
+ raise ArgumentError, "not a dollar amount: #{usd.inspect}"
44
+ end
45
+ (value * MICRO_USD_PER_USD).round
46
+ end
47
+
48
+ # Formats an integer amount as dollars with all decimal places, using
49
+ # integer arithmetic: 100 → "$0.000100", -1_250_000 → "-$1.250000".
50
+ # @param amount [Integer] micro-USD (or units of 10^-decimals)
51
+ # @param decimals [Integer]
52
+ # @return [String]
53
+ def format(amount, decimals: 6)
54
+ amount = integer!(amount)
55
+ whole, fraction = amount.abs.divmod(10**decimals)
56
+ sign = amount.negative? ? "-" : ""
57
+ return "#{sign}$#{whole}" if decimals.zero?
58
+
59
+ "#{sign}$#{whole}.#{fraction.to_s.rjust(decimals, "0")}"
60
+ end
61
+
62
+ def integer!(amount)
63
+ raise ArgumentError, "not an integer amount: #{amount.inspect}" unless amount.is_a?(Integer)
64
+
65
+ amount
66
+ end
67
+ private_class_method :integer!
68
+ end
69
+ end
@@ -14,8 +14,7 @@ module OctaSpace
14
14
  # end
15
15
  class Railtie < ::Rails::Railtie
16
16
  initializer "octaspace.configure" do
17
- # No-op: users call OctaSpace.configure {} directly in their initializer.
18
- # This hook exists for future extensions (e.g., auto-configure from credentials).
17
+ # Configure the SDK with OctaSpace.configure in your own initializer.
19
18
  end
20
19
 
21
20
  # Gracefully shut down the shared client's persistent connection pools
@@ -2,31 +2,19 @@
2
2
 
3
3
  module OctaSpace
4
4
  module Resources
5
- # Account-related API endpoints
5
+ # The account the API key belongs to
6
6
  #
7
7
  # @example
8
- # client.accounts.profile
9
- # client.accounts.balance
8
+ # client.accounts.balance.formatted # => "$12.500000"
10
9
  class Accounts < Base
11
- # Fetch the authenticated user's profile
12
- # GET /accounts
13
- # @return [OctaSpace::Response]
14
- def profile
15
- get("/accounts")
16
- end
17
-
18
- # Fetch the authenticated user's balance
10
+ # Account balance.
19
11
  # GET /accounts/balance
20
- # @return [OctaSpace::Response]
12
+ #
13
+ # Also a simple way to check that an API key works. A recent charge or
14
+ # deposit can take a moment to appear.
15
+ # @return [OctaSpace::Types::Balance]
21
16
  def balance
22
- get("/accounts/balance")
23
- end
24
-
25
- # Generate / create a new wallet for the authenticated user
26
- # POST /accounts
27
- # @return [OctaSpace::Response]
28
- def generate_wallet
29
- post("/accounts")
17
+ Types::Balance.new(get("/accounts/balance").data)
30
18
  end
31
19
  end
32
20
  end
@@ -7,8 +7,11 @@ module OctaSpace
7
7
  # Base class for all API resource groups
8
8
  #
9
9
  # Delegates HTTP methods to the transport layer and provides
10
- # a clean DSL for subclasses.
10
+ # helpers shared by the resources.
11
11
  class Base
12
+ # Integer fields of a listing's GPU objects, read as numbers
13
+ GPU_INTEGER_FIELDS = %w[mem_total_mb pcie_link_gen pcie_link_width core_clock mem_clock power_limit].freeze
14
+
12
15
  # @param transport [OctaSpace::Transport::Base]
13
16
  def initialize(transport)
14
17
  @transport = transport
@@ -20,8 +23,8 @@ module OctaSpace
20
23
 
21
24
  def get(path, **opts) = transport.get(path, **opts)
22
25
  def post(path, **opts) = transport.post(path, **opts)
23
- def put(path, **opts) = transport.put(path, **opts)
24
26
  def patch(path, **opts) = transport.patch(path, **opts)
27
+ def put(path, **opts) = transport.put(path, **opts)
25
28
  def delete(path, **opts) = transport.delete(path, **opts)
26
29
 
27
30
  # Encode a single path segment to prevent path traversal
@@ -30,6 +33,50 @@ module OctaSpace
30
33
  def encode(segment)
31
34
  URI.encode_www_form_component(segment.to_s)
32
35
  end
36
+
37
+ # Keeps only the given keys whose value is not nil, so a request never
38
+ # carries fields the caller did not set. An unknown key raises
39
+ # ArgumentError before anything is sent (the API would refuse it).
40
+ def compact_params(params, allowed)
41
+ params = params.to_h.transform_keys(&:to_sym)
42
+ unknown = params.keys - allowed
43
+ raise ArgumentError, "unknown parameter(s): #{unknown.join(", ")}" if unknown.any?
44
+
45
+ params.compact
46
+ end
47
+
48
+ # Gives every batch item an id: its own, or its position in the array.
49
+ # Raises ArgumentError when two items end up with the same id (their
50
+ # results could not be told apart, and each started session costs money).
51
+ def batch_items(items, allowed)
52
+ raise ArgumentError, "a batch needs at least one item" if Array(items).empty?
53
+
54
+ seen = {}
55
+ Array(items).each_with_index.map do |item, index|
56
+ raise ArgumentError, "batch item #{index} must be a Hash" unless item.is_a?(Hash)
57
+
58
+ params = item.to_h.transform_keys(&:to_sym)
59
+ id = params.key?(:id) ? params.delete(:id) : index
60
+ raise ArgumentError, "duplicate batch id #{id.inspect}: give every item a unique id, or none to all of them" if seen.key?(id)
61
+
62
+ seen[id] = true
63
+ {id: id, **compact_params(params, allowed)}
64
+ end
65
+ end
66
+
67
+ # Machine listings: "null" strings become nil and numeric GPU strings
68
+ # become numbers.
69
+ def normalize_machines(data, fields = GPU_INTEGER_FIELDS)
70
+ JsonNull.gpu_numbers!(JsonNull.null_strings!(Array(data)), fields)
71
+ end
72
+
73
+ # GET of statistics that need no API key, with "null" strings read as nil
74
+ def get_public(path, **params)
75
+ JsonNull.null_strings!(get(path, params: params, auth: :none).data)
76
+ end
77
+
78
+ # Converts a Time (or anything with #to_time) to Unix seconds
79
+ def unix(value) = value.respond_to?(:to_time) ? value.to_time.to_i : value
33
80
  end
34
81
  end
35
82
  end
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OctaSpace
4
+ module Resources
5
+ # Compute machines and apps: listing, start (single and batch) and restart.
6
+ #
7
+ # @example
8
+ # machine = client.compute.list.min_by(&:base_price)
9
+ # uuid = client.compute.start(node_number: machine.node_number, image: "ubuntu:24.04",
10
+ # disk_size: 10, ssh: true)
11
+ # client.sessions.wait_ready(uuid)
12
+ class Compute < Base
13
+ # Parameters that {#restart} replaces
14
+ RESTART_PARAMS = %i[disk_size envs ports http_ports entrypoint args ssh fm startup_script].freeze
15
+
16
+ # Parameters of {#start}
17
+ START_PARAMS = (%i[node_number image app] + RESTART_PARAMS).freeze
18
+
19
+ # Machines available for rent.
20
+ # GET /services/compute
21
+ #
22
+ # Works without an API key, but is then refreshed about once an hour;
23
+ # with a key it is at most 10 seconds old.
24
+ # @return [Array<OctaSpace::Types::ComputeMachine>]
25
+ def list
26
+ Types::ComputeMachine.wrap_all(normalize_machines(get("/services/compute", auth: :optional).data))
27
+ end
28
+
29
+ # Apps to start a session from: the official ones and, with an API key,
30
+ # your own (+personal?+), which also carry +startup_script+ and +envs+.
31
+ # GET /compute/apps
32
+ #
33
+ # @example Start a session from an app
34
+ # app = client.compute.apps.find { |a| a.name == "Ubuntu 24.04 LTS" }
35
+ # client.compute.start(node_number: "7KQ4-M2XD-4", image: app.image, app: app.uuid,
36
+ # disk_size: [app.min_disk_size || 1, 10].max)
37
+ # @return [Array<OctaSpace::Types::ComputeApp>]
38
+ def apps
39
+ data = Array(get("/compute/apps", auth: :optional).data)
40
+ data.each do |app|
41
+ next unless app.is_a?(Hash)
42
+
43
+ %w[category description].each { |field| app[field] = nil if app[field] == "null" }
44
+ end
45
+ Types::ComputeApp.wrap_all(data)
46
+ end
47
+
48
+ # Starts one session.
49
+ # POST /services/compute
50
+ #
51
+ # Returns as soon as the session is created; wait for it with
52
+ # +client.sessions.wait_ready+. Validation and business errors
53
+ # ("Insufficient balance", "Node not available", …) raise
54
+ # {OctaSpace::ValidationError}; an unknown parameter raises ArgumentError
55
+ # before anything is sent. Never retried automatically: a start costs
56
+ # money.
57
+ #
58
+ # @param node_number [String] node number from the listing, e.g. "7KQ4-M2XD-4"
59
+ # (case, dashes and spaces are ignored)
60
+ # @param image [String] container image, e.g. "ubuntu:24.04"
61
+ # @param app [String, nil] uuid of an app from {#apps}; +image+ is still required
62
+ # @param disk_size [Integer, nil] disk, GB (default 1); an app's +min_disk_size+
63
+ # is a recommendation: with less, the app may run out of space
64
+ # @param envs [Hash{String=>String}, nil] up to 64 variables, values up to 4 KiB
65
+ # @param ports [Array<Integer>, nil] TCP/UDP ports to expose (0 and 22 are ignored)
66
+ # @param http_ports [Array<Integer>, nil] HTTP ports to expose (7681, 7682 are reserved)
67
+ # @param entrypoint [String, nil] replaces the image's ENTRYPOINT (one line, up to 4 KiB)
68
+ # @param args [String, nil] replaces the image's CMD (one line, up to 4 KiB)
69
+ # @param ssh [Boolean, nil] web terminal and SSH access; nil = the app's setting
70
+ # @param fm [Boolean, nil] web file manager (no login: anyone with the URL can use it);
71
+ # nil = the app's setting
72
+ # @param startup_script [String, nil] run as root in the background once the container is up
73
+ # @return [String] the session uuid
74
+ def start(**params)
75
+ missing = %i[node_number image].reject { |key| params.key?(key) }
76
+ raise ArgumentError, "missing keyword(s): #{missing.join(", ")}" if missing.any?
77
+
78
+ post("/services/compute", body: compact_params(params, START_PARAMS)).data.fetch("uuid")
79
+ end
80
+
81
+ # Starts several sessions at once.
82
+ # POST /services/compute
83
+ #
84
+ # Each item is validated on its own and reported in request order; a
85
+ # failed item does not fail the batch. Items without an +:id+ get their
86
+ # position in the array; ids may be integers or strings.
87
+ #
88
+ # @param items [Array<Hash>] {#start} parameters, each with an optional +:id+
89
+ # @return [Array<OctaSpace::Types::BatchResult>]
90
+ def start_batch(items)
91
+ Types::BatchResult.wrap_all(post("/services/compute", body: batch_items(items, START_PARAMS)).data)
92
+ end
93
+
94
+ # Recreates the session's container on the same node, keeping the rent,
95
+ # uuid and prices.
96
+ # POST /services/compute/{uuid}/restart
97
+ #
98
+ # Follow the progress with +client.sessions.get(uuid)+; if the new
99
+ # parameters cannot be applied, the session stops.
100
+ #
101
+ # - Without parameters: restarts with the original parameters.
102
+ # - With parameters: *replaces all of them*. Every omitted parameter gets
103
+ # a fixed default, not its current value: +disk_size+ 1 GB,
104
+ # +entrypoint+/+args+ from the image, no +startup_script+, no +envs+,
105
+ # no +ports+/+http_ports+, +ssh+/+fm+ from the app (off without one).
106
+ # Pass the full set you want, +disk_size+ included.
107
+ #
108
+ # Raises {OctaSpace::ConflictError} (409) while the session is still
109
+ # starting or restarting, and {OctaSpace::RateLimitError} (429) when it is
110
+ # restarted more often than once per 5 minutes or 6 times per hour
111
+ # (+retry_after+ says how long to wait). Never retried automatically.
112
+ #
113
+ # @param uuid [String]
114
+ # @param params [Hash] see {#start}, without node_number, image and app
115
+ # @return [String] the session uuid
116
+ def restart(uuid, **params)
117
+ body = compact_params(params, RESTART_PARAMS)
118
+ response = post("/services/compute/#{encode(uuid)}/restart", body: body.empty? ? nil : body)
119
+ response.data.is_a?(Hash) ? response.data.fetch("uuid", uuid) : uuid
120
+ end
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OctaSpace
4
+ module Resources
5
+ # Nodes the account hosts: state, prices and maintenance
6
+ #
7
+ # @example
8
+ # client.hosting.nodes.each { |node| puts "#{node.number} #{node.status}" }
9
+ # client.hosting.set_prices("7KQ4-M2XD-4", base: OctaSpace::Money.from_usd("0.25"))
10
+ # client.hosting.start_maintenance("7KQ4-M2XD-4")
11
+ class Hosting < Base
12
+ PRICE_FIELDS = %i[base storage traffic min_rent_minutes].freeze
13
+
14
+ # Integer GPU fields of +system.gpus+, read as numbers
15
+ HOSTING_GPU_FIELDS = (GPU_INTEGER_FIELDS + %w[mem_free_mb fan_speed gpu_temperature gpu_utilization power_draw_watt]).freeze
16
+
17
+ # Online nodes of the account with their state, hardware and prices.
18
+ # GET /hosting/nodes
19
+ #
20
+ # Offline nodes are not listed. A node that runs only VPN sessions stays
21
+ # "idle".
22
+ # @return [Array<OctaSpace::Types::HostingNode>]
23
+ def nodes
24
+ Types::HostingNode.wrap_all(normalize_nodes(transport.get("/hosting/nodes").data))
25
+ end
26
+
27
+ # One online node of the account.
28
+ # GET /hosting/nodes/{number}
29
+ #
30
+ # Raises {OctaSpace::NotFoundError} when the node is offline, does not
31
+ # exist or is not yours, and {OctaSpace::ValidationError} for a
32
+ # malformed number.
33
+ # @param number [String] node number; case and dashes are ignored
34
+ # @return [OctaSpace::Types::HostingNode]
35
+ def get(number)
36
+ Types::HostingNode.wrap(normalize_nodes([transport.get("/hosting/nodes/#{encode(number)}").data]).first)
37
+ end
38
+
39
+ # Updates some prices of a node.
40
+ # PATCH /hosting/nodes/{number}/prices
41
+ #
42
+ # Never retried automatically.
43
+ # Only the given fields are sent; at least one is required. Amounts are
44
+ # integer micro-USD (convert dollars with {OctaSpace::Money.from_usd}).
45
+ # Ranges: base and traffic 100..1_000_000_000, storage 0..1_000_000_000,
46
+ # min_rent_minutes 0..60. The API refuses other values with
47
+ # {OctaSpace::ValidationError}, and an unknown node with
48
+ # {OctaSpace::NotFoundError}.
49
+ #
50
+ # The listings (+hosting.nodes+, +compute.list+) show new prices within
51
+ # seconds.
52
+ #
53
+ # @param number [String] node number; case and dashes are ignored
54
+ # @param base [Integer, nil]
55
+ # @param storage [Integer, nil]
56
+ # @param traffic [Integer, nil]
57
+ # @param min_rent_minutes [Integer, nil]
58
+ # @return [nil]
59
+ def set_prices(number, **prices)
60
+ body = compact_params(prices, PRICE_FIELDS)
61
+ raise ArgumentError, "set_prices needs at least one of #{PRICE_FIELDS.join(", ")}" if body.empty?
62
+
63
+ body.each do |field, value|
64
+ raise ArgumentError, "#{field} must be an Integer (micro-USD or minutes), got #{value.inspect}" unless value.is_a?(Integer)
65
+ end
66
+ patch("/hosting/nodes/#{encode(number)}/prices", body: body)
67
+ nil
68
+ end
69
+
70
+ # Puts a node in maintenance: it is no longer offered for new rentals;
71
+ # running sessions go on and their renters are notified. Works for an
72
+ # offline node too, and calling it again changes nothing.
73
+ # PUT /hosting/nodes/{number}/maintenance
74
+ #
75
+ # Raises {OctaSpace::NotFoundError} when the node is not yours or does
76
+ # not exist, and {OctaSpace::ValidationError} for a malformed number.
77
+ # @param number [String] node number
78
+ # @return [nil]
79
+ def start_maintenance(number)
80
+ put(maintenance_path(number))
81
+ nil
82
+ end
83
+
84
+ # Offers a node for rent again. Calling it again changes nothing.
85
+ # DELETE /hosting/nodes/{number}/maintenance
86
+ #
87
+ # Raises the same errors as {#start_maintenance}.
88
+ # @param number [String] node number
89
+ # @return [nil]
90
+ def end_maintenance(number)
91
+ delete(maintenance_path(number))
92
+ nil
93
+ end
94
+
95
+ private
96
+
97
+ def maintenance_path(number) = "/hosting/nodes/#{encode(number)}/maintenance"
98
+
99
+ # "null" strings become nil and numeric GPU strings in +system.gpus+ numbers
100
+ def normalize_nodes(data)
101
+ nodes = JsonNull.null_strings!(Array(data))
102
+ JsonNull.gpu_numbers!(nodes.filter_map { |node| node["system"] if node.is_a?(Hash) }, HOSTING_GPU_FIELDS)
103
+ nodes
104
+ end
105
+ end
106
+ end
107
+ end
@@ -2,16 +2,35 @@
2
2
 
3
3
  module OctaSpace
4
4
  module Resources
5
- # Network information endpoint
5
+ # Platform statistics; no API key needed
6
6
  #
7
7
  # @example
8
- # client.network.info
8
+ # client.network.info.nodes.online
9
+ # client.network.history(from: Time.now - 7 * 86_400).points.last.nodes_online
9
10
  class Network < Base
10
- # Fetch combined network information (blockchain, market, nodes, power, etc.)
11
+ # Platform statistics now: nodes, capacity, sessions, users, rendered
12
+ # frames and VPN nodes.
11
13
  # GET /network
12
- # @return [OctaSpace::Response]
14
+ #
15
+ # Raises {OctaSpace::ServiceUnavailableError} while it is unavailable.
16
+ # @return [OctaSpace::Types::Network]
13
17
  def info
14
- get("/network")
18
+ Types::Network.new(get_public("/network"))
19
+ end
20
+
21
+ # Platform statistics over time, one point per +step+. Each value is the
22
+ # average over its step, so it can be fractional. Defaults to the last
23
+ # day with hourly points. Invalid ranges (step < 300, too many points,
24
+ # from after to) raise {OctaSpace::ValidationError}.
25
+ # GET /network/history
26
+ #
27
+ # @param from [Time, Integer, nil] range start (Unix seconds); a day before +to+ by default
28
+ # @param to [Time, Integer, nil] range end (Unix seconds); now by default
29
+ # @param step [Integer, nil] seconds between points, at least 300 (default 3600);
30
+ # at most 2000 points
31
+ # @return [OctaSpace::Types::NetworkHistory]
32
+ def history(from: nil, to: nil, step: nil)
33
+ Types::NetworkHistory.new(get_public("/network/history", start: unix(from), end: unix(to), step: step))
15
34
  end
16
35
  end
17
36
  end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OctaSpace
4
+ module Resources
5
+ # Render nodes: listing and start (single and batch).
6
+ #
7
+ # @example
8
+ # node = client.render.list.max_by(&:blender_score)
9
+ # uuid = client.render.start(node_number: node.node_number)
10
+ class Render < Base
11
+ START_PARAMS = %i[node_number].freeze
12
+
13
+ # Nodes available for render.
14
+ # GET /services/render
15
+ #
16
+ # Works without an API key, but is then refreshed about once an hour;
17
+ # with a key it is at most 10 seconds old.
18
+ # @return [Array<OctaSpace::Types::RenderMachine>]
19
+ def list
20
+ Types::RenderMachine.wrap_all(normalize_machines(get("/services/render", auth: :optional).data))
21
+ end
22
+
23
+ # Rents a node as a render node, billed by the hour until stopped.
24
+ # POST /services/render
25
+ #
26
+ # While render is temporarily unavailable this raises
27
+ # {OctaSpace::ServiceUnavailableError} (503). Never retried automatically.
28
+ # @param node_number [String]
29
+ # @return [String] the session uuid
30
+ def start(node_number:)
31
+ post("/services/render", body: {node_number: node_number}).data.fetch("uuid")
32
+ end
33
+
34
+ # Rents several render nodes at once.
35
+ # POST /services/render
36
+ #
37
+ # Unlike {#start}, a temporarily unavailable service is reported in each
38
+ # item's +reason+ instead of raising {OctaSpace::ServiceUnavailableError}.
39
+ # @param items [Array<Hash>] each +{node_number:}+ with an optional +:id+
40
+ # @return [Array<OctaSpace::Types::BatchResult>]
41
+ def start_batch(items)
42
+ Types::BatchResult.wrap_all(post("/services/render", body: batch_items(items, START_PARAMS)).data)
43
+ end
44
+ end
45
+ end
46
+ end
@@ -2,22 +2,137 @@
2
2
 
3
3
  module OctaSpace
4
4
  module Resources
5
- # Session listing endpoint
5
+ # The account's running sessions.
6
6
  #
7
- # For operations on a specific session (info/logs/stop),
8
- # use the proxy pattern: client.services.session("uuid")
7
+ # The API reports running sessions only: once a session stops, {#get},
8
+ # {#logs} and {#stop} raise {OctaSpace::NotFoundError}, and there is no
9
+ # session history.
9
10
  #
10
11
  # @example
11
- # client.sessions.list
12
- # client.sessions.list(recent: true)
12
+ # uuid = client.compute.start(node_number: "7KQ4-M2XD-4", image: "ubuntu:24.04")
13
+ # session = client.sessions.wait_ready(uuid) { |s| puts "#{s.progress} #{s.pull_percent}" }
14
+ # client.sessions.logs(uuid, tail: 50).container
15
+ # client.sessions.stop(uuid)
16
+ # client.sessions.wait_stopped(uuid)
13
17
  class Sessions < Base
14
- # List all sessions
18
+ # Default seconds between polls of {#wait_ready} and {#wait_stopped}
19
+ # (the authenticated limit is 300 requests a minute per account)
20
+ DEFAULT_WAIT_INTERVAL = 3
21
+
22
+ # @param sleeper [#call] waits the given number of seconds between polls
23
+ def initialize(transport, sleeper: ->(seconds) { sleep(seconds) })
24
+ super(transport)
25
+ @sleeper = sleeper
26
+ end
27
+
28
+ # Running sessions of the account, oldest first.
15
29
  # GET /sessions
16
- # @param params [Hash] optional filter params
17
- # @return [OctaSpace::Response]
18
- def list(**params)
19
- get("/sessions", params:)
30
+ # @return [Array<OctaSpace::Types::Session>] ComputeSession, RenderSession or
31
+ # VpnSession, or a plain Session for a service this SDK does not know
32
+ def list
33
+ Array(get_raw("/sessions").data).map { |item| Types::Session.build(item) }
34
+ end
35
+
36
+ # A running session.
37
+ # GET /services/{uuid}/info
38
+ #
39
+ # Raises {OctaSpace::NotFoundError} when it has stopped or never existed,
40
+ # and {OctaSpace::ValidationError} for a malformed uuid.
41
+ # @param uuid [String]
42
+ # @return [OctaSpace::Types::Session]
43
+ def get(uuid)
44
+ Types::Session.build(get_raw(session_path(uuid, "info")).data)
45
+ end
46
+
47
+ # System log and latest container output of a running compute session.
48
+ # GET /services/{uuid}/logs
49
+ #
50
+ # Render and VPN sessions have no logs, and a stopped session's logs are
51
+ # gone: these raise {OctaSpace::NotFoundError}.
52
+ # @param uuid [String]
53
+ # @param tail [Integer, nil] last lines of container output, 1..1000 (default 200)
54
+ # @return [OctaSpace::Types::SessionLogs]
55
+ def logs(uuid, tail: nil)
56
+ Types::SessionLogs.new(get_raw(session_path(uuid, "logs"), params: {tail: tail}).data)
57
+ end
58
+
59
+ # Stops a session.
60
+ # POST /services/{uuid}/stop
61
+ #
62
+ # Stopping is asynchronous: the session is gone once {#get} raises
63
+ # NotFoundError (see {#wait_stopped}). Repeating the call while the
64
+ # session is stopping is harmless, so it is retried on transient errors.
65
+ # A session stopped before its +min_rent_minutes+ is charged base and
66
+ # storage for that long.
67
+ # @param uuid [String]
68
+ # @return [String] the session uuid
69
+ def stop(uuid)
70
+ response = post(session_path(uuid, "stop"), idempotent: true)
71
+ response.data.is_a?(Hash) ? response.data.fetch("uuid", uuid) : uuid
72
+ end
73
+
74
+ # Polls the session until its status is "ready" and returns it.
75
+ #
76
+ # After +compute.restart+ the session may still report "ready" for a
77
+ # moment: wait until it leaves "ready" first if you need to observe the
78
+ # restart finishing.
79
+ #
80
+ # @param uuid [String]
81
+ # @param timeout [Numeric, nil] seconds; nil waits indefinitely
82
+ # @param interval [Numeric] seconds between polls
83
+ # @yieldparam session [OctaSpace::Types::Session] every polled state (progress reporting)
84
+ # @return [OctaSpace::Types::Session]
85
+ # @raise [OctaSpace::SessionStoppedError] the session stopped meanwhile
86
+ # @raise [OctaSpace::WaitTimeoutError] the timeout ran out
87
+ def wait_ready(uuid, timeout: nil, interval: DEFAULT_WAIT_INTERVAL)
88
+ poll(timeout, interval) do
89
+ session = begin
90
+ get(uuid)
91
+ rescue NotFoundError => e
92
+ raise SessionStoppedError.new("Session #{uuid} stopped before it became ready: #{e.message}", response: e.response)
93
+ end
94
+ yield session if block_given?
95
+ session if session.ready?
96
+ end
97
+ end
98
+
99
+ # Polls until the API no longer reports the session (404), i.e. it has
100
+ # stopped. Returns at once for a session that is already gone.
101
+ #
102
+ # @param uuid [String]
103
+ # @param timeout [Numeric, nil] seconds; nil waits indefinitely
104
+ # @param interval [Numeric] seconds between polls
105
+ # @return [true]
106
+ # @raise [OctaSpace::WaitTimeoutError] the timeout ran out
107
+ def wait_stopped(uuid, timeout: nil, interval: DEFAULT_WAIT_INTERVAL)
108
+ poll(timeout, interval) do
109
+ get(uuid)
110
+ nil
111
+ rescue NotFoundError
112
+ true
113
+ end
114
+ end
115
+
116
+ private
117
+
118
+ def get_raw(path, **opts) = transport.get(path, **opts)
119
+
120
+ def session_path(uuid, action) = "/services/#{encode(uuid)}/#{action}"
121
+
122
+ def poll(timeout, interval)
123
+ deadline = timeout && (monotonic + timeout)
124
+ loop do
125
+ result = yield
126
+ return result if result
127
+ if deadline && monotonic + interval > deadline
128
+ raise WaitTimeoutError, "Gave up waiting after #{timeout} seconds"
129
+ end
130
+
131
+ @sleeper.call(interval)
132
+ end
20
133
  end
134
+
135
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
21
136
  end
22
137
  end
23
138
  end