Class: DockerEngineRuby::Internal::Transport::BaseClient Abstract Private

Inherits:
Object
  • Object
show all
Extended by:
Util::SorbetRuntimeSupport
Defined in:
lib/docker_engine_ruby/internal/transport/base_client.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

This class is abstract.

Direct Known Subclasses

Client

Constant Summary collapse

MAX_REDIRECTS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

from whatwg fetch spec

20
REDIRECT_STATUSES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

[301, 302, 303, 307, 308].freeze
PLATFORM_HEADERS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

rubocop:disable Style/MutableConstant

{
  "x-stainless-arch" => DockerEngineRuby::Internal::Util.arch,
  "x-stainless-lang" => "ruby",
  "x-stainless-os" => DockerEngineRuby::Internal::Util.os,
  "x-stainless-package-version" => DockerEngineRuby::VERSION,
  "x-stainless-runtime" => ::RUBY_ENGINE,
  "x-stainless-runtime-version" => ::RUBY_ENGINE_VERSION
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util::SorbetRuntimeSupport

const_missing, define_sorbet_constant!, sorbet_constant_defined?, to_sorbet_type, to_sorbet_type

Constructor Details

#initialize(base_url:, timeout: 0.0, max_retries: 0, initial_retry_delay: 0.0, max_retry_delay: 0.0, headers: {}, idempotency_header: nil, tls_verify_peer: true, tls_ca_cert_path: nil, tls_client_cert_path: nil, tls_client_key_path: nil) ⇒ BaseClient

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of BaseClient.

Parameters:

  • base_url (String)
  • timeout (Float) (defaults to: 0.0)
  • max_retries (Integer) (defaults to: 0)
  • initial_retry_delay (Float) (defaults to: 0.0)
  • max_retry_delay (Float) (defaults to: 0.0)
  • headers (Hash{String=>String, Integer, Array<String, Integer, nil>, nil}) (defaults to: {})
  • idempotency_header (String, nil) (defaults to: nil)
  • tls_verify_peer (Boolean) (defaults to: true)
  • tls_ca_cert_path (String, nil) (defaults to: nil)
  • tls_client_cert_path (String, nil) (defaults to: nil)
  • tls_client_key_path (String, nil) (defaults to: nil)


204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 204

def initialize(
  base_url:,
  timeout: 0.0,
  max_retries: 0,
  initial_retry_delay: 0.0,
  max_retry_delay: 0.0,
  headers: {},
  idempotency_header: nil,
  tls_verify_peer: true,
  tls_ca_cert_path: nil,
  tls_client_cert_path: nil,
  tls_client_key_path: nil
)
  parsed_base_url = DockerEngineRuby::Internal::Util.parse_uri(base_url)
  @unix_socket_path = parsed_base_url[:scheme] == "unix" ? parsed_base_url[:path] : nil
  if parsed_base_url[:scheme] == "unix" && @unix_socket_path.to_s.empty?
    raise ArgumentError.new("base_url unix:// must include an absolute socket path")
  end
  @requester = DockerEngineRuby::Internal::Transport::PooledNetRequester.new(
    unix_socket_path: @unix_socket_path,
    tls_verify_peer: tls_verify_peer,
    tls_ca_cert_path: tls_ca_cert_path,
    tls_client_cert_path: tls_client_cert_path,
    tls_client_key_path: tls_client_key_path
  )
  @headers = DockerEngineRuby::Internal::Util.normalized_headers(
    self.class::PLATFORM_HEADERS,
    {
      "accept" => "application/json",
      "content-type" => "application/json",
      "user-agent" => user_agent
    },
    headers
  )
  @base_url_components =
    if @unix_socket_path
      DockerEngineRuby::Internal::Util.parse_uri("http://localhost")
    else
      parsed_base_url
    end
  @base_url = base_url
  @idempotency_header = idempotency_header&.to_s&.downcase
  @timeout = timeout
  @max_retries = max_retries
  @initial_retry_delay = initial_retry_delay
  @max_retry_delay = max_retry_delay
end

Instance Attribute Details

#base_urlURI::Generic (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (URI::Generic)


167
168
169
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 167

def base_url
  @base_url
end

#headersHash{String=>String} (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Hash{String=>String})


182
183
184
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 182

def headers
  @headers
end

#idempotency_headerString? (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (String, nil)


185
186
187
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 185

def idempotency_header
  @idempotency_header
end

#initial_retry_delayFloat (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Float)


176
177
178
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 176

def initial_retry_delay
  @initial_retry_delay
end

#max_retriesInteger (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Integer)


173
174
175
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 173

def max_retries
  @max_retries
end

#max_retry_delayFloat (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Float)


179
180
181
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 179

def max_retry_delay
  @max_retry_delay
end

#requesterDockerEngineRuby::Internal::Transport::PooledNetRequester (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



189
190
191
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 189

def requester
  @requester
end

#timeoutFloat (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Float)


170
171
172
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 170

def timeout
  @timeout
end

Class Method Details

.follow_redirect(request, status:, response_headers:) ⇒ Hash{Symbol=>Object}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • request (Hash{Symbol=>Object})

    .

    @option request [Symbol] :method

    @option request [URI::Generic] :url

    @option request [HashString=>String] :headers

    @option request [Object] :body

    @option request [Integer] :max_retries

    @option request [Float] :timeout

  • status (Integer)
  • response_headers (Hash{String=>String})

Returns:

  • (Hash{Symbol=>Object})


101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 101

def follow_redirect(request, status:, response_headers:)
  method, url, headers = request.fetch_values(:method, :url, :headers)
  location =
    Kernel.then do
      URI.join(url, response_headers["location"])
    rescue ArgumentError
      message = "Server responded with status #{status} but no valid location header."
      raise DockerEngineRuby::Errors::APIConnectionError.new(
        url: url,
        response: response_headers,
        message: message
      )
    end

  request = {**request, url: location}

  case [url.scheme, location.scheme]
  in ["https", "http"]
    message = "Tried to redirect to a insecure URL"
    raise DockerEngineRuby::Errors::APIConnectionError.new(
      url: url,
      response: response_headers,
      message: message
    )
  else
    nil
  end

  # from whatwg fetch spec
  case [status, method]
  in [301 | 302, :post] | [303, _]
    drop = %w[content-encoding content-language content-length content-location content-type]
    request = {
      **request,
      method: method == :head ? :head : :get,
      headers: headers.except(*drop),
      body: nil
    }
  else
  end

  # from undici
  if DockerEngineRuby::Internal::Util.uri_origin(url) != DockerEngineRuby::Internal::Util.uri_origin(location)
    drop = %w[authorization cookie host proxy-authorization]
    request = {**request, headers: request.fetch(:headers).except(*drop)}
  end

  request
end

.reap_connection!(status, stream:) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:



155
156
157
158
159
160
161
162
163
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 155

def reap_connection!(status, stream:)
  case status
  in (..199) | (300..499)
    stream&.each { next }
  in DockerEngineRuby::Errors::APIConnectionError | (500..)
    DockerEngineRuby::Internal::Util.close_fused!(stream)
  else
  end
end

.redirect_status?(status) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • status (Integer)

Returns:

  • (Boolean)


76
77
78
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 76

def redirect_status?(status)
  REDIRECT_STATUSES.include?(status)
end

.should_retry?(status, headers:) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • status (Integer)
  • headers (Hash{String=>String})

Returns:

  • (Boolean)


54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 54

def should_retry?(status, headers:)
  coerced = DockerEngineRuby::Internal::Util.coerce_boolean(headers["x-should-retry"])
  case [coerced, status]
  in [true | false, _]
    coerced
  in [_, 408 | 409 | 429 | (500..)]
    # retry on:
    # 408: timeouts
    # 409: locks
    # 429: rate limits
    # 500+: unknown errors
    true
  else
    false
  end
end

.validate!(req) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • req (Hash{Symbol=>Object})

Raises:

  • (ArgumentError)


34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 34

def validate!(req)
  keys = [:method, :path, :query, :headers, :body, :unwrap, :page, :stream, :model, :options]
  case req
  in Hash
    req.each_key do |k|
      unless keys.include?(k)
        raise ArgumentError.new("Request `req` keys must be one of #{keys}, got #{k.inspect}")
      end
    end
  else
    raise ArgumentError.new("Request `req` must be a Hash or RequestOptions, got #{req.inspect}")
  end
end

Instance Method Details

#inspectString

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (String)


563
564
565
566
567
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 563

def inspect
  # rubocop:disable Layout/LineLength
  "#<#{self.class.name}:0x#{object_id.to_s(16)} base_url=#{@base_url} max_retries=#{@max_retries} timeout=#{@timeout}>"
  # rubocop:enable Layout/LineLength
end

#request(method, path, query: {}, headers: {}, body: nil, unwrap: nil, page: nil, stream: nil, model: DockerEngineRuby::Internal::Type::Unknown, options: {}) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Execute the request specified by req. This is the method that all resource methods call into.

Parameters:

  • method (Symbol)
  • path (String, Array<String>)
  • query (Hash{String=>Array<String>, String, nil}, nil)
  • headers (Hash{String=>String, Integer, Array<String, Integer, nil>, nil}, nil)
  • body (Object, nil)
  • unwrap (Symbol, Integer, Array<Symbol, Integer>, Proc, nil)
  • page (Class<DockerEngineRuby::Internal::Type::BasePage>, nil)
  • stream (Class<DockerEngineRuby::Internal::Type::BaseStream>, nil)
  • model (DockerEngineRuby::Internal::Type::Converter, Class, nil)
  • options (DockerEngineRuby::RequestOptions, Hash{Symbol=>Object}, nil)

    .

    @option options [String, nil] :idempotency_key

    @option options [HashString, nil, nil] :extra_query

    @option options [Hashnil, nil] :extra_headers

    @option options [Object, nil] :extra_body

    @option options [Integer, nil] :max_retries

    @option options [Float, nil] :timeout

Returns:

  • (Object)

Raises:



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 512

def request(req)
  self.class.validate!(req)
  model = req.fetch(:model) { DockerEngineRuby::Internal::Type::Unknown }
  opts = req[:options].to_h
  unwrap = req[:unwrap]
  DockerEngineRuby::RequestOptions.validate!(opts)
  request = build_request(req.except(:options), opts)
  url = request.fetch(:url)

  # Don't send the current retry count in the headers if the caller modified the header defaults.
  send_retry_header = request.fetch(:headers)["x-stainless-retry-count"] == "0"
  status, response, stream = send_request(
    request,
    redirect_count: 0,
    retry_count: 0,
    send_retry_header: send_retry_header
  )

  headers = DockerEngineRuby::Internal::Util.normalized_headers(response.each_header.to_h)

  # Some Docker endpoints return non-JSON streaming payloads while generated
  # resource methods intentionally model their response as `nil`.
  # In that case, drain the response body and return early.
  if model == NilClass && !req.key?(:stream) && !req.key?(:page)
    stream&.each { next }
    return nil
  end

  decoded = DockerEngineRuby::Internal::Util.decode_content(headers, stream: stream)
  case req
  in {stream: Class => st}
    st.new(
      model: model,
      url: url,
      status: status,
      headers: headers,
      response: response,
      unwrap: unwrap,
      stream: decoded
    )
  in {page: Class => page}
    page.new(client: self, req: req, headers: headers, page_data: decoded)
  else
    unwrapped = DockerEngineRuby::Internal::Util.dig(decoded, unwrap)
    DockerEngineRuby::Internal::Type::Converter.coerce(model, unwrapped)
  end
end

#send_request(request, redirect_count:, retry_count:, send_retry_header:) ⇒ Array(Integer, Net::HTTPResponse, Enumerable<String>)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • request (Hash{Symbol=>Object})

    .

    @option request [Symbol] :method

    @option request [URI::Generic] :url

    @option request [HashString=>String] :headers

    @option request [Object] :body

    @option request [Integer] :max_retries

    @option request [Float] :timeout

  • redirect_count (Integer)
  • retry_count (Integer)
  • send_retry_header (Boolean)

Returns:

  • (Array(Integer, Net::HTTPResponse, Enumerable<String>))

Raises:



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/docker_engine_ruby/internal/transport/base_client.rb', line 403

def send_request(request, redirect_count:, retry_count:, send_retry_header:)
  url, headers, max_retries, timeout = request.fetch_values(:url, :headers, :max_retries, :timeout)
  input = {**request.except(:timeout), deadline: DockerEngineRuby::Internal::Util.monotonic_secs + timeout}

  if send_retry_header
    headers["x-stainless-retry-count"] = retry_count.to_s
  end

  begin
    status, response, stream = @requester.execute(input)
  rescue DockerEngineRuby::Errors::APIConnectionError => e
    status = e
  end
  headers = DockerEngineRuby::Internal::Util.normalized_headers(response&.each_header&.to_h)

  case status
  in ..299
    [status, response, stream]
  in Integer => status if self.class.redirect_status?(status) &&
    redirect_count >= self.class::MAX_REDIRECTS
    self.class.reap_connection!(status, stream: stream)

    message = "Failed to complete the request within #{self.class::MAX_REDIRECTS} redirects."
    raise DockerEngineRuby::Errors::APIConnectionError.new(
      url: url,
      response: response,
      message: message
    )
  in Integer => status if self.class.redirect_status?(status)
    self.class.reap_connection!(status, stream: stream)

    request = self.class.follow_redirect(request, status: status, response_headers: headers)
    send_request(
      request,
      redirect_count: redirect_count + 1,
      retry_count: retry_count,
      send_retry_header: send_retry_header
    )
  in DockerEngineRuby::Errors::APIConnectionError if retry_count >= max_retries
    raise status
  in (300..) if retry_count >= max_retries || !self.class.should_retry?(status, headers: headers)
    decoded = Kernel.then do
      DockerEngineRuby::Internal::Util.decode_content(headers, stream: stream, suppress_error: true)
    ensure
      self.class.reap_connection!(status, stream: stream)
    end

    raise DockerEngineRuby::Errors::APIStatusError.for(
      url: url,
      status: status,
      headers: headers,
      body: decoded,
      request: nil,
      response: response
    )
  in (400..) | DockerEngineRuby::Errors::APIConnectionError
    self.class.reap_connection!(status, stream: stream)

    delay = retry_delay(response || {}, retry_count: retry_count)
    sleep(delay)

    send_request(
      request,
      redirect_count: redirect_count,
      retry_count: retry_count + 1,
      send_retry_header: send_retry_header
    )
  end
end