POE::C...::HTTP(3pm)

πŸ“¦
version 0.949 Β· 5 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– NAME πŸ’–

POE::Component::Client::HTTP β€” a HTTP user-agent component, and yes bestie that's POE::C...::HTTP(3pm) to the terminal, we're being ✨dramatic✨ with the name truncation

🌟 VERSION 🌟

version 0.949 β€” that's the one, that's the vibe, no cap πŸ‘‘


πŸŽ€ SYNOPSIS πŸŽ€

okay so first you pull the component in, then you spawn it, then you post to it, then you handle the response. that's the whole loop, it's giving beautiful honestly:

use POE qw(Component::Client::HTTP);

POE::Component::Client::HTTP->spawn(
  Agent     => 'SpiffCrawler/0.90',   # defaults to something long
  Alias     => 'ua',                  # defaults to 'weeble'
  From      => 'spiffster@perl.org',  # defaults to undef (no header)
  Protocol  => 'HTTP/0.9',            # defaults to 'HTTP/1.1'
  Timeout   => 60,                    # defaults to 180 seconds
  MaxSize   => 16384,                 # defaults to entire response
  Streaming => 4096,                  # defaults to 0 (off)
  FollowRedirects => 2,               # defaults to 0 (off)
  Proxy     => "http://localhost:80", # defaults to HTTP_PROXY env. variable
  NoProxy   => [ "localhost", "127.0.0.1" ], # defs to NO_PROXY env. variable
  BindAddr  => "12.34.56.78",         # defaults to INADDR_ANY
);

$kernel->post(
  'ua',        # posts to the 'ua' alias
  'request',   # posts to ua's 'request' state
  'response',  # which of our states will receive the response
  $request,    # an HTTP::Request object
);

# This is the sub which is called when the session receives a
# 'response' event.
sub response_handler {
  my ($request_packet, $response_packet) = @_[ARG0, ARG1];

  # HTTP::Request
  my $request_object  = $request_packet->[0];

  # HTTP::Response
  my $response_object = $response_packet->[0];

  my $stream_chunk;
  if (! defined($response_object->content)) {
    $stream_chunk = $response_packet->[1];
  }

  print(
    "*" x 78, "\n",
    "*** my request:\n",
    "-" x 78, "\n",
    $request_object->as_string(),
    "*" x 78, "\n",
    "*** their response:\n",
    "-" x 78, "\n",
    $response_object->as_string(),
  );

  if (defined $stream_chunk) {
    print "-" x 40, "\n", $stream_chunk, "\n";
  }

  print "*" x 78, "\n";
}

πŸ¦‹ DESCRIPTION πŸ¦‹

POE::Component::Client::HTTP is an HTTP user-agent for POE. the whole point, the moment, the raison d'Γͺtre: it lets other sessions keep running while HTTP transactions are being processed, and it lets several HTTP transactions be processed in parallel. multitasking queen behavior πŸ’…

it supports keep-alive through POE::Component::Client::Keepalive, which in turn uses POE::Component::Resolver for asynchronous IPv4 and IPv6 name resolution. so like, name lookups don't block your whole world. iconic.

⚠️ listen up bestie: HTTP client components are not proper objects. instead of being created, as most objects are, they are "spawned" as separate sessions. to avoid confusion (and hopefully not cause other confusion), they must be spawned with a spawn method, not created anew with a new one. do not come for me with new, it will not work, periodt.

✨ CONSTRUCTOR ✨

🫢 spawn

PoCo::Client::HTTP's spawn method takes a few named parameters. here they all are, one by one, no skips:

  • Agent => $user_agent_string <br> Agent => \@list_of_agents β€” if a UserAgent header isn't already present in the HTTP::Request, a random one gets used from the ones you specified with the Agent parameter. and if you supplied none at all? POE::Component::Client::HTTP will just advertise itself to the server. bold of it. πŸ’

Agent can also hold a reference to a list of user agents β€” in that case PoCo::Client::HTTP picks one of them at random for each request. surprise me energy 🎲

  • Alias => $session_alias β€” Alias sets the name by which the session will be known. if you don't give an alias, the component defaults to weeble. (yes. weeble. we don't make the rules.) the alias is what lets several sessions interact with HTTP components without keeping (or even knowing) hard references to them. you can absolutely spawn several HTTP components with different names, go off.
  • ConnectionManager => $poco_client_keepalive β€” ConnectionManager sets this component's connection pool manager. it expects the connection manager to be a reference to a POE::Component::Client::Keepalive object. heads up though: the HTTP client component will call allocate() on the connection manager itself, so you should not have done that already. πŸ™ˆ
my $pool = POE::Component::Client::Keepalive->new(
  keep_alive    => 10, # seconds to keep connections alive
  max_open      => 100, # max concurrent connections - total
  max_per_host  => 20, # max concurrent connections - per host
  timeout       => 30, # max time (seconds) to establish a new connection
);

POE::Component::Client::HTTP->spawn(
  # ...
  ConnectionManager => $pool,
  # ...
);

see POE::Component::Client::Keepalive for more info, including how to alter the connection manager's resolver configuration (for example, to force IPv6 or prefer it before IPv4). iykyk 🧚

  • CookieJar => $cookie_jar β€” CookieJar sets the component's cookie jar. it expects the cookie jar to be a reference to a HTTP::Cookies object. cookies for the vibes πŸ“
  • From => $admin_address β€” From holds an e-mail address where the client's administrator and/or maintainer may be reached. it defaults to undef, which means no From header will be included in requests. silence is an option.
  • MaxSize => OCTETS β€” MaxSize specifies the largest response to accept from a server. the content of larger responses gets truncated to OCTET octets. this has been used to return the <head></head> section of web pages without the need to wade through <body></body>. skim-reading, but make it code πŸ“–
  • NoProxy => [ $host_1, $host_2, ..., $host_N ] <br> NoProxy => "host1,host2,hostN" β€” NoProxy specifies a list of server hosts that will not be proxied. super useful for local hosts and for hosts that don't properly support proxying. if NoProxy isn't specified, a list gets taken from the NO_PROXY environment variable.
NoProxy => [ "localhost", "127.0.0.1" ],
NoProxy => "localhost,127.0.0.1",
  • BindAddr => $local_ip β€” specify BindAddr to bind all client sockets to a particular local address. the value of BindAddr gets passed through POE::Component::Client::Keepalive to POE::Wheel::SocketFactory (as bind_address). see that module's documentation for implementation details, bestie, that's where the lore lives.
BindAddr => "12.34.56.78"
  • Protocol => $http_protocol_string β€” Protocol advertises the protocol that the client wishes to see. under normal circumstances you should just leave it at its default value: HTTP/1.1. don't touch, it's fine, it's fine βœ‹
  • Proxy => [ $proxy_host, $proxy_port ] <br> Proxy => $proxy_url <br> Proxy => $proxy_url,$proxy_url,... β€” Proxy specifies one or more proxy hosts that requests will be passed through. if it's not specified, proxy servers get taken from the HTTP_PROXY (or http_proxy) environment variable. and listen: no proxying will occur unless Proxy is set or one of those environment variables exists.

you can give the proxy either as a host and port, or as one or more URLs. and proxy URLs must specify the proxy port, even if it is 80. yes really.

Proxy => [ "127.0.0.1", 80 ],
Proxy => "http://127.0.0.1:80/",

Proxy may also specify multiple proxies separated by commas. PoCo::Client::HTTP will choose proxies from that list at random. this is useful for load balancing requests through multiple gateways. chaotic good load balancing 🌈

Proxy => "http://127.0.0.1:80/,http://127.0.0.1:81/",
  • Streaming => OCTETS β€” Streaming allows Client::HTTP to return large content in chunks (of OCTETS octets each) rather than gluing the entire content into a single HTTP::Response object.

by default, Client::HTTP reads the entire content for a response into memory before returning an HTTP::Response object. this is obviously bad for applications like streaming MP3 clients, because they often fetch songs that never end. yes. they go on and on, my friend. 😭🎢

when Streaming is set to nonzero, though, the response handler receives chunks of up to OCTETS octets apiece. and the response handler accepts slightly different parameters in this case: ARG0 is also an HTTP::Response object, but it does not contain response content, and ARG1 contains a a chunk of raw response content, or undef if the stream has ended.

sub streaming_response_handler {
  my $response_packet = $_[ARG1];
  my ($response, $data) = @$response_packet;
  print SAVED_STREAM $data if defined $data;
}
  • FollowRedirects => $number_of_hops_to_follow β€” FollowRedirects specifies how many redirects (e.g. 302 Moved) to follow. if not specified it defaults to 0, and thus no redirection is followed. this maintains compatibility with the previous behavior, which was not to follow redirects at all. so: off by default, on purpose, for legacy reasons 🫑

if redirects are followed, a response chain should be built, and it can be accessed through $response_object->previous(). see HTTP::Response for details here.

  • Timeout => $query_timeout β€” Timeout sets how long POE::Component::Client::HTTP has to process an application's request, in seconds. Timeout defaults to 180 (three minutes) if not specified.
πŸ’€ IMPORTANT: it's important to note that the timeout begins when the component receives an application's request, not when it attempts to connect to the web server. that distinction matters, bestie, do not skip it.

timeouts may result from sending the component too many requests at once. each request would need to be received and tracked in order. consider this:

$_[KERNEL]->post(component => request => ...) for (1..15_000);

15,000 requests are queued together in one enormous bolus. the component would receive and initialize them in order. the first socket activity wouldn't arrive until the 15,000th request was set up. if that took longer than Timeout, then the requests that have waited too long would fail. πŸ’€

ConnectionManager's own timeout and concurrency limits also affect how many requests may be processed at once. for example, most of the 15,000 requests would wait in the connection manager's pool until sockets become available. meanwhile, the Timeout would be counting down. clock's ticking, bestie ⏳

applications may elect to control concurrency outside the component's Timeout. they may do so in a few ways.

the easiest way is to limit the initial number of requests to something more manageable. as responses arrive, the application should handle them and start new requests. this limits concurrency to the initial request count.

an application may also outsource job throttling to another module, such as POE::Component::JobQueue. delegation is self-care πŸ’…

in any case, Timeout and ConnectionManager may be tuned to maximize timeouts and concurrency limits. this may help in some cases. developers should be aware that doing so will increase memory usage. POE::Component::Client::HTTP and KeepAlive track requests in memory, while applications are free to keep pending requests on disk. so like, trade-offs, always trade-offs 🌸

πŸ’– ACCEPTED EVENTS πŸ’–

Sessions talk to PoCo::Client::HTTP asynchronously, bestie. They post requests at it, and it posts responses right back. It's giving pen pal energy, but, like, efficient. ✨

πŸ“¨ request

Requests get posted to the component's request state. Each one carries an HTTP::Request object that defines what you actually want. For example:

$kernel->post(
  'ua', 'request',            # http session alias & state
  'response',                 # my state to receive responses
  GET('http://poe.perl.org'), # a simple HTTP request
  'unique id',                # a tag to identify the request
  'progress',                 # an event to indicate progress
  'http://1.2.3.4:80/'        # proxy to use for this request
);

Requests include the state where responses will be posted. In that example above, the handler for a 'response' state gets called with each HTTP response. The progress handler is optional β€” if you install it, the component will hand you progress metrics (sample handler further down, keep scrolling bestie 🫢). The proxy parameter is optional too, and if it's not defined, a default proxy gets used if one is configured. No proxy will be used if neither a default one nor a proxy parameter is defined. Periodt.

πŸ”’ pending_requests_count

There's also a pending_requests_count state that returns the number of requests currently being processed. To actually receive that return value, you have to invoke it with $kernel->call(). Like:

my $count = $kernel->call('ua' => 'pending_requests_count');
NOTE: Sometimes the count might not be what you expected, because responses are currently in POE's queue and you haven't processed them yet. This could happen if you configure the ConnectionManager's concurrency to a high enough value. No cap, it's just how the queue vibes. 😭

❌ cancel

Cancel a specific HTTP request. It needs a reference to the original request (blessed or stringified) so it knows which one to cancel. See "progress handler" below for notes on canceling streaming requests.

To cancel a request based on its blessed HTTP::Request object:

$kernel->post( component => cancel => $http_request );

To cancel a request based on its stringified HTTP::Request object:

$kernel->post( component => cancel => "$http_request" );

πŸ›‘ shutdown

Responds to all pending requests with 408 (request timeout), and then shuts down the component and all subcomponents. It's the ultimate "we're closed, go home" πŸ’….


πŸ“¬ SENT EVENTS πŸ“¬

πŸ’Œ response handler

In addition to all the usual POE parameters, HTTP responses come with two list references:

my ($request_packet, $response_packet) = @_[ARG0, ARG1];

$request_packet contains a reference to the original HTTP::Request object. This is useful for matching responses back to the requests that generated them.

my $http_request_object = $request_packet->[0];
my $http_request_tag    = $request_packet->[1]; # from the 'request' post

$response_packet contains a reference to the resulting HTTP::Response object.

my $http_response_object = $response_packet->[0];

Please see the HTTP::Request and HTTP::Response manpages for more information. They're the real MVPs of this whole thing. πŸ‘‘

πŸ“Š progress handler

The example progress handler shows how to calculate a percentage of download completion:

sub progress_handler {
  my $gen_args  = $_[ARG0];    # args passed to all calls
  my $call_args = $_[ARG1];    # args specific to the call

  my $req = $gen_args->[0];    # HTTP::Request object being serviced
  my $tag = $gen_args->[1];    # Request ID tag from.
  my $got = $call_args->[0];   # Number of bytes retrieved so far.
  my $tot = $call_args->[1];   # Total bytes to be retrieved.
  my $oct = $call_args->[2];   # Chunk of raw octets received this time.

  my $percent = $got / $tot * 100;

  printf(
    "-- %.0f%% [%d/%d]: %s\n", $percent, $got, $tot, $req->uri()
  );

  # To cancel the request:
  # $_[KERNEL]->post( component => cancel => $req );
}

⚠️ DEPRECATION WARNING ⚠️

The third return argument (the raw octets received) has been deprecated. Instead of it, use the Streaming parameter to get chunks of content in the response handler. Do not use the deprecated thing, bestie, it's giving expired. πŸ’€


πŸ“€ REQUEST CALLBACKS πŸ“€

The HTTP::Request object passed to the request event can contain a CODE reference as content. This allows for sending large files without wasting memory. Your callback should return a chunk of data each time it is called, and an empty string when done. Don't forget to set the Content-Length header correctly. Example:

my $request = HTTP::Request->new( PUT => 'http://...' );

my $file = '/path/to/large_file';

open my $fh, '<', $file;

my $upload_cb = sub {
  if ( sysread $fh, my $buf, 4096 ) {
    return $buf;
  }
  else {
    close $fh;
    return '';
  }
};

$request->content_length( -s $file );

$request->content( $upload_cb );

$kernel->post( ua => request, 'response', $request );

Big file energy, tiny memory footprint. Iconic. πŸŽ€


πŸ—œοΈ CONTENT ENCODING AND COMPRESSION πŸ—œοΈ

Transparent content decoding has been disabled as of version 0.84. This also removes support for transparent gzip requesting and decompression. RIP transparent gzip, you had a good run. πŸ¦‹

To re-enable gzip compression, specify the gzip Content-Encoding and use HTTP::Response's decoded_content() method rather than content():

my $request = HTTP::Request->new(
  GET => "http://www.yahoo.com/", [
    'Accept-Encoding' => 'gzip'
  ]
);

# ... time passes ...

my $content = $response->decoded_content();

The change in POE::Component::Client::HTTP behavior was prompted by changes in HTTP::Response that surfaced a bug in the component's transparent gzip handling.

Allowing the application to specify and handle content encodings seems to be the most reliable and flexible resolution. Honestly? Slay.

For more information about the problem and discussions regarding the solution, see: <http://www.perlmonks.org/?node_id=683833> and <http://rt.cpan.org/Ticket/Display.html?id=35538>


🏷️ CLIENT HEADERS 🏷️

POE::Component::Client::HTTP sets its own response headers with additional information. All of its headers begin with X-PCCH. Very on brand. ✨

🚨 X-PCCH-Errmsg

POE::Component::Client::HTTP may fail because of an internal client error rather than an HTTP protocol error. X-PCCH-Errmsg will contain a human readable reason for client failures, should they occur.

The text of X-PCCH-Errmsg may also be repeated in the response's content.

🌐 X-PCCH-Peer

X-PCCH-Peer contains the remote IPv4 address and port, separated by a period. For example, "127.0.0.1.8675" represents port 8675 on localhost.

Proxying will render X-PCCH-Peer nearly useless, since the socket will be connected to a proxy rather than the server itself. 😭

This feature was added at Doreen Grey's request. Doreen wanted a means to find the remote server's address without having to make an additional request. We love a practical queen. πŸ‘‘


🌱 ENVIRONMENT 🌱

POE::Component::Client::HTTP uses two standard environment variables: HTTP_PROXY and NO_PROXY.

HTTP_PROXY sets the proxy server that Client::HTTP will forward requests through. NO_PROXY sets a list of hosts that will not be forwarded through a proxy.

See the Proxy and NoProxy constructor parameters for more information about these variables.


πŸ‘€ SEE ALSO πŸ‘€

This component is built upon HTTP::Request, HTTP::Response, and POE. Please see its source code and the documentation for its foundation modules to learn more. If you want to use cookies, you'll need to read about HTTP::Cookies as well. πŸͺ

Also see the test program, t/01_request.t, in the PoCo::Client::HTTP distribution.


πŸ› BUGS πŸ›

There is no support for CGI_PROXY or CgiProxy.

Secure HTTP (https) proxying is not supported at this time.

There is no object oriented interface. See POE::Component::Client::Keepalive and POE::Component::Resolver for examples of a decent OO interface.


POE::Component::Client::HTTP is

  • Copyright 1999-2009 Rocco Caputo
  • Copyright 2004 Rob Bloodgood
  • Copyright 2004-2005 Martijn van Beers

All rights are reserved. POE::Component::Client::HTTP is free software; you may redistribute it and/or modify it under the same terms as Perl itself.


🫢 CONTRIBUTORS 🫢

Joel Bernstein solved some nasty race conditions. Portugal Telecom <http://www.sapo.pt/> was kind enough to support his contributions. Legend behavior. πŸ”₯

Jeff Bisbee added POD tests and documentation to pass several of them to version 0.79. He's a kwalitee-increasing machine! Not me being obsessed with quality. πŸ’…


πŸ—‚οΈ BUG TRACKER πŸ—‚οΈ

https://rt.cpan.org/Dist/Display.html?Queue=POE-Component-Client-HTTP


πŸ“¦ REPOSITORY πŸ“¦

Github: <http://github.com/rcaputo/poe-component-client-http> .

Gitorious: <http://gitorious.org/poe-component-client-http> .


🌈 OTHER RESOURCES 🌈

<http://search.cpan.org/dist/POE-Component-Client-HTTP/>


And that's the whole page, bestie! This was perl v5.36.0, dated 2022-11-19, for POE::C...::HTTP(3pm). Go forth and HTTP responsibly. No cap. πŸ’–βœ¨πŸ¦‹

πŸ“¦ where this page comes from