CodeSampleX

Ejemplo

faraday-net_http 3.4.4: Handle Net::HTTP socket exceptions, connection timeouts, and stream bodies in Faraday without misidentifying OpenTimeout as TimeoutError

Muestra verificada para gem faraday-net_http 3.4.4: Handle Net::HTTP socket exceptions, connection timeouts, and stream bodies in Faraday without…

sha256:897148af1287e730b9b86d1bf801ae4dffe0fd84b874c70db3904c6fc53ca0af

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
1
Entorno declarado ruby linux x64 ruby ruby rubygems

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-16
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 SKIPPED compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL
CONTAINER_RUN · rubygems@1
2026-08-18

Caso

HOW
Objetivo
Handle Net::HTTP socket exceptions, connection timeouts, and stream bodies in Faraday without misidentifying OpenTimeout as TimeoutError
Paquetes
Símbolos
  • Faraday::Adapter::NetHttp
  • Faraday::Adapter::NetHttp#call
  • Faraday::Adapter::NetHttp#create_request
  • Faraday::Adapter::NetHttp#encoded_body
  • Faraday::Adapter::NetHttp::NET_HTTP_EXCEPTIONS
Entorno
ruby
Creado
2026-08-16T17:24:37Z

Contrato

  1. assert Net::OpenTimeout raises Faraday::ConnectionFailed rather than Faraday::TimeoutError
  2. assert Net::ReadTimeout and Net::WriteTimeout raise Faraday::TimeoutError
  3. assert OpenSSL::SSL::SSLError raises Faraday::SSLError with wrapped_exception preserved
  4. assert socket and connection refusal errors raise Faraday::ConnectionFailed with wrapped_exception preserved
  5. assert streamable body responding to read populates body_stream and leaves body nil
  6. assert string body populates body and leaves body_stream nil
  7. assert HEAD request configures response_body_permitted to false
  8. assert response body encoding matches Content-Type charset and gracefully ignores invalid charsets
  9. assert nil response body is normalized to empty string
  10. assert RequestHandler correctly categorizes Net::HTTP adapter exceptions

Archivos

  • Gemfile
  • NOTES.md
  • csx.json
  • lib/request_handler.rb
  • test/contract.rb

Descargar el artefacto de código fuente (tar.gz)

Código fuente

Gemfile
# frozen_string_literal: true

source 'https://rubygems.org'

gem 'faraday', '~> 2.14'
gem 'faraday-net_http', '~> 3.4'
NOTES.md
# Notes on faraday-net_http Exception Translation and Request Processing Contracts

## Existing Solutions Found
A lookup for `pkg:gem/faraday-net_http` returned existing samples `sha256:3b76bde8...` and `sha256:0554ba15...` covering adapter option hash dropping, yield configuration blocks, and max_retries resets.

## What a Competent Model Would Have Written Instead
- Competent models routinely assume that all timeout conditions in Faraday (including connection open timeouts) raise `Faraday::TimeoutError`, writing error handling blocks like `rescue Faraday::TimeoutError`.
- In `faraday-net_http`, `Net::OpenTimeout` is explicitly grouped into `NET_HTTP_EXCEPTIONS` and rescued by the inner handler, raising `Faraday::ConnectionFailed` rather than `Faraday::TimeoutError`.
- Models also frequently assume that passing a streamable IO body populates `request.body` instead of `request.body_stream`, or that `encoded_body` returns `nil` when the response body is empty.

## Failure Mode (Loud vs Silent)
- Rescuing only `Faraday::TimeoutError` when handling connection open timeouts fails loudly at runtime with an uncaught `Faraday::ConnectionFailed` exception, while checking `request.body` on stream uploads fails silently with `nil`.
csx.json
{"case":{"believed":"all Net::HTTP timeout conditions including connection open timeouts raise Faraday::TimeoutError","caseId":"case:sha256:d696e9da7ef1ea68ef1f30295b9c3d626ec5dc754d862d4f2bccbda339d0ec52","contract":["assert Net::OpenTimeout raises Faraday::ConnectionFailed rather than Faraday::TimeoutError","assert Net::ReadTimeout and Net::WriteTimeout raise Faraday::TimeoutError","assert OpenSSL::SSL::SSLError raises Faraday::SSLError with wrapped_exception preserved","assert socket and connection refusal errors raise Faraday::ConnectionFailed with wrapped_exception preserved","assert streamable body responding to read populates body_stream and leaves body nil","assert string body populates body and leaves body_stream nil","assert HEAD request configures response_body_permitted to false","assert response body encoding matches Content-Type charset and gracefully ignores invalid charsets","assert nil response body is normalized to empty string","assert RequestHandler correctly categorizes Net::HTTP adapter exceptions"],"goal":"Handle Net::HTTP socket exceptions, connection timeouts, and stream bodies in Faraday without misidentifying OpenTimeout as TimeoutError","kind":"HOW","packages":["pkg:gem/faraday-net_http@3.4.4"],"schemaVersion":1,"symbols":["Faraday::Adapter::NetHttp","Faraday::Adapter::NetHttp#call","Faraday::Adapter::NetHttp#create_request","Faraday::Adapter::NetHttp#encoded_body","Faraday::Adapter::NetHttp::NET_HTTP_EXCEPTIONS"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/faraday-net_http@3.4.4"],"schemaVersion":1,"symbols":["Faraday::Adapter::NetHttp","Faraday::Adapter::NetHttp#call","Faraday::Adapter::NetHttp#create_request","Faraday::Adapter::NetHttp#encoded_body","Faraday::Adapter::NetHttp::NET_HTTP_EXCEPTIONS"],"verifierAdapter":"rubygems@1"}
lib/request_handler.rb
# frozen_string_literal: true

require 'faraday'
require 'faraday/net_http'

module FaradayNetHttpSample
  # Demonstrates safe exception handling and request preparation patterns
  # when using Faraday::Adapter::NetHttp
  class RequestHandler
    attr_reader :adapter

    def initialize(adapter = Faraday::Adapter::NetHttp.new(->(env) { env }))
      @adapter = adapter
    end

    # Executes a request while categorizing exceptions according to Faraday's NetHttp adapter semantics.
    # Note: Net::OpenTimeout translates to Faraday::ConnectionFailed (not Faraday::TimeoutError).
    def execute(env)
      adapter.call(env)
    rescue Faraday::SSLError => e
      { status: :ssl_error, cause: e.wrapped_exception, error: e }
    rescue Faraday::ConnectionFailed => e
      # Catches Net::OpenTimeout as well as DNS/Socket failures and connection refusal
      { status: :connection_failed, cause: e.wrapped_exception, error: e }
    rescue Faraday::TimeoutError => e
      # Catches Net::ReadTimeout and Net::WriteTimeout
      { status: :timeout_error, cause: e.wrapped_exception, error: e }
    end

    # Builds a Net::HTTPGenericRequest through the adapter
    def build_request(env)
      adapter.send(:create_request, env)
    end

    # Decodes raw Net::HTTP response bodies respecting Content-Type charset headers
    def decode_body(http_response)
      adapter.send(:encoded_body, http_response)
    end
  end
end
test/contract.rb
# frozen_string_literal: true

require 'faraday'
require 'faraday/net_http'
require 'stringio'
require 'openssl'
require 'uri'
require_relative '../lib/request_handler'

puts "Running faraday-net_http contracts..."

# ---------------------------------------------------------------------------
# Setup helper to simulate adapter call errors
# ---------------------------------------------------------------------------
def simulate_adapter_call(adapter, exception_to_raise)
  env = Faraday::Env.new(:get, nil, URI('http://example.test/status'), Faraday::RequestOptions.new, {}, nil, nil)
  adapter.define_singleton_method(:perform_request) do |_http, _env|
    raise exception_to_raise
  end
  adapter.call(env)
end

adapter = Faraday::Adapter::NetHttp.new(->(env) { env })
handler = FaradayNetHttpSample::RequestHandler.new(adapter)

# ---------------------------------------------------------------------------
# 1. Trap: Net::OpenTimeout translates to Faraday::ConnectionFailed, NOT Faraday::TimeoutError
# ---------------------------------------------------------------------------
# Naive models assume open timeouts raise Faraday::TimeoutError.
# In faraday-net_http, Net::OpenTimeout is listed in NET_HTTP_EXCEPTIONS and rescued
# by the inner rescue block, raising Faraday::ConnectionFailed.
begin
  simulate_adapter_call(adapter, Net::OpenTimeout.new('execution expired'))
  raise "Expected call to raise an exception"
rescue Faraday::TimeoutError
  raise "Unexpected Faraday::TimeoutError: Net::OpenTimeout must raise Faraday::ConnectionFailed"
rescue Faraday::ConnectionFailed => e
  raise "Expected wrapped_exception to be Net::OpenTimeout" unless e.wrapped_exception.is_a?(Net::OpenTimeout)
  puts "✓ Net::OpenTimeout raises Faraday::ConnectionFailed (not Faraday::TimeoutError)"
end

# ---------------------------------------------------------------------------
# 2. Net::ReadTimeout and Net::WriteTimeout translate to Faraday::TimeoutError
# ---------------------------------------------------------------------------
# Net::ReadTimeout and Net::WriteTimeout are not in NET_HTTP_EXCEPTIONS, so they
# fall through to the outer rescue Timeout::Error and raise Faraday::TimeoutError.
begin
  simulate_adapter_call(adapter, Net::ReadTimeout.new('Net::ReadTimeout with http://example.test'))
  raise "Expected call to raise an exception"
rescue Faraday::ConnectionFailed
  raise "Unexpected Faraday::ConnectionFailed: Net::ReadTimeout must raise Faraday::TimeoutError"
rescue Faraday::TimeoutError => e
  raise "Expected wrapped_exception to be Net::ReadTimeout" unless e.wrapped_exception.is_a?(Net::ReadTimeout)
  puts "✓ Net::ReadTimeout raises Faraday::TimeoutError"
end

begin
  simulate_adapter_call(adapter, Net::WriteTimeout.new('Net::WriteTimeout'))
  raise "Expected call to raise an exception"
rescue Faraday::ConnectionFailed
  raise "Unexpected Faraday::ConnectionFailed: Net::WriteTimeout must raise Faraday::TimeoutError"
rescue Faraday::TimeoutError => e
  raise "Expected wrapped_exception to be Net::WriteTimeout" unless e.wrapped_exception.is_a?(Net::WriteTimeout)
  puts "✓ Net::WriteTimeout raises Faraday::TimeoutError"
end

# ---------------------------------------------------------------------------
# 3. OpenSSL::SSL::SSLError translates to Faraday::SSLError
# ---------------------------------------------------------------------------
begin
  simulate_adapter_call(adapter, OpenSSL::SSL::SSLError.new('certificate verify failed'))
  raise "Expected call to raise an exception"
rescue Faraday::SSLError => e
  raise "Expected wrapped_exception to be OpenSSL::SSL::SSLError" unless e.wrapped_exception.is_a?(OpenSSL::SSL::SSLError)
  puts "✓ OpenSSL::SSL::SSLError raises Faraday::SSLError with wrapped_exception preserved"
end

# ---------------------------------------------------------------------------
# 4. Socket and connection refusal errors translate to Faraday::ConnectionFailed
# ---------------------------------------------------------------------------
begin
  simulate_adapter_call(adapter, SocketError.new('getaddrinfo: Name or service not known'))
  raise "Expected call to raise an exception"
rescue Faraday::ConnectionFailed => e
  raise "Expected wrapped_exception to be SocketError" unless e.wrapped_exception.is_a?(SocketError)
  puts "✓ SocketError raises Faraday::ConnectionFailed with wrapped_exception preserved"
end

begin
  simulate_adapter_call(adapter, Errno::ECONNREFUSED.new('Connection refused'))
  raise "Expected call to raise an exception"
rescue Faraday::ConnectionFailed => e
  raise "Expected wrapped_exception to be Errno::ECONNREFUSED" unless e.wrapped_exception.is_a?(Errno::ECONNREFUSED)
  puts "✓ Errno::ECONNREFUSED raises Faraday::ConnectionFailed with wrapped_exception preserved"
end

# ---------------------------------------------------------------------------
# 5. Request body handling: IO stream sets body_stream; String sets body
# ---------------------------------------------------------------------------
io_payload = StringIO.new("stream-chunk-data")
env_io = Faraday::Env.new(:post, io_payload, URI('http://example.test/upload'), Faraday::RequestOptions.new, {}, nil, nil)
req_io = handler.build_request(env_io)

raise "Expected body_stream to be the IO instance" unless req_io.body_stream.equal?(io_payload)
raise "Expected body to be nil when body_stream is used" unless req_io.body.nil?
raise "Expected request_body_permitted? to be true" unless req_io.request_body_permitted?
puts "✓ Streamable body populates body_stream and leaves body nil"

string_payload = "string-content-body"
env_str = Faraday::Env.new(:post, string_payload, URI('http://example.test/post'), Faraday::RequestOptions.new, {}, nil, nil)
req_str = handler.build_request(env_str)

raise "Expected body to be the string payload" unless req_str.body == string_payload
raise "Expected body_stream to be nil when body is a string" unless req_str.body_stream.nil?
puts "✓ String body populates body and leaves body_stream nil"

# ---------------------------------------------------------------------------
# 6. HEAD request method sets response_body_permitted to false
# ---------------------------------------------------------------------------
env_head = Faraday::Env.new(:head, nil, URI('http://example.test/head'), Faraday::RequestOptions.new, {}, nil, nil)
req_head = handler.build_request(env_head)

raise "Expected response_body_permitted? to be false for HEAD" if req_head.response_body_permitted?
raise "Expected request_body_permitted? to be false for nil body" if req_head.request_body_permitted?
puts "✓ HEAD request configures response_body_permitted to false"

# ---------------------------------------------------------------------------
# 7. Response body encoding based on Content-Type charset
# ---------------------------------------------------------------------------
MockNetHttpResponse = Struct.new(:body, :headers) do
  def [](key)
    headers[key]
  end
end

resp_iso = MockNetHttpResponse.new("caf\xE9".b, { 'Content-Type' => 'text/html; charset=ISO-8859-1' })
decoded_iso = handler.decode_body(resp_iso)
raise "Expected body encoding to be ISO-8859-1, got #{decoded_iso.encoding}" unless decoded_iso.encoding == Encoding::ISO_8859_1
puts "✓ Response body encoding matches Content-Type charset (ISO-8859-1)"

resp_bad_charset = MockNetHttpResponse.new("plain payload".b, { 'Content-Type' => 'text/plain; charset=nonexistent-charset-xyz' })
decoded_bad = handler.decode_body(resp_bad_charset)
raise "Expected body to be returned intact on unknown charset" unless decoded_bad == "plain payload"
puts "✓ Unknown charset falls back gracefully without raising error"

# ---------------------------------------------------------------------------
# 8. Nil response body normalization
# ---------------------------------------------------------------------------
resp_nil = MockNetHttpResponse.new(nil, {})
decoded_nil = handler.decode_body(resp_nil)
raise "Expected nil body to normalize to empty string \"\", got #{decoded_nil.inspect}" unless decoded_nil == ""
puts "✓ Nil response body is normalized to empty string"

# ---------------------------------------------------------------------------
# 9. RequestHandler execution wrapper test
# ---------------------------------------------------------------------------
adapter.define_singleton_method(:perform_request) do |_http, _env|
  raise Net::OpenTimeout, 'execution expired'
end
handler_open_res = handler.execute(Faraday::Env.new(:get, nil, URI('http://example.test'), Faraday::RequestOptions.new, {}, nil, nil))
raise "Expected status :connection_failed, got #{handler_open_res[:status]}" unless handler_open_res[:status] == :connection_failed
raise "Expected cause to be Net::OpenTimeout" unless handler_open_res[:cause].is_a?(Net::OpenTimeout)
puts "✓ RequestHandler correctly handles and classifies connection failures"

puts "All faraday-net_http contract tests passed successfully!"

Seeder de origen

csx-seed