all lists on lists.proxmox.com
 help / color / mirror / Atom feed
From: Thomas Lamprecht <t.lamprecht@proxmox.com>
To: pve-devel@lists.proxmox.com
Subject: [PATCH http-server 01/09] response: support deferred async API2 responses
Date: Mon, 30 Nov 2026 01:58:05 +0100	[thread overview]
Message-ID: <20261130010113.2166775-2-t.lamprecht@proxmox.com> (raw)
In-Reply-To: <20261130010113.2166775-1-t.lamprecht@proxmox.com>

API2 handlers currently return synchronously from rest_handler(). An
endpoint that performs remote I/O therefore blocks the event loop of
one of the three pveproxy workers 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 <t.lamprecht@proxmox.com>
---
 src/PVE/APIServer/AnyEvent.pm | 254 +++++++++++++++++++++++++++++-----
 1 file changed, 221 insertions(+), 33 deletions(-)

diff --git a/src/PVE/APIServer/AnyEvent.pm b/src/PVE/APIServer/AnyEvent.pm
index b4d3f21..7bbd586 100644
--- a/src/PVE/APIServer/AnyEvent.pm
+++ b/src/PVE/APIServer/AnyEvent.pm
@@ -54,6 +54,19 @@ 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.
+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 +160,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 +1045,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 +1256,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 +1323,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 +2623,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





  reply	other threads:[~2026-11-30  1:01 UTC|newest]

Thread overview: 12+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-30  0:58 [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Thomas Lamprecht
2026-11-30  0:58 ` Thomas Lamprecht [this message]
2026-11-30  0:58 ` [PATCH http-server 02/09] proxy: strip chunked framing headers from decoded responses Thomas Lamprecht
2026-11-30  0:58 ` [PATCH http-server 03/09] response: support incremental streaming API2 responses Thomas Lamprecht
2026-11-30  0:58 ` [PATCH apiclient 04/09] add non-blocking AnyEvent API client Thomas Lamprecht
2026-11-30  0:58 ` [PATCH apiclient 05/09] add bounded AnyEvent request pool with backpressure and timeout Thomas Lamprecht
2026-11-30  0:58 ` [PATCH manager 06/09] api: metrics export: fetch remote nodes asynchronously Thomas Lamprecht
2026-11-30  0:58 ` [PATCH manager 07/09] api: metrics export: stream sorted metrics via incremental k-way merge Thomas Lamprecht
2026-11-30  0:58 ` [PATCH manager 08/09] api: metrics export: add unsorted pass-through streaming option Thomas Lamprecht
2026-11-30  0:58 ` [PATCH manager 09/09] test: add pull metric export test suite Thomas Lamprecht
2026-12-01 10:13 ` [PATCH http-server,apiclient,manager 00/09] async and streaming pull metric export Jonas Theisen
2026-12-01 10:22 ` superseded: " Thomas Lamprecht

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261130010113.2166775-2-t.lamprecht@proxmox.com \
    --to=t.lamprecht@proxmox.com \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal