toland/patron
Tentang
Ruby HTTP client based on libcurl
Alat pengembanganPertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- +1
- dalam 15 hari
- +2
- dalam 1 bulan
- Mengumpulkan riwayat
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
AsliPatron
Patron is a Ruby HTTP client library based on libcurl. It does not try to expose the full "power" (read complexity) of libcurl but instead tries to provide a sane API while taking advantage of libcurl under the hood.
Usage
First, you instantiate a Session object. You can set a few default options on the Session instance that will be used by all subsequent requests:
sess = Patron::Session.new
sess.timeout = 10
sess.base_url = "http://myserver.com:9900"
sess.headers['User-Agent'] = 'myapp/1.0'
You can set options with a hash in the constructor:
sess = Patron::Session.new(timeout: 10,
base_url: 'http://myserver.com:9900',
headers: {'User-Agent' => 'myapp/1.0'})
Or the set options in a block:
sess = Patron::Session.new do |patron|
patron.timeout = 10
patron.base_url = 'http://myserver.com:9900'
patron.headers = {'User-Agent' => 'myapp/1.0'}
end
Output libcurl's verbose log to a file, to any IO, or to $stderr when called without arguments:
sess.enable_debug "/tmp/patron.debug"
sess.enable_debug $stdout
The Session is used to make HTTP requests.
resp = sess.get("/foo/bar")
Requests return a Response object:
if resp.status < 400
puts resp.body
end
resp.headers is a Hash of the response headers whose lookups ignore the case of the name, since the
casing is the server's to pick: HTTP/2 and HTTP/3 send header names lowercase, as does Puma 8 over
HTTP/1.1, while most other servers still capitalize them. The keys themselves stay as they came in, so
iterating or printing them shows you what was actually on the wire:
resp.headers["Content-Type"] # finds the header the server sent as "content-type" just as well
resp.headers.keys # => ["content-type", "x-request-id"], however the server spelled them
A header that arrived more than once (Set-Cookie, typically) comes back as an Array of its values in
order, even when the server varied the casing between them. The casing is kept rather than folded away
because it can be data and not just a debugging aid - a signing scheme that covers header names signs the
names it was handed. Only one header per name is kept, whatever the casing it gets written under, and
everything that builds a new collection out of the headers (merge, select, slice, ...) hands back
another case-insensitive Patron::Headers, while to_h is the way out to a plain Hash.
GET, HEAD, PUT, PATCH, POST, DELETE and COPY have methods of their own. Any other verb goes through
request, which sends whatever HTTP token it is given, upper-cased - OPTIONS, TRACE, QUERY, PROPFIND
and so on:
sess.put("/foo/baz", "some data")
sess.delete("/foo/baz")
sess.request(:propfind, "/foo", {"Depth" => "1"}, data: "<propfind/>")
sess.request(:query, "/search", {"Content-Type" => "application/json"}, data: '{"q":"patron"}')
Every verb can carry a body, given as data: or file:, except HEAD and TRACE: those raise an
ArgumentError when given one, rather than send the request without it. POST, PUT and PATCH require
a body. A Hash body is form-encoded, whatever the verb.
A failed transfer raises a subclass of Patron::Error (Patron::TimeoutError, Patron::ConnectionFailed,
Patron::HostResolutionError and so on). Every such error carries the libcurl error code as curl_code.
You can ship custom headers with a single request:
sess.post("/foo/stuff", "some data", {"Content-Type" => "text/plain"})
A request header replaces a Session header of the same name, whatever the casing of either. A header
with a CR, LF or NUL in its name or value raises an ArgumentError instead of being sent, since what
follows a line break would go out as a header of its own.
libcurl reads NO_PROXY (and no_proxy) from the environment, even for a proxy set on the Session.
no_proxy lists the hosts to reach directly instead, and an empty String has every request go
through the proxy:
sess.proxy = "http://proxy.internal:3128"
sess.no_proxy = "localhost,.internal"
A request body can be a String, a File (uploaded straight from disk by libcurl) or anything that
responds to readpartial or read, which is streamed. With readpartial a pipe or a socket goes out
as soon as something is written to it. A body without a size goes out with chunked transfer-encoding,
unless you pass a Content-Length header:
reader, writer = IO.pipe
Thread.new { 3.times { |i| writer.write("line #{i}\n") }; writer.close }
sess.put("/foo/log", reader)
sess.post("/foo/stuff", StringIO.new("some data"))
If the body has to be sent again (a 307 redirect, say) Patron rewinds it with seek,
and a body that can't be rewound, like a pipe, fails the request with a Patron::Error.
libcurl's transfer timings are available on the response, in seconds since the request started:
resp = sess.get("/foo/bar")
resp.timings # => {namelookup: 0.001, connect: 0.012, appconnect: 0.045, pretransfer: 0.045,
# starttransfer: 0.210, redirect: 0.0, total: 0.214}
To authenticate with a client certificate (mutual TLS), point Patron at a PKCS#12 bundle:
sess.ssl_cert = "/path/to/client.p12"
sess.ssl_cert_type = "P12"
sess.ssl_key_password = "secret"
or at a PEM certificate with a separate private key:
sess.ssl_cert = "/path/to/client.pem"
sess.ssl_key = "/path/to/client_key.pem"
sess.ssl_key_password = "secret" # if the key is encrypted
If the certificate or key can't be loaded (wrong password, missing file) the request raises Patron::ClientCertificateError.
This depends on the TLS library libcurl is built against: with GnuTLS these surface as a plain Patron::Error.
Client certificates are tested with the OpenSSL and LibreSSL backends - libcurl's Secure Transport backend
can't load a PEM certificate from a file at all.
ssl_cert and ssl_key are paths to files. The certificate and key can also be given as they are,
with no file on disk, as client_cert and client_key - the PEM text itself (or the PKCS#12 bytes,
with ssl_cert_type = "P12") - if libcurl's TLS backend supports that (OpenSSL does):
sess.client_cert = File.read("/path/to/client.pem")
sess.client_key = File.read("/path/to/client_key.pem")
verify_hostname = false accepts a certificate issued for another host name while still checking
who signed it.
Trusting your own CAs
There are two ways to tell a Session which CAs to trust, and they exclude each other: assigning one
clears the other, and giving both to Session.new or to one request raises ArgumentError.
The first is what libcurl takes natively, and the one to use: cert_bundle_path is the path to a PEM
bundle, cert_directory_path the path to a directory of hashed certificates (as openssl rehash
leaves it), cert_bundle the PEM text itself. cert_bundle_path and cert_directory_path can go
together. cert_bundle_path was called cacert in Patron 1.1, which still works but warns.
sess.cert_bundle_path = "/etc/ssl/private-ca.pem"
sess.cert_directory_path = "/etc/ssl/private-cas"
sess.cert_bundle = ENV.fetch("PRIVATE_CA_PEM")
Whichever of them you give replaces the CAs libcurl was built with (its CA bundle and CA directory) rather than adding to them. The exception is the libcurl macOS ships, which falls back to the system's trust settings whatever it is given - on macOS these can add trust, but not take any away. A libcurl from Homebrew does what it is told.
The second is cert_store, an OpenSSL::X509::Store, for when that is all you have:
sess.cert_store = store # cert_bundle_path, cert_directory_path and cert_bundle are nil now
sess.cert_bundle_path = "/etc/ssl/private-ca.pem" # and cert_store is nil again
libcurl can't take a store, so for a request with one libcurl verifies nothing itself and leaves it to the store:
- Each time a connection is up - the TLS handshake done, nothing of the request sent yet - the
certificates the server presented go to the store, which verifies them for a TLS server with its
flags, CRLs and
verify_callback. The server's certificate also has to be issued for the host name, unlessverify_hostnameisfalse. - That happens for every connection, so each hop of a redirect is verified by the store too. A plain HTTP hop has nothing to verify. Through a proxy, it is the server at the other end of the tunnel.
- If the store refuses, the request raises
Patron::CertificateVerificationError, and nothing of it has been sent. - Such a request never reuses a connection, its own or another request's, and does not resume a TLS session either: every request, and every hop of a redirect, makes a new connection with a full handshake. That is the price of the store seeing every certificate.
- A client certificate, if there is one, is presented during that handshake - before the store has looked at the server, since libcurl's own verification is off for these connections.
- It needs a libcurl TLS backend that reports the server's certificates (OpenSSL, LibreSSL and GnuTLS do).
What the TLS attributes take
They are Session attributes, Session.new keywords and per-request options alike. Given to a request as
nil, the CA attributes (cert_bundle_path, cert_directory_path, cert_bundle, cert_store) count as
not given, and the Session's apply.
| Attribute | Takes | Example | libcurl option |
|---|---|---|---|
cert_bundle_path |
path to a PEM file of CA certificates (was cacert) |
"/etc/ssl/private-ca.pem" |
CURLOPT_CAINFO |
cert_directory_path |
path to a directory of hashed CA certificates | "/etc/ssl/private-cas" |
CURLOPT_CAPATH |
cert_bundle |
the PEM text of one or more CA certificates | ca.to_pem |
CURLOPT_CAINFO_BLOB |
cert_store |
an OpenSSL::X509::Store |
OpenSSL::X509::Store.new.tap(&:set_default_paths) |
none, see above |
verify_hostname |
false to skip only the host name check |
false |
CURLOPT_SSL_VERIFYHOST |
ssl_cert |
path to the client certificate file | "/path/to/client.p12" |
CURLOPT_SSLCERT |
client_cert |
the client certificate itself, PEM text or PKCS#12 bytes | File.binread("client.p12") |
CURLOPT_SSLCERT_BLOB |
ssl_cert_type |
the form of ssl_cert or client_cert: "PEM" (default), "DER" or "P12" |
"P12" |
CURLOPT_SSLCERTTYPE |
ssl_key |
path to the PEM private key, unless it is in the certificate | "/path/to/client_key.pem" |
CURLOPT_SSLKEY |
client_key |
the PEM text of the private key itself | ENV.fetch("CLIENT_KEY_PEM") |
CURLOPT_SSLKEY_BLOB |
ssl_key_password |
the password of an encrypted key | "secret" |
CURLOPT_KEYPASSWD |
What is plainly meant for another attribute raises as soon as it is assigned, not on the first
request. A path given where the certificate itself goes raises ArgumentError, whether it is a String or a
Pathname. cert_bundle raises TypeError for anything but a String or a Pathname, and ArgumentError
for a String with no PEM certificate in it - a path to a file or a directory (pointing at cert_bundle_path or
cert_directory_path), DER (with how to convert it: OpenSSL::X509::Certificate.new(der).to_pem) or
anything else. cert_bundle_path and cert_directory_path raise ArgumentError for PEM text and
TypeError for anything but a String or a Pathname, client_cert and client_key raise ArgumentError for
a Pathname or a path to an existing file and TypeError for anything else but a String, and cert_store
raises TypeError for anything but a store. Whether a path exists is left to libcurl.
libcurl's GnuTLS backend takes none of cert_bundle, client_cert and client_key (as of libcurl 7.88).
A request given one of them raises a Patron::Error saying so, before connecting, rather than going ahead
without it.
Streaming responses
Session#stream (and get_stream, post_stream, put_stream, patch_stream) yields the response as
soon as its head has arrived, and the block receives the body by reading from it. Nothing is buffered
meanwhile: every read drives libcurl until some bytes have arrived. timeout still bounds the whole
transfer, so set it to 0 and use read_timeout to bound the wait for each next piece. Connecting is not
part of that wait, a redirect's next hop included - connect_timeout bounds it:
stats = sess.get_stream("/events", { "Accept" => "text/event-stream" }, timeout: 0, read_timeout: 30) do |stream|
raise "Unexpected #{stream.status}" unless stream.ok? && stream.content_type == "text/event-stream"
stream.each_line do |line|
puts line.force_encoding(Encoding::UTF_8)
end
end
stats.complete? # => true when the body was received to its end
stats.timings # the same Hash as Response#timings
stats.trailers # chunked or HTTP/2 trailers, {} when none
Note that there is also a proper client for SSE, see below.
read(length, buffer) and readpartial(length, buffer) fill a String you own, so copying a body
somewhere allocates nothing per chunk. IO.copy_stream uses exactly that, into a File or anything
with write:
sess.get_stream("/large.bin") do |stream|
raise "Too big" if stream.content_length && stream.content_length > 1024 * 1024 * 1024
File.open("large.bin", "wb") { |file| IO.copy_stream(stream, file) }
end
content_length is already an Integer, or nil when the response did not say how long its body is -
which is the case for a chunked HTTP/1.1 response and for a streamed HTTP/2 one, so the guard above
has to let an unknown length through rather than take nil.to_i for a zero. stream.sized? is that
question on its own, for when you want to refuse what you cannot measure up front:
raise "Refusing a body of unknown length" unless stream.sized?
Leaving the block early (break, return, an exception) aborts the transfer and closes its connection;
call stream.drain! first to receive and discard the rest and keep the connection. Using the stream after
its block raises IOError. The block is mandatory, and the Session is busy while it runs. Under a Fiber
scheduler use each and each_line with a block rather than an external Enumerator.
Server-sent events
Patron::SSEClient reads a text/event-stream on top of stream, and reconnects the way a browser's
EventSource does: after the retry interval (the server's retry: field wins), sending Last-Event-ID.
client = Patron::SSEClient.new(
"https://example.com/stream",
headers: { "Authorization" => "Bearer ..." },
idle_timeout: 45, # seconds of silence before reconnecting
retry: 3, # seconds between reconnects until the server sends a retry field
max_reconnects: nil, # nil: forever
last_event_id: nil, # resume from a stored id
session: nil # or a configured Patron::Session: TLS, proxy, auth, cookies, base_url
)
# each_event will start the request and keeps listening as long
# as the server keeps sending
client.each_event do |event|
event.type # "message" unless the server sent an event: field
event.data # data: lines joined with "\n", UTF-8
event.id
break if event.type == "done"
end
client.last_event_id # to persist between process runs
new connects to nothing: it only holds on to the settings. each_event is what opens the stream, and it is
a blocking loop rather than a handler you install - it issues the GET, then reads the response and yields
every event to your block as the bytes arrive, returning only when the block breaks, the server answers 204,
close is called or the reconnects run out. Your block runs inside that read loop, so a slow block slows the
reading down and the server feels it as backpressure on the connection; nothing is being received while there
is no block there to receive it, so there is no window in which events pile up or get missed for want of a
handler. This is the one place where the client is not like a browser's EventSource, which connects as soon
as it is constructed and calls onmessage whenever an event turns up afterwards.
A 204 ends each_event. Any other status than 200, or another Content-Type, raises
Patron::SSEClient::UnexpectedResponse with the status, headers and first 4 KB of body, since retrying
a 503 is the application's call. An event that is not valid UTF-8 raises Patron::SSEClient::InvalidEncoding
and ends the stream, where a browser would substitute U+FFFD. client.close from another thread or fiber makes
each_event return.
The client only issues GETs, like an EventSource. For an event stream that answers a POST, which is how the
LLM completion APIs stream, run the same parser over the body yourself:
session.post_stream("/v1/chat/completions", body.to_json, headers) do |stream|
raise "status #{stream.status}" unless stream.status == 200
Patron::SSEClient.parse(stream) do |event|
break if event.data == "[DONE]"
print JSON.parse(event.data).dig("choices", 0, "delta", "content")
end
end
Patron::SSEClient.parse takes anything with readpartial, so a file or a socket works as well as a
ResponseStream, and returns the last event ID it saw.
Threading
A Patron::Session performs one request at a time and must not be shared between threads: each Session
owns its own libcurl handles and buffers, and using it from two threads at once raises Patron::Error.
Patron releases the GVL (the global VM lock) whenever it waits for the network, so using one Session
per thread gives you real parallelism.
For sharing a pool of sessions between threads we recommend the excellent connection_pool gem by Mike Perham.
patron_pool = ConnectionPool.new(size: 5, timeout: 5) { Patron::Session.new }
patron_pool.with do |session|
session.get(...)
end
Sharing Session objects between requests will also allow you to benefit from persistent connections (connection reuse), see below.
Persistent connections
Every Session owns a libcurl multi handle with its own connection cache, plus a share handle for
cookies, DNS entries and TLS sessions. If you create the Session once and use it for multiple requests
to the same hostname/port/protocol, the connection gets reused, following libcurl's rules on
connection reuse. Requests with a cert_store
are the exception: each of them makes connections of its own, see Trusting your own CAs.
Interrupting requests
A request in flight can be aborted from another thread with Session#interrupt, after which the
request raises Patron::Aborted. Thread#kill, Thread#raise, Timeout.timeout and signals interrupt
a request the same way, immediately and in any phase of the transfer, including DNS resolution and
connecting. A progress_callback that returns false aborts the request as well, and an exception
raised inside the callback propagates out of the request once libcurl is done with it.
Fibers and the async gem
When a Fiber scheduler is installed for the current thread (as inside Async { }), Patron hands the
wait for the network to the scheduler instead of blocking the thread, so requests from several fibers
overlap and other fibers keep running while one waits:
Async do |task|
pages = urls.map { |url| task.async { Patron::Session.new(timeout: 10).get(url) } }.map(&:wait)
end
Each fiber needs its own Session, just like each thread does. Async::Task#stop and
Task#with_timeout interrupt a request in flight the same way Thread#kill and Timeout do, and
Session#interrupt and SSEClient#close from another fiber reach the waiting one at once.
Ractors
Patron works from non-main Ractors, so Ractors give you parallelism for the Ruby side of your
requests as well, not just for the waits. A Session belongs to the Ractor that created it: Ruby refuses
to copy, move or share one (Ractor::Error), so create the Session inside the Ractor and ship
Response objects out. A worker pool looks like this on Ruby 4.0:
results = Ractor::Port.new
workers = 4.times.map do
Ractor.new(results) do |results|
session = Patron::Session.new(timeout: 10)
while (url = Ractor.receive)
results << Ractor.make_shareable(session.get(url))
end
end
end
urls.each_with_index { |url, i| workers[i % workers.size].send(url) }
responses = urls.size.times.map { results.receive }
Ractor.make_shareable on the Response is optional: it saves copying the body when the Response crosses
over, and a shareable (frozen) Response still decodes its body. A Patron::Error raised inside the
Ractor comes out of Ractor#value as the cause of a Ractor::RemoteError, curl_code and all.
Patron::Request objects can be made shareable and used from any Ractor too.
How the GVL is handled
Patron drives libcurl through its multi interface. The part of libcurl that moves bytes
(curl_multi_perform) runs with the GVL held, which is what makes it safe to run your progress callback
and to write straight into Ruby Strings from inside libcurl. Whenever libcurl has nothing to do but wait
for the network, Patron releases the GVL (curl_multi_poll), so other Ruby threads run in parallel with
the transfer, and that wait is what Ruby interrupts when it needs the thread back.
Requirements
Patron 1.0 and up requires Ruby 3.3 or newer and libcurl 7.81.0 or newer (Ubuntu 22.04 and up,
Debian 12 and up, any current macOS). The 0.x versions support older Rubies and stay on the v0.x branch.
You will have to install the libcurl development package on Debian or Ubuntu (libcurl4-openssl-dev),
Alpine (curl-dev) and the like. The build looks libcurl up through pkg-config, then curl-config,
then the default include and library paths. To build against a specific libcurl, for example
Homebrew's OpenSSL-backed one instead of the SecureTransport-backed one macOS ships:
$ gem install patron -- --with-curl-dir=$(brew --prefix curl)
or, for every Bundler-driven install:
$ bundle config build.patron --with-curl-dir=$(brew --prefix curl)
In a checkout of this repository, bundle exec rake compile && bundle exec ruby script/smoke is a
one-second check of whichever libcurl you have just built against: it loads the extension, maps a refused
connection, reads a streamed body in small pieces (which is what makes a transfer pause and resume) and
does it all again in a forked child. Useful for a libcurl the suite never gets run against - one you built
yourself, or the one your distro ships. bundle exec rake is still the real coverage.
The SecureTransport backend of the macOS system libcurl cannot load PEM client certificates, and older versions of it crash when doing HTTPS in a forked subprocess, so the Homebrew libcurl is the better choice on macOS.
One libcurl version is worth avoiding: 8.16.0 ends a paused transfer with CURLE_AGAIN ("Socket not
ready for send/recv") rather than completing it, which breaks every streamed response that is read in
smaller pieces than libcurl delivers them - Session#stream, get_file and SSEClient with it, since
reading a part of the body is what pauses the transfer. It is an
upstream regression in that one release, fixed two days later
in 8.17.0 ("cw-out: fix EAGAIN handling on pause"); 8.15.0 and earlier are fine, and so is everything from
8.17.0 on. Patron does not work around it, so upgrade libcurl if Patron.libcurl_version says 8.16.0.
Installation
gem install patron
Copyright (c) 2008 The Hive
Jelajahi proyek terkait
Memuat…