From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id 91C551FF09F for ; Tue, 01 Dec 2026 11:21:07 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 42EE521741; Tue, 01 Dec 2026 11:20:32 +0100 (CET) From: Thomas Lamprecht To: pve-devel@lists.proxmox.com Subject: [PATCH http-server v2 3/9] response: support incremental streaming API2 responses Date: Tue, 1 Dec 2026 11:18:58 +0100 Message-ID: <20261201101913.1885484-4-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261201101913.1885484-1-t.lamprecht@proxmox.com> References: <20261201101913.1885484-1-t.lamprecht@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796120358830 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.148 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: 5TP75N5Z2UJQFCBTOHKDILUS7XFSKQLH X-Message-ID-Hash: 5TP75N5Z2UJQFCBTOHKDILUS7XFSKQLH X-MailFrom: t.lamprecht@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox VE development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: Deferred async API2 responses still buffer, format, and compress the entire payload in one blocking pass. When PDM or monitoring scrapes large clusters via /api2/extjs/ or /api2/json/cluster/metrics/export (especially with history=1), materializing and compressing hundreds of megabytes inside a pveproxy worker drives RSS into gigabytes and stalls the event loop for seconds. Add async_stream_response() and PVE::APIServer::AsyncStream so handlers can emit formatted output incrementally. HTTP/1.1 clients receive chunked responses with keep-alive preserved, while HTTP/1.0 clients fall back to a close-delimited stream. Output is compressed on the fly with Compress::Raw::Zlib at level 2 (gzip or deflate) when accepted. Writes signal backpressure above 4 MiB queued, and on_drain() arms a write timeout so stalled clients disconnect. AsyncStream owns the outer API2 envelope for supported formats: json wraps the streamed value in {"data":...} and extjs wraps it in {"data":...,"success":1}. Handlers check the no-argument async_stream_supported() helper and emit only the inner JSON value, while unsupported formats are rejected in start_async_stream(). Trade-offs: level 2 produces a ~47% larger compressed payload than memGzip level 6 on 17.8 MiB of metric JSON (still 8.2x vs 12.1x ratio) in exchange for ~12x faster compression (769 ms -> 64 ms). Once 200 OK headers are sent, fatal aborts omit the closing envelope and reset the TCP connection (SO_LINGER) rather than returning HTTP 5xx so clients cannot mistake truncated output for a complete response. In a single-worker 100-node x 10,000-guest (10M metrics) harness, streaming cut worker peak VmHWM from 9.02 GiB to ~209 MiB, total export time from 53.1 s to 15.5 s (sorted) or 9.1 s (unsorted), and concurrent /ping stalls on the same worker from 47.2 s to 37 ms. Signed-off-by: Thomas Lamprecht --- Changes in v2: - Check that the selected formatter is the standard json or extjs formatter in async_stream_supported() so method/path page formatters are never silently bypassed. - Validate the HTTP status code as a 3-digit 1xx-5xx value and route compressor initialization failures through abort() in AsyncStream::start() before writing headers. - Defer keep-alive connection reuse in AsyncStream::finish() onto on_drain() with wtimeout when the final slice crosses buf_size, and keep a write-only wtimeout active while draining non-reusable connections. - Document the top-level dispatch, RPC state capture, UTF-8 JSON bytes, 2xx envelope, backpressure on_drain(sub { ... }), deadline, and cancel-on-disconnect/abort contracts. src/Makefile | 1 + src/PVE/APIServer/AnyEvent.pm | 104 +++++++- src/PVE/APIServer/AsyncStream.pm | 411 +++++++++++++++++++++++++++++++ 3 files changed, 513 insertions(+), 3 deletions(-) create mode 100644 src/PVE/APIServer/AsyncStream.pm diff --git a/src/Makefile b/src/Makefile index 50861bd..be6bcf9 100644 --- a/src/Makefile +++ b/src/Makefile @@ -7,6 +7,7 @@ all: install: PVE install -d -m 755 ${PERL5DIR}/PVE/APIServer install -m 0644 PVE/APIServer/AnyEvent.pm ${PERL5DIR}/PVE/APIServer + install -m 0644 PVE/APIServer/AsyncStream.pm ${PERL5DIR}/PVE/APIServer install -m 0644 PVE/APIServer/Formatter.pm ${PERL5DIR}/PVE/APIServer install -m 0644 PVE/APIServer/Utils.pm ${PERL5DIR}/PVE/APIServer install -d -m 755 ${PERL5DIR}/PVE/APIServer/Formatter diff --git a/src/PVE/APIServer/AnyEvent.pm b/src/PVE/APIServer/AnyEvent.pm index 8f77737..4cf8074 100644 --- a/src/PVE/APIServer/AnyEvent.pm +++ b/src/PVE/APIServer/AnyEvent.pm @@ -46,6 +46,7 @@ use PVE::INotify; use PVE::SafeSyslog; use PVE::Tools qw(trim); +use PVE::APIServer::AsyncStream; use PVE::APIServer::Formatter; use PVE::APIServer::Utils; @@ -55,20 +56,46 @@ my $limit_max_post = 512 * 1024; my $limit_max_request_line = 64 * 1024; my $ASYNC_SUPPORTED = 0; +my $ASYNC_STREAM_SUPPORTED = 0; sub async_supported { return $ASYNC_SUPPORTED; } +# Returns true only inside handle_api2_request() when the request uses the standard json or extjs +# formatter (not a method/path page formatter). Streaming handlers pass UTF-8-encoded JSON bytes +# for the inner `data` value; the server owns the outer envelope and does not emit `total` or +# `changes` attributes. +sub async_stream_supported { + return $ASYNC_STREAM_SUPPORTED; +} + # Wrap a deferred API2 response starter: sub ($resolve, $reject) -> optional cancel coderef. -# The server disables its inactivity timeout while waiting; the starter must bound its own wait -# and may return a cancel callback invoked on client disconnect. +# Only top-level API2 responses directly under $res->{data} are dispatched asynchronously. Handlers +# must capture any request-specific RPC state (such as user or credentials) before returning, as +# rest_handler() clears it before the starter runs. The server disables its inactivity timeout +# while waiting; the starter owns its deadline and may return a cancel callback invoked on client +# disconnect. sub async_response { my ($starter) = @_; die "async_response requires a CODE ref\n" if ref($starter) ne 'CODE'; return bless { start => $starter }, 'PVE::APIServer::AnyEvent::AsyncResponse'; } +# Wrap a deferred streaming API2 response starter: sub ($stream) -> optional cancel coderef. +# Only top-level API2 responses directly under $res->{data} are dispatched asynchronously; handlers +# must capture any request-specific RPC state before returning. The starter owns its deadline, and +# its optional cancel callback runs on client disconnect or stream abort (including pre-start +# abort). Pass UTF-8-encoded JSON bytes for the inner `data` value to $stream->write(); the server +# wraps body-bearing 2xx responses in the outer json or extjs envelope (without `total` or +# `changes` attributes). For a formatted API error, call $stream->abort($err) before +# $stream->start(). +sub async_stream_response { + my ($starter) = @_; + die "async_stream_response requires a CODE ref\n" if ref($starter) ne 'CODE'; + return bless { start => $starter }, 'PVE::APIServer::AnyEvent::AsyncStreamResponse'; +} + my $known_methods = { GET => 1, POST => 1, @@ -1236,6 +1263,45 @@ my sub start_async_response { ); } +my sub start_async_stream { + my ($self, $reqstate, $async_stream, $res, $finish, $format, $stream_supported) = @_; + + if ( + ref($async_stream) ne 'PVE::APIServer::AnyEvent::AsyncStreamResponse' + || ref($async_stream->{start}) ne 'CODE' + ) { + die "invalid async stream response\n"; + } + + if (!$stream_supported) { + die "unsupported async stream format\n"; + } + + return if !prepare_async_handle($reqstate); + + my $stream = PVE::APIServer::AsyncStream->new( + server => $self, + reqstate => $reqstate, + format => $format, + on_early_error => sub { + my ($err) = @_; + set_error_result($res, $err); + $finish->($res); + }, + ); + + $reqstate->{on_disconnect} = sub { + $stream->_on_disconnect(); + }; + + run_async_starter( + 'async_stream_response', + $stream, + sub { $async_stream->{start}->($stream) }, + sub { $stream->abort($_[0]) }, + ); +} + sub handle_api2_request { my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_; @@ -1269,10 +1335,24 @@ sub handle_api2_request { my $clientip = $reqstate->{peer_host}; + my $default_formatter = PVE::APIServer::Formatter::get_formatter($format); + my $stream_supported = + defined($format) + && ($format eq 'json' || $format eq 'extjs') + && defined($default_formatter) + && $formatter == $default_formatter + ? 1 + : 0; + my $res = do { my $prev_async = $ASYNC_SUPPORTED; - my $guard = guard { $ASYNC_SUPPORTED = $prev_async }; + my $prev_stream = $ASYNC_STREAM_SUPPORTED; + my $guard = guard { + $ASYNC_SUPPORTED = $prev_async; + $ASYNC_STREAM_SUPPORTED = $prev_stream; + }; $ASYNC_SUPPORTED = 1; + $ASYNC_STREAM_SUPPORTED = $stream_supported; $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format); }; @@ -1281,6 +1361,17 @@ sub handle_api2_request { AnyEvent->now_update(); # in case somebody called sleep() + if (ref($res->{data}) eq 'PVE::APIServer::AnyEvent::AsyncStreamResponse') { + my $async_stream = delete $res->{data}; + my $finish = sub { + finish_api2_request($self, $reqstate, $_[0], $formatter, $params, $path, $auth); + }; + start_async_stream( + $self, $reqstate, $async_stream, $res, $finish, $format, $stream_supported, + ); + return; + } + if (ref($res->{data}) eq 'PVE::APIServer::AnyEvent::AsyncResponse') { my $async = delete $res->{data}; my $finish = sub { @@ -2643,6 +2734,13 @@ sub rest_handler { # info => $info, # status => HTTP_OK, # }; + + # to stream the response incrementally via the event loop use: + # { + # data => PVE::APIServer::AnyEvent::async_stream_response($starter), + # info => $info, + # status => HTTP_OK, + # }; } sub check_cert_fingerprint { diff --git a/src/PVE/APIServer/AsyncStream.pm b/src/PVE/APIServer/AsyncStream.pm new file mode 100644 index 0000000..9079fc2 --- /dev/null +++ b/src/PVE/APIServer/AsyncStream.pm @@ -0,0 +1,411 @@ +package PVE::APIServer::AsyncStream; + +# Push-based incremental HTTP response stream for API2 handlers returned via +# PVE::APIServer::AnyEvent::async_stream_response(). Exists so endpoints with large payloads +# (such as cluster-wide metric exports) can emit chunks incrementally with on-the-fly +# gzip/deflate compression instead of buffering and compressing the full body in one worker stall. +# +# Lifecycle: +# start() - writes HTTP/1.1 chunked (or HTTP/1.0) headers and, for json/extjs API2 streams, +# opens the outer {"data": envelope. +# write() - compresses and pushes a chunk of the inner JSON value. Returns 0 either when +# the stream is already closed (check is_closed(); the chunk was dropped) or when +# queued write-buffer bytes reach buf_size (the chunk was accepted and queued; do +# not resend it - pause further writes and register $stream->on_drain(sub { ... }) +# to resume). +# flush() - sync-flushes the active compressor (useful to minimize TTFB on the first slice). +# finish() - closes the outer envelope (emitting null if nothing was written), finalizes +# compression/chunking, logs the request, and keeps HTTP/1.1 connections reusable. +# abort() - invokes the starter's optional cancel callback (if any); before start(), delegates +# to normal formatted API2 error handling; after start(), omits the closing envelope +# and terminating 0-chunk and resets the socket (TCP RST) so clients cannot mistake +# truncated output for a complete response. + +use v5.36; + +use AnyEvent; +use Compress::Raw::Zlib (); +use HTTP::Date; +use HTTP::Headers; +use HTTP::Status qw(:constants); +use Net::SSLeay; + +my $DEFAULT_BUF_SIZE = 4 * 1024 * 1024; +my $DEFAULT_GZIP_LEVEL = 2; + +sub new($class, %args) { + + my ($prefix, $suffix); + if (defined($args{format})) { + if ($args{format} eq 'json') { + ($prefix, $suffix) = ('{"data":', '}'); + } elsif ($args{format} eq 'extjs') { + ($prefix, $suffix) = ('{"data":', ',"success":1}'); + } else { + die "unsupported async stream format\n"; + } + } + + return bless { + server => $args{server}, + reqstate => $args{reqstate}, + on_early_error => $args{on_early_error}, + buf_size => $args{buf_size} // $DEFAULT_BUF_SIZE, + prefix => $prefix, + suffix => $suffix, + envelope_started => 0, + wrote_body => 0, + started => 0, + finished => 0, + aborted => 0, + disconnected => 0, + chunked => 0, + bytes_written => 0, + cancel => undef, + deflate => undef, + }, $class; +} + +sub _clear_refs($self) { + delete @$self{qw(server reqstate on_early_error cancel deflate)}; +} + +sub is_closed($self) { + return $self->{finished} || !$self->{reqstate} || !$self->{reqstate}->{hdl} ? 1 : 0; +} + +sub is_backpressured($self) { + return 0 if $self->is_closed(); + my $hdl = $self->{reqstate}->{hdl}; + my $queued = length($hdl->{wbuf} // '') + length($hdl->{_tls_wbuf} // ''); + return $queued >= $self->{buf_size} ? 1 : 0; +} + +my sub push_frame($hdl, $chunked, $out) { + # Clear OpenSSL errors before writing so outbound TLS work cannot disrupt the client socket. + Net::SSLeay::ERR_clear_error(); + if ($chunked) { + $hdl->push_write(sprintf("%x\015\012", length($out)) . $out . "\015\012"); + } else { + $hdl->push_write($out); + } +} + +my sub write_payload($self, $bytes, $flush_mode = undef) { + my $has_bytes = defined($bytes) && length($bytes); + return 1 if !$has_bytes && !defined($flush_mode); + + my $out; + if (my $deflate = $self->{deflate}) { + $out = ''; + if ($has_bytes) { + my $st = $deflate->deflate($bytes, $out); + if ($st != Compress::Raw::Zlib::Z_OK()) { + $self->abort("stream compression failed ($st)"); + return 0; + } + } + if (defined($flush_mode)) { + my $st = $deflate->flush($out, $flush_mode); + if ($st != Compress::Raw::Zlib::Z_OK()) { + $self->abort("stream flush failed ($st)"); + return 0; + } + } + } else { + $out = $has_bytes ? $bytes : ''; + } + + if (length($out)) { + my $hdl = $self->{reqstate} ? $self->{reqstate}->{hdl} : undef; + return 0 if !$hdl; + $self->{bytes_written} += length($out); + push_frame($hdl, $self->{chunked}, $out); + return 0 if $self->is_closed(); + } + + return 1; +} + +sub start($self, %opts) { + return 0 if $self->is_closed(); + return 1 if $self->{started}; + + my ($server, $reqstate) = $self->@{ 'server', 'reqstate' }; + my $hdl = $reqstate->{hdl}; + + my $code = $opts{status} // HTTP_OK; + if (ref($code) || $code !~ /^[1-5][0-9]{2}\z/) { + $self->abort("invalid HTTP status code\n"); + return 0; + } + my $msg = $opts{message} || HTTP::Status::status_message($code) // ''; + ($msg) = $msg =~ m/^(.*)$/m; + if ($msg =~ /[\r\n]/) { + $code = HTTP_INTERNAL_SERVER_ERROR; + $msg = HTTP::Status::status_message($code); + } + + # These status codes forbid a response body and cannot be streamed. + if ($code =~ /^(1[0-9][0-9]|20[45]|304)$/) { + $self->abort("HTTP status $code does not allow streaming a response body\n"); + return 0; + } + + my $content_type = $opts{content_type} // 'application/json;charset=UTF-8'; + my $nocomp = $opts{nocomp} ? 1 : 0; + $nocomp = 1 if !$server->{compression}; + $nocomp = 1 if !$reqstate->{accept_gzip} && !$reqstate->{accept_deflate}; + + my $level = $opts{level} // $DEFAULT_GZIP_LEVEL; + my $encoding; + if (!$nocomp) { + if ($reqstate->{accept_gzip}) { + my ($deflate, $st) = Compress::Raw::Zlib::Deflate->new( + -Level => $level, + -WindowBits => Compress::Raw::Zlib::WANT_GZIP(), + -AppendOutput => 1, + ); + if ($st != Compress::Raw::Zlib::Z_OK()) { + $self->abort("failed to initialize gzip compressor: $st\n"); + return 0; + } + $self->{deflate} = $deflate; + $encoding = 'gzip'; + } elsif ($reqstate->{accept_deflate}) { + my ($deflate, $st) = Compress::Raw::Zlib::Deflate->new( + -Level => $level, + -AppendOutput => 1, + ); + if ($st != Compress::Raw::Zlib::Z_OK()) { + $self->abort("failed to initialize deflate compressor: $st\n"); + return 0; + } + $self->{deflate} = $deflate; + $encoding = 'deflate'; + } + } + + my $proto_ver = $reqstate->{proto} ? $reqstate->{proto}->{ver} : 1000; + my $proto_str = $reqstate->{proto} ? $reqstate->{proto}->{str} : 'HTTP/1.0'; + my $chunked = $proto_ver >= 1001 ? 1 : 0; + $self->{chunked} = $chunked; + + $reqstate->{keep_alive} = 0 if !$chunked || $code >= 400 || $server->{end_loop}; + $reqstate->{log}->{code} = $code; + $reqstate->{streaming} = 1; + + my $date = HTTP::Date::time2str(time()); + my $hdr = HTTP::Headers->new( + 'Content-Type' => $content_type, + 'Date' => $date, + 'Expires' => $date, + 'Cache-Control' => 'max-age=0', + 'Pragma' => 'no-cache', + 'Server' => 'pve-api-daemon/3.0', + ); + $hdr->header('Content-Encoding' => $encoding) if defined($encoding); + $hdr->header('Transfer-Encoding' => 'chunked') if $chunked; + + if (($reqstate->{keep_alive} // 0) > 0) { + $hdr->push_header('Connection' => 'Keep-Alive'); + } else { + $hdr->header('Connection' => 'close'); + } + + my $head = "$proto_str $code $msg\015\012" . $hdr->as_string("\015\012") . "\015\012"; + $self->{started} = 1; + + Net::SSLeay::ERR_clear_error(); + $hdl->push_write($head); + return 0 if $self->is_closed(); + + if ($code >= 200 && $code < 300 && defined($self->{prefix})) { + $self->{envelope_started} = 1; + return 0 if !write_payload($self, $self->{prefix}); + } + + return $self->is_closed() ? 0 : 1; +} + +sub write($self, $bytes = undef) { + return 0 if $self->is_closed(); + return 0 if !$self->{started} && !$self->start(); + return 0 if !write_payload($self, $bytes); + $self->{wrote_body} = 1 if defined($bytes) && length($bytes); + + return $self->is_backpressured() ? 0 : 1; +} + +sub flush($self) { + return 0 if $self->is_closed(); + return 1 if !$self->{started}; + + if ($self->{deflate}) { + return 0 if !write_payload($self, undef, Compress::Raw::Zlib::Z_SYNC_FLUSH()); + } + + return $self->is_backpressured() ? 0 : 1; +} + +sub on_drain($self, $cb = undef) { + return if $self->is_closed(); + my $hdl = $self->{reqstate}->{hdl}; + if (!defined($cb)) { + $hdl->wtimeout(0); + $hdl->on_drain(undef); + return; + } + die "stream on_drain requires a CODE ref\n" if ref($cb) ne 'CODE'; + + # Use a write-only timeout so a stalled reader disconnects even if it sends data. + AnyEvent->now_update(); + $hdl->wtimeout_reset(); + $hdl->wtimeout($self->{server}->{timeout}); + + # One-shot wrapper; AnyEvent::Handle invokes on_drain synchronously if already drained. + $hdl->on_drain(sub($wrhdl) { + $wrhdl->wtimeout(0); + $wrhdl->on_drain(undef); + return if $self->is_closed(); + eval { $cb->(); }; + my $err = $@; + # The callback may have used OpenSSL for other connections, see Note 1 in AnyEvent.pm. + Net::SSLeay::ERR_clear_error(); + $self->abort($err) if $err; + }); +} + +sub finish($self) { + return if $self->{finished}; + return if !$self->{started} && !$self->start(); + return if $self->{finished}; + + my ($server, $reqstate, $chunked) = $self->@{ 'server', 'reqstate', 'chunked' }; + + my $hdl = $reqstate->{hdl}; + if (!$hdl) { + $self->{finished} = 1; + delete $reqstate->{on_disconnect}; + $self->_clear_refs(); + return; + } + + $hdl->wtimeout(0); + $hdl->on_drain(undef); + + my $suffix; + if ($self->{envelope_started}) { + $suffix = $self->{wrote_body} ? $self->{suffix} : 'null' . $self->{suffix}; + } + my $flush_mode = $self->{deflate} ? Compress::Raw::Zlib::Z_FINISH() : undef; + if (!write_payload($self, $suffix, $flush_mode)) { + return if $self->{finished}; + $self->{finished} = 1; + delete $reqstate->{on_disconnect}; + $self->_clear_refs(); + return; + } + + if ($reqstate->{hdl} && $chunked) { + Net::SSLeay::ERR_clear_error(); + $hdl->push_write("0\015\012\015\012"); + } + + my $defer_reuse = + $reqstate->{hdl} + && $chunked + && ($reqstate->{keep_alive} // 0) > 0 + && $self->is_backpressured(); + + $self->{finished} = 1; + delete $reqstate->{on_disconnect}; + + if ($reqstate->{hdl}) { + $reqstate->{log}->{content_length} = $self->{bytes_written}; + $server->log_request($reqstate, $reqstate->{request}); + + AnyEvent->now_update(); + + # Chunked bodies are delimited by the 0-chunk and may reuse the connection; HTTP/1.0 + # streams keep streaming set until finish_response()'s on_drain writes everything out. + delete $reqstate->{streaming} if $chunked; + + $self->_clear_refs(); + + if ($defer_reuse) { + # Wait for the write queue to drain before reusing a keep-alive connection so a slow + # reader cannot accumulate unbounded pipelined responses across one-slice exports. + $hdl->wtimeout_reset(); + $hdl->wtimeout($server->{timeout}); + $hdl->on_drain(sub($wrhdl) { + $wrhdl->wtimeout(0); + $wrhdl->on_drain(undef); + return if !$reqstate->{hdl}; + AnyEvent->now_update(); + $wrhdl->timeout_reset(); + $wrhdl->timeout($server->{timeout}); + $server->finish_response($reqstate); + }); + } elsif ($server->{end_loop} || ($reqstate->{keep_alive} // 0) <= 0) { + # Keep a write-only deadline active while finish_response() drains queued output on a + # non-reusable connection so inbound client traffic cannot reset the timeout. + $hdl->timeout(0); + $hdl->wtimeout_reset(); + $hdl->wtimeout($server->{timeout}); + $server->finish_response($reqstate); + } else { + $hdl->timeout_reset(); + $hdl->timeout($server->{timeout}); + $server->finish_response($reqstate); + } + } else { + $self->_clear_refs(); + } +} + +sub abort($self, $err = undef) { + return if $self->{finished}; + $self->{finished} = 1; + $self->{aborted} = 1; + + my ($server, $reqstate, $on_early_error, $started, $cancel) = + $self->@{ 'server', 'reqstate', 'on_early_error', 'started', 'cancel' }; + + $self->_clear_refs(); + delete $reqstate->{on_disconnect} if $reqstate; + + if (ref($cancel) eq 'CODE') { + eval { $cancel->(); }; + warn $@ if $@; + Net::SSLeay::ERR_clear_error(); + } + + return if !$reqstate || !$reqstate->{hdl}; + + Net::SSLeay::ERR_clear_error(); + AnyEvent->now_update(); + + if (!$started) { + $on_early_error->($err) if $on_early_error; + return; + } + + # Headers are already sent; keep streaming set so client_do_disconnect() sends a TCP RST. + $reqstate->{streaming} = 1; + my $reason = defined($err) ? "$err" : 'stream aborted'; + $reason =~ s/\s+$//; + $server->log_aborted_request($reqstate, $reason); + $server->client_do_disconnect($reqstate); +} + +sub _on_disconnect($self) { + return if $self->{finished}; + $self->{finished} = 1; + $self->{disconnected} = 1; + my $cb = $self->{cancel}; + $self->_clear_refs(); + $cb->() if ref($cb) eq 'CODE'; +} + +1; -- 2.47.3