| 1 | package YAHC; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | our $VERSION = '0.009'; | ||
| 7 | |||
| 8 | use EV; | ||
| 9 | use Time::HiRes; | ||
| 10 | use Exporter 'import'; | ||
| 11 | use Scalar::Util qw/weaken/; | ||
| 12 | use Fcntl qw/F_GETFL F_SETFL O_NONBLOCK/; | ||
| 13 | use POSIX qw/EINPROGRESS EINTR EAGAIN EWOULDBLOCK strftime/; | ||
| 14 | use Socket qw/PF_INET SOCK_STREAM $CRLF SOL_SOCKET SO_ERROR inet_aton inet_ntoa pack_sockaddr_in/; | ||
| 15 | |||
| 16 | sub YAHC::Error::NO_ERROR () { 0 } | ||
| 17 | sub YAHC::Error::REQUEST_TIMEOUT () { 1 << 0 } | ||
| 18 | sub YAHC::Error::CONNECT_TIMEOUT () { 1 << 1 } | ||
| 19 | sub YAHC::Error::DRAIN_TIMEOUT () { 1 << 2 } | ||
| 20 | |||
| 21 | sub YAHC::Error::CONNECT_ERROR () { 1 << 10 } | ||
| 22 | sub YAHC::Error::READ_ERROR () { 1 << 11 } | ||
| 23 | sub YAHC::Error::WRITE_ERROR () { 1 << 12 } | ||
| 24 | sub YAHC::Error::REQUEST_ERROR () { 1 << 13 } | ||
| 25 | sub YAHC::Error::RESPONSE_ERROR () { 1 << 14 } | ||
| 26 | sub YAHC::Error::CALLBACK_ERROR () { 1 << 15 } | ||
| 27 | sub YAHC::Error::INTERNAL_ERROR () { 1 << 31 } | ||
| 28 | |||
| 29 | sub YAHC::State::INITIALIZED () { 1 << 0 } | ||
| 30 | sub YAHC::State::RESOLVE_DNS () { 1 << 1 } | ||
| 31 | sub YAHC::State::WAIT_SYNACK () { 1 << 2 } | ||
| 32 | sub YAHC::State::CONNECTED () { 1 << 3 } | ||
| 33 | sub YAHC::State::WRITING () { 1 << 4 } | ||
| 34 | sub YAHC::State::READING () { 1 << 5 } | ||
| 35 | sub YAHC::State::USER_ACTION () { 1 << 15 } | ||
| 36 | sub YAHC::State::COMPLETED () { 1 << 30 } # terminal state | ||
| 37 | |||
| 38 | use constant { | ||
| 39 | HTTP_PORT => 80, | ||
| 40 | TCP_READ_CHUNK => 65536, | ||
| 41 | CALLBACKS => [ qw/init_callback wait_synack_callback connected_callback | ||
| 42 | writing_callback reading_callback callback/ ], | ||
| 43 | }; | ||
| 44 | |||
| 45 | our @EXPORT_OK = qw/ | ||
| 46 | yahc_reinit_conn | ||
| 47 | yahc_conn_last_error | ||
| 48 | yahc_conn_id | ||
| 49 | yahc_conn_url | ||
| 50 | yahc_conn_target | ||
| 51 | yahc_conn_state | ||
| 52 | yahc_conn_errors | ||
| 53 | yahc_conn_timeline | ||
| 54 | yahc_conn_request | ||
| 55 | yahc_conn_response | ||
| 56 | yahc_conn_retries_left | ||
| 57 | /; | ||
| 58 | |||
| 59 | our %EXPORT_TAGS = (all => \@EXPORT_OK); | ||
| 60 | |||
| 61 | ################################################################################ | ||
| 62 | # User facing functons | ||
| 63 | ################################################################################ | ||
| 64 | |||
| 65 | sub new { | ||
| 66 | my ($class, $args) = @_; | ||
| 67 | |||
| 68 | die 'YAHC: ->new() expect args to be a hashref' if defined $args and ref($args) ne 'HASH'; | ||
| 69 | die 'YAHC: please do `my ($yahc, $yahc_storage) = YAHC::new()` and keep both these objects in the same scope' unless wantarray; | ||
| 70 | |||
| 71 | # wrapping target selection here allows all client share same list | ||
| 72 | # and more importantly to share index within the list | ||
| 73 | $args->{_target} = _wrap_target_selection($args->{host}) if $args->{host}; | ||
| 74 | |||
| 75 | # this's a radical way of avoiding circular references. | ||
| 76 | # let's see how it plays out in practise. | ||
| 77 | my %storage = ( | ||
| 78 | watchers => {}, | ||
| 79 | callbacks => {}, | ||
| 80 | connections => {}, | ||
| 81 | ); | ||
| 82 | |||
| 83 | my $self = bless { | ||
| 84 | loop => new EV::Loop, | ||
| 85 | pid => $$, # store pid to detect forks | ||
| 86 | storage => \%storage, | ||
| 87 | watchers => $storage{watchers}, | ||
| 88 | callbacks => $storage{callbacks}, | ||
| 89 | connections => $storage{connections}, | ||
| 90 | last_connection_id => $$ * 1000, | ||
| 91 | |||
| 92 | debug => delete $args->{debug} || 0, | ||
| 93 | keep_timeline => delete $args->{keep_timeline} || 0, | ||
| 94 | pool_args => $args, | ||
| 95 | }, $class; | ||
| 96 | |||
| 97 | weaken($self->{storage}); | ||
| 98 | weaken($self->{watchers}); | ||
| 99 | weaken($self->{callbacks}); | ||
| 100 | weaken($self->{connections}); | ||
| 101 | return $self, \%storage; | ||
| 102 | } | ||
| 103 | |||
| 104 | sub request { | ||
| 105 | my ($self, @args) = @_; | ||
| 106 | my ($conn_id, $request); | ||
| 107 | die 'YAHC: new_request() expects arguments' unless @args; | ||
| 108 | die 'YAHC: storage object is destroyed' unless $self->{storage}; | ||
| 109 | |||
| 110 | if (@args == 1) { | ||
| 111 | $conn_id = 'connection_' . $self->{last_connection_id}++; | ||
| 112 | $request = $args[0]; | ||
| 113 | } else { | ||
| 114 | ($conn_id, $request) = @args; | ||
| 115 | } | ||
| 116 | |||
| 117 | die "YAHC: Connection with name '$conn_id' already exists\n" | ||
| 118 | if exists $self->{connections}{$conn_id}; | ||
| 119 | |||
| 120 | my $conn = { | ||
| 121 | id => $conn_id, | ||
| 122 | request => $request, | ||
| 123 | response => { status_code => 0 }, | ||
| 124 | attempt => 0, | ||
| 125 | retries => $request->{retries} || 0, | ||
| 126 | state => YAHC::State::INITIALIZED(), | ||
| 127 | debug => delete $request->{debug} || $self->{debug}, | ||
| 128 | keep_timeline => delete $request->{keep_timeline} || $self->{keep_timeline}, | ||
| 129 | selected_target => [], | ||
| 130 | }; | ||
| 131 | |||
| 132 | my $pool_args = $self->{pool_args}; | ||
| 133 | $request->{_target} = _wrap_target_selection($request->{host}) if $request->{host}; | ||
| 134 | do { $request->{$_} ||= $pool_args->{$_} if $pool_args->{$_} } foreach (qw/host port scheme/); | ||
| 135 | die "YAHC: host must be defined\n" unless $request->{host}; | ||
| 136 | |||
| 137 | $request->{scheme} //= 'http'; | ||
| 138 | die "YAHC: only support scheme http\n" unless $request->{scheme} eq 'http'; | ||
| 139 | |||
| 140 | my %callbacks; | ||
| 141 | foreach (@{ CALLBACKS() }) { | ||
| 142 | next unless $request->{$_}; | ||
| 143 | $callbacks{$_} = delete $request->{$_}; | ||
| 144 | $conn->{"has_$_"} = 1; | ||
| 145 | } | ||
| 146 | |||
| 147 | $self->{watchers}{$conn_id} = {}; | ||
| 148 | $self->{callbacks}{$conn_id} = \%callbacks; | ||
| 149 | $self->{connections}{$conn_id} = $conn; | ||
| 150 | |||
| 151 | $self->_set_init_state($conn_id); | ||
| 152 | return $conn; | ||
| 153 | } | ||
| 154 | |||
| 155 | sub drop { | ||
| 156 | my ($self, $c) = @_; | ||
| 157 | my $conn_id = ref($c) eq 'HASH' ? $c->{id} : $c; | ||
| 158 | |||
| 159 | my $conn = $self->{connections}{$conn_id} | ||
| 160 | or return; | ||
| 161 | |||
| 162 | _register_in_timeline($conn, "dropping connection from pool") if $conn->{keep_timeline}; | ||
| 163 | $self->_set_completed_state($conn_id) unless $conn->{state} == YAHC::State::COMPLETED(); | ||
| 164 | |||
| 165 | return delete $self->{connections}{$conn_id}; | ||
| 166 | } | ||
| 167 | |||
| 168 | sub run { shift->_run(0, @_) } | ||
| 169 | sub run_once { shift->_run(EV::RUN_ONCE) } | ||
| 170 | sub run_tick { shift->_run(EV::RUN_NOWAIT) } | ||
| 171 | |||
| 172 | ################################################################################ | ||
| 173 | # Routines to manipulate connections (also user facing) | ||
| 174 | ################################################################################ | ||
| 175 | |||
| 176 | sub yahc_reinit_conn { | ||
| 177 | my ($conn, $args) = @_; | ||
| 178 | die "YAHC: cannot reinit completed connection\n" | ||
| 179 | if $conn->{state} >= YAHC::State::COMPLETED(); | ||
| 180 | |||
| 181 | $conn->{attempt} = 0; | ||
| 182 | $conn->{state} = YAHC::State::INITIALIZED(); | ||
| 183 | return unless defined $args && ref($args) eq 'HASH'; | ||
| 184 | |||
| 185 | my $request = $conn->{request}; | ||
| 186 | do { $request->{$_} = $args->{$_} if $args->{$_} } foreach (keys %$args); | ||
| 187 | $request->{_target} = _wrap_target_selection($args->{host}) if $args->{host}; | ||
| 188 | } | ||
| 189 | |||
| 190 | sub yahc_conn_last_error { | ||
| 191 | my $conn = shift; | ||
| 192 | return unless $conn->{errors} && @{ $conn->{errors} }; | ||
| 193 | return wantarray ? @{ $conn->{errors}[-1] } : $conn->{errors}[-1]; | ||
| 194 | } | ||
| 195 | |||
| 196 | sub yahc_conn_id { $_[0]->{id} } | ||
| 197 | sub yahc_conn_state { $_[0]->{state} } | ||
| 198 | sub yahc_conn_errors { $_[0]->{errors} } | ||
| 199 | sub yahc_conn_timeline { $_[0]->{timeline} } | ||
| 200 | sub yahc_conn_request { $_[0]->{request} } | ||
| 201 | sub yahc_conn_response { $_[0]->{response} } | ||
| 202 | sub yahc_conn_retries_left { $_[0]->{retries} - $_[0]->{attempt} } | ||
| 203 | |||
| 204 | sub yahc_conn_target { | ||
| 205 | my $target = $_[0]->{selected_target}; | ||
| 206 | return unless $target && scalar @{ $target }; | ||
| 207 | my ($host, $ip, $port) = @{ $target }; | ||
| 208 | return ($host || $ip) . ($port ne "80" ? ":$port" : ''); | ||
| 209 | } | ||
| 210 | |||
| 211 | sub yahc_conn_url { | ||
| 212 | my $target = $_[0]->{selected_target}; | ||
| 213 | my $request = $_[0]->{request}; | ||
| 214 | return unless $target && @{ $target }; | ||
| 215 | |||
| 216 | my ($host, $ip, $port) = @{ $target }; | ||
| 217 | return $request->{scheme} . "://" | ||
| 218 | . ($host || $ip) | ||
| 219 | . ($port ne "80" ? ":$port" : '') | ||
| 220 | . ($request->{path} || "/") | ||
| 221 | . (defined $request->{query_string} ? ("?" . $request->{query_string}) : ""); | ||
| 222 | } | ||
| 223 | |||
| 224 | ################################################################################ | ||
| 225 | # Internals | ||
| 226 | ################################################################################ | ||
| 227 | |||
| 228 | sub _run { | ||
| 229 | my ($self, $how, $until_state, @cs) = @_; | ||
| 230 | die "YAHC: storage object is destroyed\n" unless $self->{storage}; | ||
| 231 | |||
| 232 | if ($self->{pid} != $$) { | ||
| 233 | _log_message('Reinitializing event loop after forking') if $self->{debug}; | ||
| 234 | $self->{pid} = $$; | ||
| 235 | $self->{loop}->loop_fork; | ||
| 236 | } | ||
| 237 | |||
| 238 | if (defined $until_state) { | ||
| 239 | my $until_state_str = _strstate($until_state); | ||
| 240 | die "YAHC: unknown until_state $until_state\n" if $until_state_str =~ m/unknown/; | ||
| 241 | |||
| 242 | my @connections = (@cs == 0) | ||
| 243 | ? values %{ $self->{connections} } | ||
| 244 | : map { $self->{connections}{$_} || () } | ||
| 245 | map { ref($_) eq 'HASH' ? $_->{id} : $_ } @cs; | ||
| 246 | |||
| 247 | $self->{stop_condition} = { | ||
| 248 | expected_state => $until_state, | ||
| 249 | connections => { map { $_->{id} => 1 } grep { $_->{state} < $until_state } @connections }, | ||
| 250 | }; | ||
| 251 | } else { | ||
| 252 | delete $self->{stop_condition}; | ||
| 253 | } | ||
| 254 | |||
| 255 | my $loop = $self->{loop}; | ||
| 256 | $loop->now_update; | ||
| 257 | return $loop->run($how || 0) unless $self->{debug}; # shortcut | ||
| 258 | |||
| 259 | my $iterations = $loop->iteration; | ||
| 260 | _log_message('pid %d entering event loop%s', $$, ($until_state ? " with until state " . _strstate($until_state) : '')); | ||
| 261 | $loop->run($how || 0); | ||
| 262 | _log_message('pid %d exited from event loop after %d iterations', $$, $loop->iteration - $iterations); | ||
| 263 | } | ||
| 264 | |||
| 265 | sub _break { | ||
| 266 | my ($self, $reason) = @_; | ||
| 267 | _log_message('pid %d breaking event loop because %s', $$, ($reason || 'no reason')) if $self->{debug}; | ||
| 268 | $self->{loop}->break(EV::BREAK_ONE) | ||
| 269 | } | ||
| 270 | |||
| 271 | sub _check_stop_condition { | ||
| 272 | my ($self, $conn) = @_; | ||
| 273 | my $stop_condition = $self->{stop_condition}; | ||
| 274 | return if !$stop_condition || $conn->{state} < $stop_condition->{expected_state}; | ||
| 275 | |||
| 276 | delete $stop_condition->{connections}{$conn->{id}}; | ||
| 277 | my $awaiting_connections = scalar keys %{ $stop_condition->{connections} }; | ||
| 278 | my $expected_state = $stop_condition->{expected_state}; | ||
| 279 | |||
| 280 | if ($awaiting_connections == 0) { | ||
| 281 | $self->_break(sprintf("until state '%s' is reached", _strstate($expected_state))); | ||
| 282 | } else { | ||
| 283 | _log_message("Still have %d connections awaiting state '%s'", | ||
| 284 | $awaiting_connections, _strstate($expected_state)) if $self->{debug}; | ||
| 285 | } | ||
| 286 | } | ||
| 287 | |||
| 288 | ################################################################################ | ||
| 289 | # IO routines | ||
| 290 | ################################################################################ | ||
| 291 | |||
| 292 | sub _set_init_state { | ||
| 293 | my ($self, $conn_id) = @_; | ||
| 294 | |||
| 295 | my $conn = $self->{connections}{$conn_id} or die "YAHC: unknown connection id $conn_id\n"; | ||
| 296 | my $watchers = $self->{watchers}{$conn_id} or die "YAHC: no watchers for connection id $conn_id\n"; | ||
| 297 | |||
| 298 | $conn->{response} = { status_code => 0 }; | ||
| 299 | $conn->{state} = YAHC::State::INITIALIZED(); | ||
| 300 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 301 | $self->_call_state_callback($conn, 'init_callback') if $conn->{has_init_callback}; | ||
| 302 | |||
| 303 | my $continue = 1; | ||
| 304 | while ($continue) { | ||
| 305 | if (my $w = delete $watchers->{io}) { | ||
| 306 | $w->stop; | ||
| 307 | shutdown($w->fh, 2); | ||
| 308 | } | ||
| 309 | |||
| 310 | my $attempt = $conn->{attempt}++; | ||
| 311 | if ($attempt > $conn->{retries}) { | ||
| 312 | $self->_set_user_action_state($conn_id, YAHC::Error::CONNECT_ERROR(), "retries limit reached"); | ||
| 313 | return; | ||
| 314 | } | ||
| 315 | |||
| 316 | # If later I would need timeout covering multiple attempts | ||
| 317 | # I can set them here under $attempt == 0 condition. | ||
| 318 | # Also, in _set_until_state_timer I would go to USER_ACTION_STATE | ||
| 319 | # instead of reinitializing connection. | ||
| 320 | |||
| 321 | $self->_set_request_timer($conn_id) if $conn->{request}{request_timeout}; | ||
| 322 | $self->_set_connection_timer($conn_id) if $conn->{request}{connect_timeout}; | ||
| 323 | $self->_set_drain_timer($conn_id) if $conn->{request}{drain_timeout}; | ||
| 324 | |||
| 325 | eval { | ||
| 326 | my ($host, $ip, $port) = _get_next_target($conn); | ||
| 327 | _register_in_timeline($conn, "Target $host:$port ($ip:$port) chosen for attempt #$attempt") if $conn->{keep_timeline}; | ||
| 328 | |||
| 329 | my $sock = _build_socket_and_connect($ip, $port, $conn->{request}); | ||
| 330 | $self->_set_wait_synack_state($conn_id, $sock, $ip, $host, $port); | ||
| 331 | $continue = 0; | ||
| 332 | 1; | ||
| 333 | } or do { | ||
| 334 | my $error = $@ || 'zombie error'; | ||
| 335 | _register_error($conn, YAHC::Error::CONNECT_ERROR(), "Connection attempt #$attempt for $conn_id has failed: $error"); | ||
| 336 | #$self->_set_set_init_state_timer($conn_id); # trigger background timer which will do reconnection attempt # TODO | ||
| 337 | #$continue = 0; | ||
| 338 | }; | ||
| 339 | } | ||
| 340 | } | ||
| 341 | |||
| 342 | sub _set_wait_synack_state { | ||
| 343 | my ($self, $conn_id, $sock, $ip, $host, $port) = @_; | ||
| 344 | |||
| 345 | my $conn = $self->{connections}{$conn_id} or die "YAHC: unknown connection id $conn_id\n"; | ||
| 346 | my $watchers = $self->{watchers}{$conn_id} or die "YAHC: no watchers for connection id $conn_id\n"; | ||
| 347 | _assert_state($conn, YAHC::State::INITIALIZED()) if $conn->{debug}; | ||
| 348 | |||
| 349 | $conn->{state} = YAHC::State::WAIT_SYNACK(); | ||
| 350 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 351 | $self->_call_state_callback($conn, 'wait_synack_callback') if $conn->{has_wait_synack_callback}; | ||
| 352 | |||
| 353 | my $wait_synack_cb = $self->_get_safe_wrapper($conn, sub { | ||
| 354 | my $sockopt = getsockopt($sock, SOL_SOCKET, SO_ERROR); | ||
| 355 | if (!$sockopt) { | ||
| 356 | _register_error($conn, YAHC::Error::CONNECT_ERROR(), "Failed to do getsockopt(): $!"); | ||
| 357 | $self->_set_init_state($conn_id); | ||
| 358 | return; | ||
| 359 | } | ||
| 360 | |||
| 361 | if (my $err = unpack("L", $sockopt)) { | ||
| 362 | my $strerror = POSIX::strerror($err) || '<unknown POSIX error>'; | ||
| 363 | _register_error($conn, YAHC::Error::CONNECT_ERROR(), "Failed to connect to $host:$port ($ip:$port): $strerror"); | ||
| 364 | $self->_set_init_state($conn_id); | ||
| 365 | return; | ||
| 366 | } | ||
| 367 | |||
| 368 | $conn->{state} = YAHC::State::CONNECTED(); | ||
| 369 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 370 | $self->_call_state_callback($conn, 'connected_callback') if $conn->{has_connected_callback}; | ||
| 371 | |||
| 372 | $self->_set_write_state($conn_id); | ||
| 373 | }); | ||
| 374 | |||
| 375 | $watchers->{io} = $self->{loop}->io($sock, EV::WRITE, $wait_synack_cb); | ||
| 376 | $self->_check_stop_condition($conn) if $self->{stop_condition}; | ||
| 377 | } | ||
| 378 | |||
| 379 | sub _set_write_state { | ||
| 380 | my ($self, $conn_id) = @_; | ||
| 381 | |||
| 382 | my $conn = $self->{connections}{$conn_id} or die "YAHC: unknown connection id $conn_id\n"; | ||
| 383 | my $watcher = $self->{watchers}{$conn_id}{io} or die "YAHC: no watchers for connection id $conn_id\n"; | ||
| 384 | _assert_connected($conn) if $conn->{debug}; | ||
| 385 | |||
| 386 | $conn->{state} = YAHC::State::WRITING(); | ||
| 387 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 388 | $self->_call_state_callback($conn, 'writing_callback') if $conn->{has_writing_callback}; | ||
| 389 | |||
| 390 | my $fd = fileno($watcher->fh); | ||
| 391 | my $buf = _build_http_message($conn); | ||
| 392 | my $length = length($buf); | ||
| 393 | |||
| 394 | _register_in_timeline($conn, "sending request of $length bytes") if $conn->{keep_timeline}; | ||
| 395 | |||
| 396 | my $write_cb = $self->_get_safe_wrapper($conn, sub { | ||
| 397 | my $wlen = POSIX::write($fd, $buf, $length); | ||
| 398 | |||
| 399 | if (!defined $wlen || $wlen == 0) { | ||
| 400 | return if $! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR; | ||
| 401 | |||
| 402 | my $error = !defined $wlen | ||
| 403 | ? "Failed to send TCP data: $!" | ||
| 404 | : "Bizzare!!! syswrite returned 0"; # wlen == 0 | ||
| 405 | |||
| 406 | _register_error($conn, YAHC::Error::WRITE_ERROR(), $error); | ||
| 407 | $self->_set_init_state($conn_id); | ||
| 408 | } else { | ||
| 409 | substr($buf, 0, $wlen, ''); | ||
| 410 | $length -= $wlen; | ||
| 411 | $self->_set_read_state($conn_id) if $length == 0; | ||
| 412 | } | ||
| 413 | }); | ||
| 414 | |||
| 415 | $watcher->cb($write_cb); | ||
| 416 | $watcher->events(EV::WRITE); | ||
| 417 | $self->_check_stop_condition($conn) if $self->{stop_condition}; | ||
| 418 | } | ||
| 419 | |||
| 420 | sub _set_read_state { | ||
| 421 | my ($self, $conn_id) = @_; | ||
| 422 | |||
| 423 | my $conn = $self->{connections}{$conn_id} or die "YAHC: unknown connection id $conn_id\n"; | ||
| 424 | my $watcher = $self->{watchers}{$conn_id}{io} or die "YAHC: no watchers for connection id $conn_id\n"; | ||
| 425 | _assert_connected($conn) if $conn->{debug}; | ||
| 426 | |||
| 427 | $conn->{state} = YAHC::State::READING(); | ||
| 428 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 429 | $self->_call_state_callback($conn, 'reading_callback') if $conn->{has_reading_callback}; | ||
| 430 | |||
| 431 | my $buf = ''; | ||
| 432 | my $neck_pos = 0; | ||
| 433 | my $decapitated = 0; | ||
| 434 | my $content_length = 0; | ||
| 435 | my $fd = fileno($watcher->fh); | ||
| 436 | |||
| 437 | my $read_cb = $self->_get_safe_wrapper($conn, sub { | ||
| 438 | my $rlen = POSIX::read($fd, my $b = '', TCP_READ_CHUNK); | ||
| 439 | |||
| 440 | if (!defined $rlen || $rlen == 0) { | ||
| 441 | return if $! == EWOULDBLOCK || $! == EAGAIN || $! == EINTR; | ||
| 442 | if (not defined $rlen) { | ||
| 443 | _register_error($conn, YAHC::Error::READ_ERROR(), "Failed to receive TCP data: $!"); | ||
| 444 | } elsif ($content_length > 0) { # i.e. rlen == 0 and $content_length > 0 | ||
| 445 | _register_error($conn, YAHC::Error::READ_ERROR(), "Premature EOF, expect %d bytes more", $content_length - length($buf)); | ||
| 446 | } else { # i.e. rlen == 0 | ||
| 447 | _register_error($conn, YAHC::Error::READ_ERROR(), "Premature EOF"); | ||
| 448 | } | ||
| 449 | |||
| 450 | $self->_set_init_state($conn_id); | ||
| 451 | } else { | ||
| 452 | $buf .= $b; | ||
| 453 | if (!$decapitated && ($neck_pos = index($buf, "${CRLF}${CRLF}")) > 0) { | ||
| 454 | my $headers = _parse_http_headers($conn, substr($buf, 0, $neck_pos, '')); | ||
| 455 | if (not defined $headers) { | ||
| 456 | $self->_set_user_action_state($conn_id, YAHC::Error::RESPONSE_ERROR(), "unsupported HTTP reponse"); | ||
| 457 | return; | ||
| 458 | } | ||
| 459 | |||
| 460 | $decapitated = 1; | ||
| 461 | $content_length = $headers->{'Content-Length'}; | ||
| 462 | substr($buf, 0, 4, ''); # 4 = length("$CRLF$CRLF") | ||
| 463 | _register_in_timeline($conn, "headers parsed: content-length='%d' content-type='%s'", | ||
| 464 | $content_length, $headers->{'Content-Type'} || '<no-content-type>') if $conn->{keep_timeline}; | ||
| 465 | } | ||
| 466 | |||
| 467 | if ($decapitated && length($buf) >= $content_length) { | ||
| 468 | $buf = substr($buf, 0, $content_length) if length($buf) > $content_length; | ||
| 469 | $conn->{response}{body} = $buf; | ||
| 470 | $self->_set_user_action_state($conn_id); | ||
| 471 | } | ||
| 472 | } | ||
| 473 | }); | ||
| 474 | |||
| 475 | $watcher->cb($read_cb); | ||
| 476 | $watcher->events(EV::READ); | ||
| 477 | $self->_check_stop_condition($conn) if $self->{stop_condition}; | ||
| 478 | } | ||
| 479 | |||
| 480 | sub _set_user_action_state { | ||
| 481 | my ($self, $conn_id, $error, $strerror) = @_; | ||
| 482 | $error ||= YAHC::Error::NO_ERROR(); | ||
| 483 | $strerror ||= '<no strerror>'; | ||
| 484 | |||
| 485 | # this state may be used in critical places, | ||
| 486 | # so it should *NEVER* throw exception | ||
| 487 | my $conn = $self->{connections}{$conn_id} | ||
| 488 | or warn "YAHC: try to _set_user_action_state() for unknown connection $conn_id", | ||
| 489 | return; | ||
| 490 | |||
| 491 | $conn->{state} = YAHC::State::USER_ACTION(); | ||
| 492 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 493 | _register_error($conn, $error, $strerror) if $error; | ||
| 494 | |||
| 495 | return $self->_set_completed_state($conn_id) unless $conn->{has_callback}; | ||
| 496 | my $cb = $self->{callbacks}{$conn_id}{callback}; | ||
| 497 | |||
| 498 | eval { | ||
| 499 | _register_in_timeline($conn, "call callback%s", $error ? " error=$error, strerror='$strerror'" : '') if $conn->{keep_timeline}; | ||
| 500 | $cb->($conn, $error, $strerror); | ||
| 501 | 1; | ||
| 502 | } or do { | ||
| 503 | my $error = $@ || 'zombie error'; | ||
| 504 | _register_error($conn, YAHC::Error::CALLBACK_ERROR(), "Exception in user action callback (close connection): $error"); | ||
| 505 | warn "YAHC: exception in user action callback (close connection): $error"; | ||
| 506 | $self->{state} = YAHC::State::COMPLETED(); | ||
| 507 | }; | ||
| 508 | |||
| 509 | $self->{loop}->now_update; | ||
| 510 | |||
| 511 | my $state = $conn->{state}; | ||
| 512 | _register_in_timeline($conn, "after invoking callback state is %s", _strstate($state)) if $conn->{keep_timeline}; | ||
| 513 | |||
| 514 | if ($state == YAHC::State::INITIALIZED()) { | ||
| 515 | $self->_set_init_state($conn_id); # TODO eval | ||
| 516 | } elsif ($state == YAHC::State::USER_ACTION() || $state == YAHC::State::COMPLETED()) { | ||
| 517 | $self->_set_completed_state($conn_id); | ||
| 518 | } else { | ||
| 519 | _register_error($conn, YAHC::Error::CALLBACK_ERROR(), "callback set unsupported state"); | ||
| 520 | $self->_set_completed_state($conn_id); | ||
| 521 | } | ||
| 522 | } | ||
| 523 | |||
| 524 | sub _set_completed_state { | ||
| 525 | my ($self, $conn_id) = @_; | ||
| 526 | |||
| 527 | # this's a terminal state, | ||
| 528 | # so setting this state should *NEVER* fail | ||
| 529 | delete $self->{callbacks}{$conn_id}; | ||
| 530 | my $watchers = delete $self->{watchers}{$conn_id}; | ||
| 531 | my $conn = $self->{connections}{$conn_id} | ||
| 532 | or warn "YAHC: try to _set_completed_state() for unknown connection $conn_id", | ||
| 533 | return; | ||
| 534 | |||
| 535 | $conn->{state} = YAHC::State::COMPLETED(); | ||
| 536 | _register_in_timeline($conn, "new state %s", _strstate($conn->{state})) if $conn->{keep_timeline}; | ||
| 537 | |||
| 538 | if (my $w = delete $watchers->{io}) { | ||
| 539 | $w->stop; | ||
| 540 | shutdown($w->fh, 2) | ||
| 541 | } | ||
| 542 | |||
| 543 | $_->stop foreach (values %{ $watchers || {} }); | ||
| 544 | |||
| 545 | eval { $self->_check_stop_condition($conn) } if $self->{stop_condition}; | ||
| 546 | } | ||
| 547 | |||
| 548 | sub _build_socket_and_connect { | ||
| 549 | my ($ip, $port, $timeouts) = @_; | ||
| 550 | |||
| 551 | my $sock; | ||
| 552 | socket($sock, PF_INET, SOCK_STREAM, 0) or die "YAHC: Failed to construct TCP socket: $!\n"; | ||
| 553 | |||
| 554 | my $flags = fcntl($sock, F_GETFL, 0) or die "YAHC: Failed to get fcntl F_GETFL flag: $!\n"; | ||
| 555 | fcntl($sock, F_SETFL, $flags | O_NONBLOCK) or die "YAHC: Failed to set fcntl O_NONBLOCK flag: $!\n"; | ||
| 556 | |||
| 557 | my $ip_addr = inet_aton($ip); | ||
| 558 | my $addr = pack_sockaddr_in($port, $ip_addr); | ||
| 559 | if (!connect($sock, $addr) && $! != EINPROGRESS) { | ||
| 560 | die "YAHC: Failed to connect to $ip: $!\n"; | ||
| 561 | } | ||
| 562 | |||
| 563 | return $sock; | ||
| 564 | } | ||
| 565 | |||
| 566 | sub _get_next_target { | ||
| 567 | my $conn = shift; | ||
| 568 | my ($host, $ip, $port) = $conn->{request}{_target}->(); | ||
| 569 | |||
| 570 | # TODO STATE_RESOLVE_DNS | ||
| 571 | ($host, $port) = ($1, $2) if $host =~ m/^(.+):([0-9]+)$/o; | ||
| 572 | $ip = $host if $host =~ m/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/o; | ||
| 573 | $ip = inet_ntoa(gethostbyname($host) or die "Failed to resolve '$host': $!\n") unless $ip; | ||
| 574 | $port ||= $conn->{request}{port} || HTTP_PORT; | ||
| 575 | |||
| 576 | return @{ $conn->{selected_target} = [ $host, $ip, $port ] }; | ||
| 577 | } | ||
| 578 | |||
| 579 | ################################################################################ | ||
| 580 | # Timers | ||
| 581 | ################################################################################ | ||
| 582 | |||
| 583 | sub _set_request_timer { $_[0]->_set_until_state_timer($_[1], 'request_timeout', YAHC::State::USER_ACTION(), YAHC::Error::REQUEST_TIMEOUT()) } | ||
| 584 | sub _set_connection_timer { $_[0]->_set_until_state_timer($_[1], 'connect_timeout', YAHC::State::CONNECTED(), YAHC::Error::CONNECT_TIMEOUT()) } | ||
| 585 | sub _set_drain_timer { $_[0]->_set_until_state_timer($_[1], 'drain_timeout', YAHC::State::READING(), YAHC::Error::DRAIN_TIMEOUT()) } | ||
| 586 | |||
| 587 | sub _set_until_state_timer { | ||
| 588 | my ($self, $conn_id, $timeout_name, $state, $error_to_report) = @_; | ||
| 589 | |||
| 590 | my $timer_name = $timeout_name . '_timer'; | ||
| 591 | my $conn = $self->{connections}{$conn_id} or die "YAHC: unknown connection id $conn_id\n"; | ||
| 592 | my $watchers = $self->{watchers}{$conn_id} or die "YAHC: no watchers for connection id $conn_id\n"; | ||
| 593 | |||
| 594 | if (my $timer = delete $watchers->{$timer_name}) { | ||
| 595 | $timer->stop; | ||
| 596 | } | ||
| 597 | |||
| 598 | my $timeout = $conn->{request}{$timeout_name}; | ||
| 599 | return unless $timeout; | ||
| 600 | |||
| 601 | my $timer_cb = $self->_get_safe_wrapper($conn, sub { | ||
| 602 | if ($conn->{state} < $state) { | ||
| 603 | _register_error($conn, $error_to_report, "$timeout_name of %.3fs expired", $timeout); | ||
| 604 | $self->_set_init_state($conn_id); | ||
| 605 | } else { | ||
| 606 | _register_in_timeline($conn, "delete $timer_name") if $conn->{keep_timeline}; | ||
| 607 | } | ||
| 608 | }); | ||
| 609 | |||
| 610 | _register_in_timeline($conn, "setting $timeout_name to %.3fs", $timeout) if $conn->{keep_timeline}; | ||
| 611 | $watchers->{$timer_name} = $self->{loop}->timer($timeout, 0, $timer_cb); | ||
| 612 | $watchers->{$timer_name}->priority(-2); # set lowest priority | ||
| 613 | } | ||
| 614 | |||
| 615 | ################################################################################ | ||
| 616 | # HTTP functions | ||
| 617 | ################################################################################ | ||
| 618 | |||
| 619 | # copy-paste from Hijk | ||
| 620 | sub _build_http_message { | ||
| 621 | my $conn = shift; | ||
| 622 | my $request = $conn->{request}; | ||
| 623 | my $path_and_qs = ($request->{path} || "/") . (defined $request->{query_string} ? ("?" . $request->{query_string}) : ""); | ||
| 624 | |||
| 625 | return join( | ||
| 626 | $CRLF, | ||
| 627 | ($request->{method} || "GET") . " $path_and_qs " . ($request->{protocol} || "HTTP/1.1"), | ||
| 628 | "Host: " . $conn->{selected_target}[0], | ||
| 629 | $request->{body} ? ("Content-Length: " . length($request->{body})) : (), | ||
| 630 | $request->{head} ? ( | ||
| 631 | map { | ||
| 632 | $request->{head}[2*$_] . ": " . $request->{head}[2*$_+1] | ||
| 633 | } 0..$#{$request->{head}}/2 | ||
| 634 | ) : (), | ||
| 635 | "", | ||
| 636 | $request->{body} ? $request->{body} : "" | ||
| 637 | ); | ||
| 638 | } | ||
| 639 | |||
| 640 | sub _parse_http_headers { | ||
| 641 | my $conn = shift; | ||
| 642 | my $proto = substr($_[0], 0, 8); | ||
| 643 | my $status_code = substr($_[0], 9, 3); | ||
| 644 | substr($_[0], 0, index($_[0], $CRLF) + 2, ''); # 2 = length($CRLF) | ||
| 645 | |||
| 646 | my %headers; | ||
| 647 | for (split /${CRLF}/o, $_[0]) { | ||
| 648 | my ($key, $value) = split(/: /, $_, 2); | ||
| 649 | $headers{$key} = $value; | ||
| 650 | } | ||
| 651 | |||
| 652 | $conn->{response} = { | ||
| 653 | proto => $proto, | ||
| 654 | status_code => $status_code, | ||
| 655 | headers => \%headers, | ||
| 656 | }; | ||
| 657 | |||
| 658 | return \%headers; | ||
| 659 | } | ||
| 660 | |||
| 661 | ################################################################################ | ||
| 662 | # Helpers | ||
| 663 | ################################################################################ | ||
| 664 | |||
| 665 | sub _wrap_target_selection { | ||
| 666 | my $host = shift; | ||
| 667 | my $ref = ref($host); | ||
| 668 | |||
| 669 | return sub { $host } if $ref eq ''; | ||
| 670 | return $host if $ref eq 'CODE'; | ||
| 671 | |||
| 672 | my $idx = 0; | ||
| 673 | return sub { $host->[$idx++ % @$host]; } if $ref eq 'ARRAY'; | ||
| 674 | die "YAHC: unsupported host format\n"; | ||
| 675 | } | ||
| 676 | |||
| 677 | sub _call_state_callback { | ||
| 678 | my ($self, $conn, $cb_name) = @_; | ||
| 679 | my $cb = $self->{callbacks}{$conn->{id}}{$cb_name}; | ||
| 680 | return unless $cb; | ||
| 681 | |||
| 682 | eval { | ||
| 683 | $cb->($conn); | ||
| 684 | 1; | ||
| 685 | } or do { | ||
| 686 | my $error = $@ || 'zombie error'; | ||
| 687 | _register_error($conn, YAHC::Error::CALLBACK_ERROR(), "Exception in state callback (ignore error): $error"); | ||
| 688 | warn "YAHC: exception in state callback (ignore error): $error"; | ||
| 689 | }; | ||
| 690 | |||
| 691 | # $self->{loop}->now_update; # XXX expect state callbacks to be small | ||
| 692 | } | ||
| 693 | |||
| 694 | sub _get_safe_wrapper { | ||
| 695 | my ($self, $conn, $sub) = @_; | ||
| 696 | return sub { eval { | ||
| 697 | $sub->(@_); | ||
| 698 | 1; | ||
| 699 | } or do { | ||
| 700 | my $error = $@ || 'zombie error'; | ||
| 701 | _register_error($conn, YAHC::Error::INTERNAL_ERROR(), "Exception callback: $error"); | ||
| 702 | warn "YAHC: exception in callback: $error"; | ||
| 703 | $self->_set_completed_state($conn->{id}); | ||
| 704 | }}; | ||
| 705 | } | ||
| 706 | |||
| 707 | sub _register_in_timeline { | ||
| 708 | my ($conn, $format, @arguments) = @_; | ||
| 709 | my $event = sprintf("$format", @arguments); | ||
| 710 | $event =~ s/\s+$//g; | ||
| 711 | _log_message("YAHC connection '%s': %s", $conn->{id}, $event) if $conn->{debug}; | ||
| 712 | push @{ $conn->{timeline} ||= [] }, [ $event, $conn->{state}, Time::HiRes::time ] if $conn->{keep_timeline}; | ||
| 713 | } | ||
| 714 | |||
| 715 | sub _register_error { | ||
| 716 | my ($conn, $error, $format, @arguments) = @_; | ||
| 717 | my $strerror = sprintf("$format", @arguments); | ||
| 718 | $strerror =~ s/\s+$//g; | ||
| 719 | _register_in_timeline($conn, "error=$error ($strerror)") if $conn->{debug}; | ||
| 720 | push @{ $conn->{errors} ||= [] }, [ $error, $strerror, yahc_conn_target($conn) // 'no_target_yet', Time::HiRes::time ]; | ||
| 721 | } | ||
| 722 | |||
| 723 | sub _assert_state { | ||
| 724 | my ($conn, $expected_state) = @_; | ||
| 725 | return $conn->{state} == $expected_state; | ||
| 726 | die sprintf("YAHC connection '%s' is in unexpected state %s, expected %s\n", | ||
| 727 | $conn->{id}, _strstate($conn->{state}), _strstate($expected_state)); | ||
| 728 | } | ||
| 729 | |||
| 730 | sub _assert_connected { | ||
| 731 | my $conn = shift; | ||
| 732 | return if $conn->{state} >= YAHC::State::CONNECTED() && $conn->{state} < YAHC::State::COMPLETED(); | ||
| 733 | die sprintf("YAHC connection '%s' expected to be in connected state, but it's in %s\n", | ||
| 734 | $conn->{id}, _strstate($conn->{state})); | ||
| 735 | } | ||
| 736 | |||
| 737 | sub _strstate { | ||
| 738 | my $state = shift; | ||
| 739 | return 'STATE_INIT' if $state eq YAHC::State::INITIALIZED(); | ||
| 740 | return 'STATE_RESOLVE_DNS' if $state eq YAHC::State::RESOLVE_DNS(); | ||
| 741 | return 'STATE_WAIT_SYNACK' if $state eq YAHC::State::WAIT_SYNACK(); | ||
| 742 | return 'STATE_CONNECTED' if $state eq YAHC::State::CONNECTED(); | ||
| 743 | return 'STATE_WRITING' if $state eq YAHC::State::WRITING(); | ||
| 744 | return 'STATE_READING' if $state eq YAHC::State::READING(); | ||
| 745 | return 'STATE_USER_ACTION' if $state eq YAHC::State::USER_ACTION(); | ||
| 746 | return 'STATE_COMPLETED' if $state eq YAHC::State::COMPLETED(); | ||
| 747 | return "<unknown state $state>"; | ||
| 748 | } | ||
| 749 | |||
| 750 | sub _log_message { | ||
| 751 | my $format = shift; | ||
| 752 | printf STDERR "[%s] [$$] $format\n", POSIX::strftime('%F %T', localtime), @_; | ||
| 753 | } | ||
| 754 | |||
| 755 | 1; | ||
| 756 | |||
| 757 | __END__ |