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,57 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OctaSpace
4
+ module Resources
5
+ # GPU market and mining statistics; no API key needed
6
+ #
7
+ # @example
8
+ # client.stats.gpu_current.gpus.first.rented_price.p50
9
+ # client.stats.gpu_history(gpu_name: "NVIDIA GeForce RTX 4090", from: Time.now - 7 * 86_400)
10
+ # .fetch("NVIDIA GeForce RTX 4090").points
11
+ class Stats < Base
12
+ # GPU models on the market now, most common first.
13
+ # GET /stats/gpu/current
14
+ # @param verified [String, Symbol, nil] "all" (default), "yes" or "no"
15
+ # @return [OctaSpace::Types::GpuMarket]
16
+ def gpu_current(verified: nil)
17
+ Types::GpuMarket.new(get_public("/stats/gpu/current", verified: verified))
18
+ end
19
+
20
+ # GPU market over time, by model. Defaults to the last day with hourly
21
+ # points. Invalid ranges (step < 300, too many points, from after to)
22
+ # raise {OctaSpace::ValidationError}.
23
+ # GET /stats/gpu/history
24
+ #
25
+ # @param gpu_name [String, Array<String>, nil] model name(s), or "all"
26
+ # @param verified [String, Symbol, nil] "all", "yes" or "no"
27
+ # @param from [Time, Integer, nil] range start (Unix seconds); the API's +start+
28
+ # @param to [Time, Integer, nil] range end (Unix seconds); the API's +end+
29
+ # @param step [Integer, nil] seconds between points, at least 300 (default 3600)
30
+ # @return [Hash{String=>OctaSpace::Types::GpuHistory}] by model name
31
+ def gpu_history(gpu_name: nil, verified: nil, from: nil, to: nil, step: nil)
32
+ data = get_public("/stats/gpu/history",
33
+ gpu_name: gpu_name.is_a?(Array) ? gpu_name.join(",") : gpu_name,
34
+ verified: verified, start: unix(from), end: unix(to), step: step)
35
+ data.to_h.transform_values { |history| Types::GpuHistory.wrap(history) }
36
+ end
37
+
38
+ # GPUs by city and model (GeoIP), without per-node detail.
39
+ # GET /stats/gpu/locations
40
+ # @return [Array<OctaSpace::Types::GpuLocation>]
41
+ def gpu_locations
42
+ Types::GpuLocation.wrap_all(get_public("/stats/gpu/locations"))
43
+ end
44
+
45
+ # What the platform's mining sessions run: miners, algorithms and pools,
46
+ # most used first, and the miners per day.
47
+ # GET /stats/mining
48
+ #
49
+ # @param role [String, Symbol, nil] "gpu" (default) or "cpu"
50
+ # @param days [Integer, nil] days back, today included, 1..365 (default 30)
51
+ # @return [OctaSpace::Types::MiningUsage]
52
+ def mining(role: nil, days: nil)
53
+ Types::MiningUsage.new(get_public("/stats/mining", role: role, days: days))
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module OctaSpace
4
+ module Resources
5
+ # VPN nodes: listing and start.
6
+ #
7
+ # @example
8
+ # node = client.vpn.list.select { |n| n.supports?(:wg) }.min_by(&:traffic_price)
9
+ # uuid = client.vpn.start(node_number: node.node_number, subkind: "wg")
10
+ # client.sessions.wait_ready(uuid).config # => WireGuard config file
11
+ class Vpn < Base
12
+ # Protocols a VPN session can use: WireGuard, AmneziaWG, VLESS Reality
13
+ # and an HTTP proxy with a login
14
+ PROTOCOLS = %w[wg awg reality http_proxy].freeze
15
+
16
+ # Nodes offered for VPN.
17
+ # GET /services/vpn
18
+ #
19
+ # Works without an API key, but is then refreshed about once an hour;
20
+ # with a key it is at most 10 seconds old.
21
+ # @return [Array<OctaSpace::Types::VpnMachine>]
22
+ def list
23
+ Types::VpnMachine.wrap_all(JsonNull.null_strings!(Array(get("/services/vpn", auth: :optional).data)))
24
+ end
25
+
26
+ # Starts a VPN session, billed by traffic until stopped.
27
+ # POST /services/vpn
28
+ #
29
+ # Pick +subkind+ from the node's +protocols+: a protocol the node did not
30
+ # pass its connection check for is refused. You can have one VPN session
31
+ # per node. Once +client.sessions.wait_ready+ returns the session, its
32
+ # +config+ is what the client connects with. An +http_proxy+ session
33
+ # accepts connections only from the IP address that started it.
34
+ #
35
+ # Raises {OctaSpace::ValidationError} when the start is refused, for
36
+ # example "Insufficient balance", "Node not found", "You already have a
37
+ # VPN session on this node" or "Node's VPN did not pass the connection
38
+ # check". Never retried automatically.
39
+ #
40
+ # @param node_number [String] node number from {#list}
41
+ # @param subkind [String, Symbol] one of {PROTOCOLS}
42
+ # @return [String] the session uuid
43
+ def start(node_number:, subkind:)
44
+ post("/services/vpn", body: {node_number: node_number, subkind: subkind.to_s}).data.fetch("uuid")
45
+ end
46
+ end
47
+ end
48
+ end
@@ -1,17 +1,53 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "time"
4
+
3
5
  module OctaSpace
4
- # Wraps a raw Faraday response, providing a stable SDK interface
6
+ # Rate limit state reported by the API in the +RateLimit-Limit+,
7
+ # +RateLimit-Remaining+ and +RateLimit-Reset+ headers.
8
+ #
9
+ # The API keeps separate windows (anonymous per IP, authenticated per
10
+ # account, and a stricter one for starting and restarting services), so the
11
+ # values describe the window of the request they came from. When a request
12
+ # is refused with 429, prefer {ApiError#retry_after}: a per-session cooldown
13
+ # can demand a longer wait than the window reset.
14
+ RateLimit = Data.define(:limit, :remaining, :reset) do
15
+ # @param headers [Hash] response headers (case-insensitive lookup)
16
+ # @return [RateLimit, nil] nil when no header is present or one is not an integer
17
+ def self.from_headers(headers)
18
+ values = %w[limit remaining reset].to_h do |name|
19
+ raw = headers["ratelimit-#{name}"].to_s.strip
20
+ return nil unless raw.empty? || raw.match?(/\A\d+\z/)
21
+
22
+ [name.to_sym, raw.empty? ? nil : raw.to_i]
23
+ end
24
+ values.values.all?(&:nil?) ? nil : new(**values)
25
+ end
26
+ end
27
+
28
+ # An HTTP response of the API, with the JSON body already parsed
5
29
  class Response
6
- attr_reader :status, :headers, :body, :data
7
-
8
- # @param faraday_response [Faraday::Response]
9
- def initialize(faraday_response)
10
- @status = faraday_response.status
11
- @headers = faraday_response.headers
12
- @body = faraday_response.body
13
- # Faraday :json middleware parses JSON body into a Hash/Array automatically
14
- @data = faraday_response.body
30
+ # @return [Integer] HTTP status
31
+ attr_reader :status
32
+
33
+ # @return [Hash] response headers (case-insensitive when built by the SDK transport)
34
+ attr_reader :headers
35
+
36
+ # @return [String] raw response body
37
+ attr_reader :body
38
+
39
+ # @return [Hash, Array, nil] parsed JSON body; nil for an empty body (e.g. 202/204)
40
+ attr_reader :data
41
+
42
+ # @param status [Integer]
43
+ # @param headers [Hash]
44
+ # @param body [String, nil] raw body
45
+ # @param data [Hash, Array, nil] parsed JSON body
46
+ def initialize(status:, headers: {}, body: nil, data: nil)
47
+ @status = status
48
+ @headers = headers
49
+ @body = body.to_s
50
+ @data = data
15
51
  end
16
52
 
17
53
  # @return [Boolean] true for 2xx status codes
@@ -29,8 +65,22 @@ module OctaSpace
29
65
  # @return [String, nil] X-Request-Id header value
30
66
  def request_id = headers["x-request-id"]
31
67
 
32
- # @return [Integer, nil] Retry-After header value in seconds
33
- def retry_after = headers["retry-after"]&.to_i
68
+ # Retry-After header as whole seconds: delta-seconds (a fractional value is
69
+ # rounded up) or an HTTP date.
70
+ # @return [Integer, nil]
71
+ def retry_after
72
+ raw = headers["retry-after"].to_s.strip
73
+ return nil if raw.empty?
74
+ return raw.to_f.ceil if raw.match?(/\A\d+(\.\d+)?\z/)
75
+ return nil unless raw.match?(/\A[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT\z/)
76
+
77
+ [(Time.httpdate(raw) - Time.now).ceil, 0].max
78
+ rescue ArgumentError
79
+ nil
80
+ end
81
+
82
+ # @return [OctaSpace::RateLimit, nil] values of the RateLimit-* headers
83
+ def rate_limit = RateLimit.from_headers(headers)
34
84
 
35
85
  def to_s
36
86
  "#<OctaSpace::Response status=#{status}>"
@@ -5,47 +5,47 @@ module OctaSpace
5
5
  # Abstract base class for HTTP transports
6
6
  #
7
7
  # Concrete implementations: FaradayTransport (standard) and
8
- # PersistentTransport (keep-alive with connection pooling).
8
+ # PersistentTransport (keep-alive with connection pooling). A custom
9
+ # transport (e.g. for tests) only needs to implement {#request}.
9
10
  class Base
10
- # @param path [String]
11
- # @param params [Hash]
12
- # @param headers [Hash]
11
+ # Perform a request and return the response, or raise an OctaSpace::Error.
12
+ #
13
+ # @param method [Symbol] :get, :post, :patch, :put or :delete
14
+ # @param path [String] API path, e.g. "/services/compute"
15
+ # @param params [Hash] query parameters (nil values are dropped)
16
+ # @param body [Hash, Array, nil] JSON body
17
+ # @param auth [Symbol] :required (raise AuthenticationError without a key),
18
+ # :optional (send the key when configured) or :none (never send it)
19
+ # @param idempotent [Boolean] allow retries for a non-GET request the API
20
+ # documents as idempotent
13
21
  # @return [OctaSpace::Response]
14
- def get(path, params: {}, headers: {})
15
- raise NotImplementedError, "#{self.class}#get not implemented"
22
+ def request(method, path, params: {}, body: nil, auth: :required, idempotent: false)
23
+ raise NotImplementedError, "#{self.class}#request not implemented"
16
24
  end
17
25
 
18
- # @param path [String]
19
- # @param body [Hash, nil]
20
- # @param headers [Hash]
21
- # @return [OctaSpace::Response]
22
- def post(path, body: nil, headers: {})
23
- raise NotImplementedError, "#{self.class}#post not implemented"
26
+ def get(path, params: {}, auth: :required)
27
+ request(:get, path, params: params, auth: auth)
24
28
  end
25
29
 
26
- # @param path [String]
27
- # @param body [Hash, nil]
28
- # @param headers [Hash]
29
- # @return [OctaSpace::Response]
30
- def put(path, body: nil, headers: {})
31
- raise NotImplementedError, "#{self.class}#put not implemented"
30
+ def post(path, body: nil, auth: :required, idempotent: false)
31
+ request(:post, path, body: body, auth: auth, idempotent: idempotent)
32
32
  end
33
33
 
34
- # @param path [String]
35
- # @param body [Hash, nil]
36
- # @param headers [Hash]
37
- # @return [OctaSpace::Response]
38
- def patch(path, body: nil, headers: {})
39
- raise NotImplementedError, "#{self.class}#patch not implemented"
34
+ def patch(path, body: nil, auth: :required)
35
+ request(:patch, path, body: body, auth: auth)
40
36
  end
41
37
 
42
- # @param path [String]
43
- # @param params [Hash]
44
- # @param headers [Hash]
45
- # @return [OctaSpace::Response]
46
- def delete(path, params: {}, headers: {})
47
- raise NotImplementedError, "#{self.class}#delete not implemented"
38
+ def put(path, body: nil, auth: :required)
39
+ request(:put, path, body: body, auth: auth)
48
40
  end
41
+
42
+ def delete(path, params: {}, auth: :required)
43
+ request(:delete, path, params: params, auth: auth)
44
+ end
45
+
46
+ # @return [OctaSpace::RateLimit, nil] rate limit state of the most recent
47
+ # response that carried RateLimit-* headers
48
+ def rate_limit = nil
49
49
  end
50
50
  end
51
51
  end
@@ -1,116 +1,194 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "faraday"
4
- require "faraday/retry"
4
+ require "json"
5
5
 
6
6
  module OctaSpace
7
7
  module Transport
8
8
  # Standard HTTP transport built on Faraday
9
9
  #
10
- # Features:
11
- # - Automatic JSON request/response encoding
12
- # - Configurable retry with exponential backoff + jitter
13
- # - URL rotation / failover across multiple base_urls
14
- # - on_request / on_response hooks
15
- # - Typed exception hierarchy mapped from HTTP status codes
10
+ # - +Authorization: Bearer <api_key>+ per endpoint auth mode
11
+ # - JSON request encoding and response parsing
12
+ # - Retries with exponential backoff and jitter for GET, PUT, DELETE and
13
+ # idempotent requests only, honouring Retry-After up to {Configuration#max_retry_after}
14
+ # - Failover across several base URLs for GET requests on network errors;
15
+ # requests that change state are never sent to a second host
16
+ # - on_request / on_response hooks, one log line per request
17
+ # - Typed exceptions mapped from HTTP status codes
16
18
  #
17
19
  # @example
18
20
  # config = OctaSpace::Configuration.new
19
- # config.api_key = "my_key"
21
+ # config.api_key = "octa_ak_..."
20
22
  # transport = OctaSpace::Transport::FaradayTransport.new(config)
21
- # response = transport.get("/nodes")
23
+ # transport.get("/accounts/balance").data
22
24
  class FaradayTransport < Base
23
- RETRY_STATUSES = [408, 429, 500, 502, 503, 504].freeze
24
- RETRY_METHODS = %i[get head options put delete].freeze
25
+ # Statuses worth retrying: rate limit and transient gateway/backend failures
26
+ RETRY_STATUSES = [429, 502, 503, 504].freeze
25
27
 
26
- def initialize(config)
27
- @config = config
28
- @rotator = (config.urls.size > 1) ? Middleware::UrlRotator.new(config.urls) : nil
29
- # Single URL: build one connection upfront for reuse
30
- @connection = build_connection(config.urls.first) unless @rotator
31
- end
28
+ # Methods that are safe to repeat
29
+ IDEMPOTENT_METHODS = %i[get put delete].freeze
32
30
 
33
- def get(path, params: {}, headers: {})
34
- request(:get, path, params: params, headers: headers)
35
- end
31
+ # Header that tells the API which app is calling
32
+ APP_HEADER = "X-OCTA-APP"
36
33
 
37
- def post(path, body: nil, headers: {})
38
- request(:post, path, body: body, headers: headers)
39
- end
34
+ # Value of {APP_HEADER}
35
+ APP_NAME = "ruby-sdk"
40
36
 
41
- def put(path, body: nil, headers: {})
42
- request(:put, path, body: body, headers: headers)
43
- end
37
+ # @param config [OctaSpace::Configuration]
38
+ # @param sleeper [#call] waits the given number of seconds between retries
39
+ def initialize(config, sleeper: ->(seconds) { sleep(seconds) })
40
+ @config = config
41
+ @urls = config.urls.freeze
42
+ raise ConfigurationError, "At least one base URL is required" if @urls.empty?
43
+
44
+ @rotator = (@urls.size > 1) ? Middleware::UrlRotator.new(@urls) : nil
45
+ @sleeper = sleeper
46
+ @connections = {}
47
+ @mutex = Mutex.new
48
+ @rate_limit = nil
49
+ end
50
+
51
+ # (see Base#request)
52
+ def request(method, path, params: {}, body: nil, auth: :required, idempotent: false)
53
+ method = method.to_sym
54
+ headers = build_headers(method, path, auth, body)
55
+ retryable = IDEMPOTENT_METHODS.include?(method) || idempotent
56
+ attempt = 0
57
+
58
+ begin
59
+ with_failover(method) do |url|
60
+ perform(url, method, path, params: params, body: body, headers: headers, attempt: attempt)
61
+ end
62
+ rescue NetworkError, ApiError => e
63
+ delay = (retryable && attempt < config.max_retries) ? retry_delay(e, attempt) : nil
64
+ raise if delay.nil?
44
65
 
45
- def patch(path, body: nil, headers: {})
46
- request(:patch, path, body: body, headers: headers)
66
+ @sleeper.call(delay) if delay.positive?
67
+ attempt += 1
68
+ retry
69
+ end
47
70
  end
48
71
 
49
- def delete(path, params: {}, headers: {})
50
- request(:delete, path, params: params, headers: headers)
72
+ # (see Base#rate_limit)
73
+ def rate_limit = @mutex.synchronize { @rate_limit }
74
+
75
+ # @return [Hash] transport diagnostics
76
+ def transport_stats
77
+ stats = {mode: :standard, urls: @urls}
78
+ stats[:rotator] = @rotator.stats if @rotator
79
+ stats
51
80
  end
52
81
 
53
82
  private
54
83
 
55
84
  attr_reader :config
56
85
 
57
- # Execute HTTP request with optional URL rotation
58
- def request(method, path, params: {}, body: nil, headers: {})
59
- invoke_hook(config.on_request, {method: method, path: path, params: params})
86
+ # GET requests try every URL in rotation order on network errors; other
87
+ # methods go to a single URL so a request that changes state (and may
88
+ # have reached the server before a timeout) is never sent twice.
89
+ def with_failover(method)
90
+ first = @rotator ? @rotator.next_url : @urls.first
91
+ urls = (method == :get) ? [first, *(@urls - [first])] : [first]
92
+ last_error = nil
60
93
 
61
- with_failover do |base_url|
62
- conn = @rotator ? build_connection(base_url) : @connection
63
- begin
64
- faraday_resp = execute(conn, method, path, params: params, body: body, headers: headers)
65
- rescue Faraday::ConnectionFailed => e
66
- raise ConnectionError, e.message
67
- rescue Faraday::TimeoutError => e
68
- raise TimeoutError, e.message
69
- end
70
- response = Response.new(faraday_resp)
71
- invoke_hook(config.on_response, response)
72
- raise OctaSpace.error_for(response) if response.error?
73
- response
94
+ urls.each do |url|
95
+ response = yield(url)
96
+ @rotator&.mark_success(url)
97
+ return response
98
+ rescue NetworkError => e
99
+ @rotator&.mark_failed(url)
100
+ last_error = e
74
101
  end
102
+
103
+ raise last_error
75
104
  end
76
105
 
77
- # Execute a single Faraday request
78
- def execute(conn, method, path, params: {}, body: nil, headers: {})
79
- conn.public_send(method, path) do |req|
80
- req.headers.merge!(default_headers.merge(headers))
81
- req.params.merge!(params) if params.any?
82
- req.body = body.to_json if body
106
+ def perform(base_url, method, path, params:, body:, headers:, attempt:)
107
+ query = params.to_h.compact
108
+ invoke_hook(config.on_request,
109
+ {method: method, url: "#{base_url}#{path}", path: path, params: query, attempt: attempt})
110
+
111
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
112
+ raw = begin
113
+ execute(connection_for(base_url), method, path.delete_prefix("/"),
114
+ query: query, payload: body.nil? ? nil : JSON.generate(body), headers: headers)
115
+ rescue Faraday::TimeoutError => e
116
+ log(method, base_url, path, "timeout", started)
117
+ raise TimeoutError, "Request timed out: #{e.message}"
118
+ rescue Faraday::ConnectionFailed, Faraday::SSLError => e
119
+ log(method, base_url, path, "connection failed", started)
120
+ raise ConnectionError, e.message
83
121
  end
84
- end
122
+ log(method, base_url, path, raw.status, started)
85
123
 
86
- # Try each URL in rotation; mark failures and retry
87
- def with_failover(&block)
88
- urls = @rotator ? @config.urls.dup : [nil]
89
- tried = []
90
- last_error = nil
124
+ response = build_response(raw)
125
+ if (rate_limit = response.rate_limit)
126
+ @mutex.synchronize { @rate_limit = rate_limit }
127
+ end
128
+ invoke_hook(config.on_response, response)
129
+ raise OctaSpace.error_for(response, api_key: headers.key?("Authorization") ? config.api_key : nil) if response.error?
91
130
 
92
- urls.each do |url|
93
- next if tried.include?(url)
94
- tried << url
131
+ response
132
+ end
133
+
134
+ # Overridden by PersistentTransport to run the request on a pooled connection
135
+ def execute(conn, method, path, query:, payload:, headers:)
136
+ conn.run_request(method, path, payload, headers) do |req|
137
+ req.params.update(query) unless query.empty?
138
+ end
139
+ end
95
140
 
141
+ def build_response(raw)
142
+ text = raw.body.to_s
143
+ data = nil
144
+ unless text.strip.empty?
96
145
  begin
97
- return yield(url)
98
- rescue ConnectionError, TimeoutError => e
99
- last_error = e
100
- @rotator&.mark_failed(url)
146
+ data = JSON.parse(text)
147
+ rescue JSON::ParserError
148
+ # E.g. a proxy or captive portal answering 200 with an HTML page.
149
+ if (200..299).cover?(raw.status)
150
+ response = Response.new(status: raw.status, headers: raw.headers, body: text)
151
+ raise ApiError.new("Response is not valid JSON (status #{raw.status})", response: response)
152
+ end
101
153
  end
102
154
  end
155
+ Response.new(status: raw.status, headers: raw.headers, body: text, data: data)
156
+ end
157
+
158
+ def build_headers(method, path, auth, body)
159
+ headers = {"User-Agent" => config.user_agent, "Accept" => "application/json", APP_HEADER => APP_NAME}
160
+ headers["Content-Type"] = "application/json" unless body.nil?
161
+
162
+ unless auth == :none
163
+ if config.api_key?
164
+ headers["Authorization"] = "Bearer #{config.api_key}"
165
+ elsif auth == :required
166
+ raise AuthenticationError,
167
+ "api_key is required for #{method.upcase} #{path}: pass an API key " \
168
+ "(#{API_KEY_PREFIX}…) from Account → Credentials → API Keys in the OctaSpace dashboard"
169
+ end
170
+ end
171
+ headers
172
+ end
173
+
174
+ # Seconds to wait before the next attempt, or nil when the error must be raised
175
+ def retry_delay(error, attempt)
176
+ return nil if error.is_a?(ApiError) && !RETRY_STATUSES.include?(error.status)
177
+
178
+ retry_after = error.is_a?(ApiError) ? error.retry_after : nil
179
+ return nil if retry_after && retry_after > config.max_retry_after
180
+ return retry_after if retry_after
181
+
182
+ cap = [config.max_retry_interval.to_f, config.retry_interval.to_f * (config.backoff_factor.to_f**attempt)].min
183
+ rand * cap
184
+ end
103
185
 
104
- raise last_error || ConnectionError.new("All API endpoints unavailable")
186
+ def connection_for(base_url)
187
+ @mutex.synchronize { @connections[base_url] ||= build_connection(base_url) }
105
188
  end
106
189
 
107
- # Build a Faraday connection for a given base URL
108
190
  def build_connection(base_url)
109
191
  Faraday.new(url: base_url, request: request_options, ssl: ssl_options) do |f|
110
- f.request :json
111
- f.request :retry, retry_options
112
- f.response :json, content_type: /\bjson/
113
- f.response :logger, config.logger, {headers: true, bodies: false} if config.logger
114
192
  configure_adapter(f)
115
193
  end
116
194
  end
@@ -120,26 +198,6 @@ module OctaSpace
120
198
  builder.adapter :net_http
121
199
  end
122
200
 
123
- def default_headers
124
- headers = {
125
- "User-Agent" => config.user_agent,
126
- "Accept" => "application/json"
127
- }
128
- headers["Authorization"] = config.api_key if config.api_key && !config.api_key.empty?
129
- headers
130
- end
131
-
132
- def retry_options
133
- {
134
- max: config.max_retries,
135
- interval: config.retry_interval,
136
- interval_randomness: 0.5,
137
- backoff_factor: config.backoff_factor,
138
- retry_statuses: RETRY_STATUSES,
139
- methods: RETRY_METHODS
140
- }
141
- end
142
-
143
201
  def request_options
144
202
  {
145
203
  open_timeout: config.open_timeout,
@@ -152,6 +210,14 @@ module OctaSpace
152
210
  {verify: config.ssl_verify}
153
211
  end
154
212
 
213
+ def log(method, base_url, path, outcome, started)
214
+ return unless config.logger
215
+
216
+ ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
217
+ config.logger.public_send(config.log_level || :info,
218
+ "[OctaSpace] #{method.upcase} #{base_url}#{path} -> #{outcome} (#{ms} ms)")
219
+ end
220
+
155
221
  def invoke_hook(hook, *args)
156
222
  hook&.call(*args)
157
223
  end