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 32FED1FF09F for ; Tue, 01 Dec 2026 11:20:56 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id CB2362172F; Tue, 01 Dec 2026 11:20:31 +0100 (CET) From: Thomas Lamprecht To: pve-devel@lists.proxmox.com Subject: [PATCH http-server v2 1/9] response: support deferred async API2 responses Date: Tue, 1 Dec 2026 11:18:56 +0100 Message-ID: <20261201101913.1885484-2-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: 1796120358703 X-SPAM-LEVEL: Spam detection results: 0 AWL -0.002 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) POISEN_SPAM_PILL 0.1 Meta: its spam POISEN_SPAM_PILL_1 0.1 random spam to be learned in bayes POISEN_SPAM_PILL_3 0.1 random spam to be learned in bayes 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: 7X245T5HTOFXRYUXSYYQJQKCUWNLU5I7 X-Message-ID-Hash: 7X245T5HTOFXRYUXSYYQJQKCUWNLU5I7 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: API2 handlers currently return synchronously from rest_handler(). An endpoint that performs remote I/O therefore blocks the event loop of the pveproxy worker handling the request until every outbound request has finished. One example is /cluster/metrics/export, which Proxmox Datacenter Manager (PDM) and external monitoring scrape periodically and which queries every other online cluster node in turn. Allow rest_handler() to return a deferred response via async_response() in $res->{data} when async_supported() is true, unblocking workers without forking per request and working uniformly across API server subclasses. While pending, the server disables the inactivity timeout, keeps EOF detection active on plain and TLS sockets, holds pipelined keep-alive requests until completion, and runs the starter's cancel callback on client disconnect. OpenSSL's error queue and AnyEvent's clock are refreshed around starter and completion callbacks so outbound TLS work cannot abort the client connection or skew timeouts. Trade-offs: the server enforces no global async deadline, so handlers must bound their own wait (for example a 60 s fan-out timeout), and a client half-close cancels the in-flight handler immediately rather than running to completion as a synchronous handler would. In a single-worker TLS benchmark harness for a 16-node pull-metric fan-out, moving to async cut total export time from 486 ms to 84 ms with uniform 25 ms peer latency, and dropped concurrent /ping tail latency on the same worker from 1,137 ms to 2.1 ms when one peer took 600 ms. Signed-off-by: Thomas Lamprecht --- Changes in v2: - Document deadline ownership and disconnect-cancellation contract on async_response(). src/PVE/APIServer/AnyEvent.pm | 256 +++++++++++++++++++++++++++++----- 1 file changed, 223 insertions(+), 33 deletions(-) diff --git a/src/PVE/APIServer/AnyEvent.pm b/src/PVE/APIServer/AnyEvent.pm index b4d3f21..fa4076d 100644 --- a/src/PVE/APIServer/AnyEvent.pm +++ b/src/PVE/APIServer/AnyEvent.pm @@ -54,6 +54,21 @@ my $limit_max_header_size = 8 * 1024; my $limit_max_post = 512 * 1024; my $limit_max_request_line = 64 * 1024; +my $ASYNC_SUPPORTED = 0; + +sub async_supported { + return $ASYNC_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. +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'; +} + my $known_methods = { GET => 1, POST => 1, @@ -147,6 +162,13 @@ sub client_do_disconnect { return if $reqstate->{disconnected}; $reqstate->{disconnected} = 1; + if (my $on_disconnect = delete $reqstate->{on_disconnect}) { + eval { $on_disconnect->(); }; + warn $@ if $@; + # HACK: see Note 1 + Net::SSLeay::ERR_clear_error(); + } + cleanup_reqstate($reqstate, 1); my $shutdown_hdl = sub { @@ -1025,6 +1047,184 @@ sub extract_params { return $params; } +my sub prepare_async_handle { + my ($reqstate) = @_; + + return 0 if !$reqstate->{hdl}; + + # Disable the inactivity timeout while waiting (also covers callers bypassing handle_request()). + # Keep an empty on_read callback so plain sockets still detect client EOF while holding any + # pipelined request until this response finishes. + $reqstate->{hdl}->timeout(0); + $reqstate->{hdl}->on_read(sub { }); + + return $reqstate->{hdl} ? 1 : 0; +} + +my sub set_error_result { + my ($res, $err) = @_; + + delete $res->{data}; + delete $res->{total}; + delete $res->{changes}; + if (ref($err) eq 'PVE::Exception') { + $res->{status} = $err->{code} || HTTP_INTERNAL_SERVER_ERROR; + $res->{errors} = $err->{errors} if $err->{errors}; + $res->{message} = $err->{msg}; + } else { + $res->{status} = HTTP_INTERNAL_SERVER_ERROR; + $res->{message} = defined($err) ? "$err" : 'internal server error'; + } +} + +my sub run_async_starter { + my ($label, $state, $starter, $on_error) = @_; + + my $cb = eval { $starter->() }; + my $err = $@; + + # HACK: see Note 1 + Net::SSLeay::ERR_clear_error(); + AnyEvent->now_update(); + + if ($err) { + if ($state->{finished}) { + warn "$label starter died after completion: $err"; + } else { + $on_error->($err); + } + } elsif ($state->{disconnected} || $state->{aborted}) { + if (ref($cb) eq 'CODE') { + eval { $cb->(); }; + warn $@ if $@; + Net::SSLeay::ERR_clear_error(); + } + } elsif (!$state->{finished}) { + if (ref($cb) eq 'CODE') { + $state->{cancel} = $cb; + } elsif (defined($cb)) { + warn "$label starter returned non-CODE cancel value\n"; + } + } +} + +my sub finish_api2_request { + my ($self, $reqstate, $res, $formatter, $params, $path, $auth) = @_; + + eval { + my $delay = 0; + if (($res->{status} // 0) == HTTP_UNAUTHORIZED) { + # always delay unauthorized calls by 3 seconds + $delay = 3 - tv_interval($reqstate->{starttime}); + $delay = 0 if $delay < 0; + } + + my $download; + $download = $res->{data}->{download} + if defined($res->{data}) && ref($res->{data}) eq 'HASH'; + if (defined($download)) { + # TODO: remove ->{download} with PVE 9.0 + if ( + $res->{info} + && ($res->{info}->{download_allowed} || $res->{info}->{download}) + ) { + send_file_start($self, $reqstate, $download); + return; + } else { + warn "Download attempted for non-marked API endpoint '$path'\n"; + } + } + + my ($raw, $ct, $nocomp) = $formatter->( + $res, $res->{data}, $params, $path, $auth, $self->{formatter_config}, + ); + + my $resp; + if (ref($raw) && (ref($raw) eq 'HTTP::Response')) { + $resp = $raw; + } else { + $resp = HTTP::Response->new($res->{status}, $res->{message}); + $resp->header("Content-Type" => $ct); + $resp->content($raw); + } + $self->response($reqstate, $resp, undef, $nocomp, $delay); + }; + if (my $err = $@) { + $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, $err) + if $reqstate->{hdl}; + } +} + +my sub start_async_response { + my ($self, $reqstate, $async, $res, $finish) = @_; + + if ( + ref($async) ne 'PVE::APIServer::AnyEvent::AsyncResponse' + || ref($async->{start}) ne 'CODE' + ) { + die "invalid async response\n"; + } + + return if !prepare_async_handle($reqstate); + + my $state = { + finished => 0, + disconnected => 0, + cancel => undef, + reqstate => $reqstate, + res => $res, + finish => $finish, + }; + + my $complete = sub { + my ($cb) = @_; + return if $state->{finished}; + $state->{finished} = 1; + + my ($rs, $r_res, $finish_cb) = delete $state->@{qw(reqstate res finish cancel)}; + + delete $rs->{on_disconnect}; + return if !$rs->{hdl}; + + # HACK: see Note 1 + Net::SSLeay::ERR_clear_error(); + AnyEvent->now_update(); + + $cb->($r_res, $finish_cb); + }; + + my $resolve = sub { + my ($data) = @_; + $complete->(sub { + my ($r_res, $finish_cb) = @_; + $r_res->{status} //= HTTP_OK; + $r_res->{data} = $data; + $finish_cb->($r_res); + }); + }; + + my $reject = sub { + my ($err) = @_; + $complete->(sub { + my ($r_res, $finish_cb) = @_; + set_error_result($r_res, $err); + $finish_cb->($r_res); + }); + }; + + $reqstate->{on_disconnect} = sub { + return if $state->{finished}; + $state->{finished} = 1; + $state->{disconnected} = 1; + my ($cb) = delete $state->@{qw(cancel reqstate res finish)}; + $cb->() if ref($cb) eq 'CODE'; + }; + + run_async_starter( + 'async_response', $state, sub { $async->{start}->($resolve, $reject) }, $reject, + ); +} + sub handle_api2_request { my ($self, $reqstate, $auth, $method, $path, $upload_state) = @_; @@ -1058,13 +1258,27 @@ sub handle_api2_request { my $clientip = $reqstate->{peer_host}; - my $res = $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format); + my $res = do { + my $prev_async = $ASYNC_SUPPORTED; + my $guard = guard { $ASYNC_SUPPORTED = $prev_async }; + $ASYNC_SUPPORTED = 1; + $self->rest_handler($clientip, $method, $rel_uri, $auth, $params, $format); + }; # HACK: see Note 1 Net::SSLeay::ERR_clear_error(); AnyEvent->now_update(); # in case somebody called sleep() + if (ref($res->{data}) eq 'PVE::APIServer::AnyEvent::AsyncResponse') { + my $async = delete $res->{data}; + my $finish = sub { + finish_api2_request($self, $reqstate, $_[0], $formatter, $params, $path, $auth); + }; + start_async_response($self, $reqstate, $async, $res, $finish); + return; + } + my $upgrade = $r->header('upgrade'); $upgrade = lc($upgrade) if $upgrade; @@ -1111,38 +1325,7 @@ sub handle_api2_request { } } - my $delay = 0; - if ($res->{status} == HTTP_UNAUTHORIZED) { - # always delay unauthorized calls by 3 seconds - $delay = 3 - tv_interval($reqstate->{starttime}); - $delay = 0 if $delay < 0; - } - - my $download; - $download = $res->{data}->{download} - if defined($res->{data}) && ref($res->{data}) eq 'HASH'; - if (defined($download)) { - # TODO: remove ->{download} with PVE 9.0 - if ($res->{info}->{download_allowed} || $res->{info}->{download}) { - send_file_start($self, $reqstate, $download); - return; - } else { - warn "Download attempted for non-marked API endpoint '$path'\n"; - } - } - - my ($raw, $ct, $nocomp) = - $formatter->($res, $res->{data}, $params, $path, $auth, $self->{formatter_config}); - - my $resp; - if (ref($raw) && (ref($raw) eq 'HTTP::Response')) { - $resp = $raw; - } else { - $resp = HTTP::Response->new($res->{status}, $res->{message}); - $resp->header("Content-Type" => $ct); - $resp->content($raw); - } - $self->response($reqstate, $resp, undef, $nocomp, $delay); + finish_api2_request($self, $reqstate, $res, $formatter, $params, $path, $auth); }; if (my $err = $@) { $self->error($reqstate, HTTP_INTERNAL_SERVER_ERROR, $err); @@ -2442,6 +2625,13 @@ sub rest_handler { # to download aspecific file use: # { download => "/path/to/file" }; + + # to complete the request asynchronously via the event loop use: + # { + # data => PVE::APIServer::AnyEvent::async_response($starter), + # info => $info, + # status => HTTP_OK, + # }; } sub check_cert_fingerprint { -- 2.47.3