From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id DBFEA1FF0B7 for ; Mon, 30 Nov 2026 02:02:31 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 0FC26217CB; Mon, 30 Nov 2026 02:01:59 +0100 (CET) From: Thomas Lamprecht To: pve-devel@lists.proxmox.com Subject: [PATCH manager 07/09] api: metrics export: stream sorted metrics via incremental k-way merge Date: Mon, 30 Nov 2026 01:58:11 +0100 Message-ID: <20261130010113.2166775-8-t.lamprecht@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261130010113.2166775-1-t.lamprecht@proxmox.com> References: <20261130010113.2166775-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: 1796000481121 X-SPAM-LEVEL: Spam detection results: 0 AWL -0.053 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 PROLO_LEO1 0.1 Meta Catches all Leo drug variations so far 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: SDJII45T5OVM7EFOFHDGRG3IVOOMDXCU X-Message-ID-Hash: SDJII45T5OVM7EFOFHDGRG3IVOOMDXCU 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: Decoding every remote node's metrics into Perl hashes and sorting the combined array in memory allocates roughly 950 B per metric (~973 MiB VmHWM at 1,001,900 metrics) and stalls the worker event loop during decode, sort, and single-shot JSON encoding. Add PVE::PullMetricExport::Reader and build_kway_merge_stream(), and route PVE::PullMetricExport::export() through PVE::APIServer::AnyEvent::async_stream_response() whenever streaming is supported. Remote payloads stay gzip-compressed while fetching; once all peers arrive, local and remote streams are incrementally inflated in bounded 256 KiB compressed / 64 KiB output chunks (compacting whitespace between objects across chunk boundaries) and merged in global timestamp order via a min-heap in cooperative 256 KiB slices without allocating per-metric Perl hashes. Reader validates flat printable-ASCII RFC 8259 objects and captures the required integer timestamp in a single non-backtracking pass, falling back to a quote/brace-aware object scan and JSON::decode_json for escapes, UTF-8, nesting, duplicate timestamp keys, or syntax errors, and dies on corrupt, truncated, or trailing input. Pre-emission peer failures still log a warning and skip the peer, while a late Reader error after records have been emitted aborts the stream (TCP RST) so scrapers do not advance start-time past partial data. Slices are scheduled via AnyEvent->idle paired with a clock-synced 10 ms fallback timer; overall fan-out timeouts abort pre-start with HTTP 504, and unexpected callback or finish_stream() exceptions abort cleanly. Measured on a single pveproxy worker in a mock harness (25 ms per-peer latency, RSA-2048 TLS with SHA-256 pinning, gzip, 16-peer cap, 34 FDs; scenarios are nodes x guests with latest or 10 history generations, and /ping HOL is max head-of-line delay for a concurrent /ping request): Scenario | Mode | Total | TTFB | VmHWM | Max /ping HOL --------------------+---------------+--------+-------+----------+-------------- 25x100 latest | Sync LWP | 980ms | - | 105 MiB | 952 ms (25,475 metrics) | K-way stream | 188ms | 118ms | 83 MiB | 7.9 ms 25x100 hist10 | Sync LWP | 2146ms | - | 337 MiB | 2194 ms (254,750 metrics) | K-way stream | 827ms | 129ms | 98 MiB | 5.3 ms 100x100 latest | Sync LWP | 4445ms | - | 180 MiB | 4128 ms (101,900 metrics) | K-way stream | 644ms | 401ms | 90 MiB | 13.3 ms 100x1000 | Buffered | 5.1 s | - | 973 MiB | - (1,001,900 metrics) | K-way stream | 2969ms | 360ms | 103 MiB | 10.5 ms Signed-off-by: Thomas Lamprecht --- PVE/Makefile | 2 +- PVE/PullMetricExport.pm | 315 ++++++++++++++++++++++++++++++++- PVE/PullMetricExport/Makefile | 15 ++ PVE/PullMetricExport/Reader.pm | 276 +++++++++++++++++++++++++++++ 4 files changed, 603 insertions(+), 5 deletions(-) create mode 100644 PVE/PullMetricExport/Makefile create mode 100644 PVE/PullMetricExport/Reader.pm diff --git a/PVE/Makefile b/PVE/Makefile index 81a42f8d0..b4b1be303 100644 --- a/PVE/Makefile +++ b/PVE/Makefile @@ -1,6 +1,6 @@ include ../defines.mk -SUBDIRS=API2 Status CLI Service Ceph Jobs +SUBDIRS=API2 Status CLI Service Ceph Jobs PullMetricExport PERLSOURCE = \ API2.pm \ diff --git a/PVE/PullMetricExport.pm b/PVE/PullMetricExport.pm index f657a1c34..9464246c2 100644 --- a/PVE/PullMetricExport.pm +++ b/PVE/PullMetricExport.pm @@ -1,21 +1,30 @@ package PVE::PullMetricExport; -# Asynchronous cluster-wide pull-metric fan-out for GET /cluster/metrics/export. -# export() fetches remote nodes concurrently (capped via PVE::APIClient::AnyEvent::Pool), -# returning a deferred PVE::APIServer::AnyEvent::AsyncResponse inside pveproxy or blocking on an -# AnyEvent CondVar for CLI/pvesh callers. +# Asynchronous cluster-wide pull-metric fan-out and streaming export for GET +# /cluster/metrics/export. export() selects between two paths: +# - Incremental k-way merge stream (default when AsyncStream is supported): keeps remote peer +# responses gzip-compressed while fetching to avoid ~950 B/metric Perl hash allocations, then +# merges local and remote streams in global timestamp order in cooperative 256 KiB slices. +# - Buffered async_response (non-stream HTTP formats) or AnyEvent CondVar (CLI/pvesh callers). use v5.36; use AnyEvent; +use JSON qw(encode_json); use PVE::APIClient::AnyEvent; use PVE::APIClient::AnyEvent::Pool; use PVE::APIServer::AnyEvent; use PVE::Exception; +use PVE::PullMetricExport::Reader; use PVE::SafeSyslog (); our $MAX_WORKER_CONCURRENT_PEERS = 32; +our $STREAM_SLICE_BYTES = 262144; +our $SLICE_FALLBACK_INTERVAL = 0.01; + +my $STREAM_PREFIX = '{"data":['; +my $STREAM_SUFFIX = ']}'; my $WORKER_ACTIVE_PEERS = 0; my @WORKER_WAIT_QUEUE; @@ -297,9 +306,307 @@ sub build_buffered_fanout(%opts) { }; } +my sub open_peer_reader($name, $body, $is_gzip) { + my $reader; + my $first_obj = eval { + $reader = PVE::PullMetricExport::Reader->open( + body => $body, + gzip => $is_gzip, + ); + undef $body; + return $reader->next(); + }; + if (my $err = $@) { + log_peer_error($name, $err); + $reader->close() if $reader; + return undef; + } + + return undef if !defined($first_obj); + return { + name => $name, + reader => $reader, + obj => $first_obj, + ts => $reader->ts(), + }; +} + +my sub heap_push($heap, $entry) { + push @$heap, $entry; + my $idx = $#$heap; + while ($idx > 0) { + my $parent = int(($idx - 1) / 2); + last if $heap->[$parent]->{ts} <= $heap->[$idx]->{ts}; + @{$heap}[$parent, $idx] = @{$heap}[$idx, $parent]; + $idx = $parent; + } +} + +my sub heap_sift_down($heap, $idx) { + my $size = scalar(@$heap); + while (1) { + my $left = 2 * $idx + 1; + last if $left >= $size; + my $right = $left + 1; + my $smallest = + ($right < $size && $heap->[$right]->{ts} < $heap->[$left]->{ts}) ? $right : $left; + last if $heap->[$idx]->{ts} <= $heap->[$smallest]->{ts}; + @{$heap}[$idx, $smallest] = @{$heap}[$smallest, $idx]; + $idx = $smallest; + } +} + +# Return the second-smallest timestamp in the min-heap so kway_merge_step can drain consecutive +# metrics from the top node without sifting down until its timestamp exceeds the next node. +my sub heap_second_min_ts($heap) { + return undef if @$heap <= 1; + if (@$heap > 2 && $heap->[2]->{ts} < $heap->[1]->{ts}) { + return $heap->[2]->{ts}; + } + return $heap->[1]->{ts}; +} + +my sub clear_slice_watchers($state) { + delete @{$state}{qw(slice_idle slice_timer)}; +} + +my sub cleanup_stream($state) { + clear_slice_watchers($state); + if (my $fanout = delete $state->{fanout}) { + $fanout->{cancel}->(); + } + delete $state->{local_json}; + @{ $state->{peer_payloads} } = () if $state->{peer_payloads}; + @{ $state->{ready_peers} } = () if $state->{ready_peers}; + if (my $heap = $state->{heap}) { + $_->{reader}->close() for @$heap; + @$heap = (); + } + if (my $active = delete $state->{active_reader}) { + $active->{reader}->close(); + } + delete $state->{stream}; +} + +my sub abort_stream($state, $err = undef) { + return if $state->{done}; + $state->{done} = 1; + my $stream = $state->{stream}; + cleanup_stream($state); + $stream->abort($err) if $stream && !$stream->is_closed(); +} + +my sub schedule_slice($state, $cb) { + clear_slice_watchers($state); + + my $run = sub { + clear_slice_watchers($state); + eval { $cb->(); }; + abort_stream($state, $@) if $@; + }; + + # AnyEvent::Loop skips select() when timers are already due, while idle alone can starve under + # continuous competing I/O. Sync the loop clock before arming the fallback timer so its + # deadline stays strictly in the future and ready I/O runs first. + AnyEvent->now_update; + $state->{slice_idle} = AnyEvent->idle(cb => $run); + $state->{slice_timer} = AnyEvent->timer(after => $SLICE_FALLBACK_INTERVAL, cb => $run); +} + +my sub finish_stream($state, $out) { + my $stream = $state->{stream}; + $out .= $STREAM_SUFFIX; + $state->{done} = 1; + cleanup_stream($state); + return if !$stream || $stream->is_closed(); + eval { + $stream->write($out); + $stream->finish(); + }; + if (my $err = $@) { + $stream->abort($err) if !$stream->is_closed(); + } +} + +my sub after_stream_write($state, $ok, $step_cb, $notify_pool = undef) { + my $stream = $state->{stream}; + return if $state->{done} || !$stream || $stream->is_closed(); + + if (!$ok || $stream->is_backpressured()) { + clear_slice_watchers($state); + $state->{waiting_drain} = 1; + # Poke pool dispatch right as backpressure begins so the pool re-evaluates can_dispatch() + # and pauses its overall_timeout budget while waiting for on_drain. + $notify_pool->() if $notify_pool; + $stream->on_drain(sub { + $state->{waiting_drain} = 0; + return if $state->{done} || $stream->is_closed(); + eval { + $notify_pool->() if $notify_pool; + $step_cb->(); + }; + abort_stream($state, $@) if $@; + }); + } else { + $notify_pool->() if $notify_pool; + schedule_slice($state, $step_cb); + } +} + +my sub kway_merge_step($state) { + my $self = __SUB__; + clear_slice_watchers($state); + my $stream = $state->{stream}; + return if $state->{done} || !$stream || $stream->is_closed(); + + my $out = ''; + if (!$state->{started_stream}) { + $state->{started_stream} = 1; + $stream->start(); + $out = $STREAM_PREFIX; + } + + my $heap = $state->{heap}; + while (@$heap && length($out) < $STREAM_SLICE_BYTES) { + my $top = $heap->[0]; + my $reader = $top->{reader}; + my $next_min_ts = heap_second_min_ts($heap); + my $exhausted = 0; + + eval { + while (length($out) < $STREAM_SLICE_BYTES) { + $out .= ',' if !$state->{first_item}; + $state->{first_item} = 0; + $out .= $top->{obj}; + + my $obj = $reader->next(); + if (!defined($obj)) { + $exhausted = 1; + last; + } + $top->{obj} = $obj; + $top->{ts} = $reader->ts(); + + if (defined($next_min_ts) && $top->{ts} > $next_min_ts) { + heap_sift_down($heap, 0); + last; + } + } + }; + if (my $err = $@) { + log_peer_error($top->{name}, $err); + $reader->close(); + abort_stream($state, "could not stream metrics from $top->{name}: $err"); + return; + } + + if ($exhausted) { + my $last = pop @$heap; + if (@$heap) { + $heap->[0] = $last; + heap_sift_down($heap, 0); + } + } + } + + if (!@$heap) { + finish_stream($state, $out); + return; + } + + my $ok = $stream->write($out); + after_stream_write($state, $ok, sub { $self->($state) }); +} + +sub build_kway_merge_stream(%opts) { + my $local_json = $opts{local_json}; + + return sub { + my ($stream) = @_; + + my $state = { + stream => $stream, + done => 0, + local_json => $local_json, + peer_payloads => [], + heap => [], + started_stream => 0, + first_item => 1, + }; + undef $local_json; + + $state->{fanout} = start_metric_fanout( + %opts, + on_peer => sub { + my ($name, $body_ref, $is_gzip) = @_; + push @{ $state->{peer_payloads} }, + { + name => $name, + body => $$body_ref, + gzip => $is_gzip, + }; + }, + on_done => sub($timed_out, $timeout) { + return if $state->{done} || $stream->is_closed(); + delete $state->{fanout}; + + if ($timed_out) { + abort_stream( + $state, + PVE::Exception->new( + "cluster metric fan-out timed out after ${timeout}s\n", + code => 504, + ), + ); + return; + } + + eval { + if (defined(my $local = delete $state->{local_json})) { + if (my $entry = open_peer_reader('local', $local, 0)) { + heap_push($state->{heap}, $entry); + } + } + + my $payloads = $state->{peer_payloads}; + while (my $peer = shift @$payloads) { + my $entry = + open_peer_reader($peer->{name}, $peer->{body}, $peer->{gzip}); + undef $peer; + heap_push($state->{heap}, $entry) if $entry; + } + + kway_merge_step($state); + }; + abort_stream($state, $@) if $@; + }, + ); + + return sub { + return if $state->{done}; + $state->{done} = 1; + cleanup_stream($state); + }; + }; +} + sub export(%opts) { my $metrics = $opts{metrics} // []; + if (PVE::APIServer::AnyEvent::async_stream_supported()) { + my $local_json; + if (@$metrics) { + # Encode local metrics into the same wire envelope as remote peers so the streaming + # reader and k-way merge heap drain local and remote sources uniformly. + @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics; + $local_json = encode_json({ data => { data => $metrics } }); + @$metrics = (); + } + return PVE::APIServer::AnyEvent::async_stream_response( + build_kway_merge_stream(%opts, local_json => $local_json), + ); + } + my $finalize = sub { # In-place sort avoids allocating a second copy of large metric arrays. @$metrics = sort { $a->{timestamp} <=> $b->{timestamp} } @$metrics; diff --git a/PVE/PullMetricExport/Makefile b/PVE/PullMetricExport/Makefile new file mode 100644 index 000000000..5098a6e52 --- /dev/null +++ b/PVE/PullMetricExport/Makefile @@ -0,0 +1,15 @@ +include ../../defines.mk + +PERLSOURCE = \ + Reader.pm + +all: + +.PHONY: clean +clean: + rm -rf *~ + +.PHONY: install +install: $(PERLSOURCE) + install -d $(PERLLIBDIR)/PVE/PullMetricExport + install -m 0644 $(PERLSOURCE) $(PERLLIBDIR)/PVE/PullMetricExport diff --git a/PVE/PullMetricExport/Reader.pm b/PVE/PullMetricExport/Reader.pm new file mode 100644 index 000000000..cdeeffa71 --- /dev/null +++ b/PVE/PullMetricExport/Reader.pm @@ -0,0 +1,276 @@ +package PVE::PullMetricExport::Reader; + +# Incremental gzip+JSON metric array reader for remote peer responses and local_json. +# Scans {"data":{"data":[...]}} in bounded 256 KiB compressed input slices and 64 KiB inflate +# chunks, validating flat printable-ASCII RFC 8259 objects without allocating per-metric Perl +# hashes (falling back to quote/brace scanning + decode_json for escapes, UTF-8, or nesting). +# Contract: open(body => $str, gzip => $bool) validates the opening envelope; next() returns each +# raw JSON object string (enforcing integer timestamp and updating obj()/ts()) or undef on clean +# EOF; dies on corrupt, malformed, truncated, or trailing data (callers call close() on error). + +use v5.36; + +use Compress::Raw::Zlib qw(WANT_GZIP Z_OK Z_STREAM_END Z_BUF_ERROR); +use JSON qw(decode_json); + +our $GZIP_INPUT_CHUNK_BYTES = 262144; + +# Exact RFC 8259 flat JSON object grammar restricted to printable ASCII strings without escapes. +# Composed as strings before compiling once to avoid nested (?^:...) regex scopes in the hot loop. +my $JSON_WS = '[ \t\r\n]*'; +my $JSON_ASCII_STR = '"[\x20\x21\x23-\x5b\x5d-\x7e]*"'; +my $JSON_NUM = '-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?'; +my $JSON_PRIM = "(?:$JSON_ASCII_STR|$JSON_NUM|true|false|null)"; +my $JSON_FLAT_PAIR = "$JSON_ASCII_STR$JSON_WS:$JSON_WS$JSON_PRIM"; +my $JSON_NON_TS_PAIR = "(?!\"timestamp\"$JSON_WS:)$JSON_FLAT_PAIR"; +my $FLAT_JSON_OBJ_RE = + qr/\G(\{$JSON_WS(?:$JSON_NON_TS_PAIR$JSON_WS,$JSON_WS)*+"timestamp"$JSON_WS:$JSON_WS(-?(?:0|[1-9][0-9]*))(?:$JSON_WS,$JSON_WS$JSON_NON_TS_PAIR)*+$JSON_WS\})/; +my $ENVELOPE_OPEN_RE = + qr/\G$JSON_WS\{$JSON_WS"data"$JSON_WS:$JSON_WS\{$JSON_WS"data"$JSON_WS:$JSON_WS\[/; +my $ENVELOPE_CLOSE_RE = qr/\G$JSON_WS\}$JSON_WS\}$JSON_WS\z/; + +# Scan a complete JSON object starting at $start, tracking string quotes, escapes, and brace +# depth. Returns the index right after the matching '}', or undef if the buffer is incomplete. +my sub find_json_object_end($buf_ref, $start) { + my $depth = 0; + my $in_string = 0; + my $len = length($$buf_ref); + pos($$buf_ref) = $start; + + while ($$buf_ref =~ /(["{}\\])/gc) { + my $tok = $1; + if ($in_string) { + if ($tok eq '\\') { + return undef if pos($$buf_ref) >= $len; + pos($$buf_ref) += 1; + } elsif ($tok eq '"') { + $in_string = 0; + } + } elsif ($tok eq '"') { + $in_string = 1; + } elsif ($tok eq '{') { + $depth++; + } elsif ($tok eq '}') { + $depth--; + return pos($$buf_ref) if $depth == 0; + } + } + + return undef; +} + +my sub refill($self) { + return 0 if $self->{eof}; + + # Compact the already-parsed prefix before inflating the next 64 KiB chunk so buffer memory + # stays bounded across multi-megabyte peer payloads. + if ($self->{pos} > 0) { + substr($self->{buf}, 0, $self->{pos}, ''); + $self->{pos} = 0; + } + + while (1) { + if (!length($self->{in_chunk}) && defined($self->{input})) { + $self->{in_chunk} = substr($self->{input}, $self->{input_pos}, $GZIP_INPUT_CHUNK_BYTES); + $self->{input_pos} += length($self->{in_chunk}); + undef $self->{input} if $self->{input_pos} >= length($self->{input}); + } + + my $prev_in = length($self->{in_chunk}); + my $chunk = ''; + my $status = $self->{inflater}->inflate($self->{in_chunk}, $chunk); + if ($status == Z_STREAM_END) { + if (length($self->{in_chunk}) || defined($self->{input})) { + die "unexpected trailing data after gzip stream\n"; + } + $self->{eof} = 1; + undef $self->{input}; + undef $self->{in_chunk}; + undef $self->{inflater}; + $self->{buf} .= $chunk; + return length($chunk) > 0 ? 1 : 0; + } elsif ($status == Z_BUF_ERROR) { + if (length($chunk) > 0) { + $self->{buf} .= $chunk; + return 1; + } + next if defined($self->{input}); + die "truncated gzip stream\n"; + } elsif ($status != Z_OK) { + die "failed to gunzip stream (zlib status $status)\n"; + } + + if (length($chunk) > 0) { + $self->{buf} .= $chunk; + return 1; + } + next if defined($self->{input}) || length($self->{in_chunk}) < $prev_in; + die "truncated gzip stream\n"; + } +} + +sub open($class, %opts) { + my $is_gzip = $opts{gzip} ? 1 : 0; + + my $inflater; + if ($is_gzip) { + my $status; + ($inflater, $status) = Compress::Raw::Zlib::Inflate->new( + -WindowBits => WANT_GZIP, + -Bufsize => 65536, + -LimitOutput => 1, + ); + die "failed to initialize gzip inflater (status $status)\n" if $status != Z_OK; + } + + # Plain payloads (such as local_json) are scanned directly in buf without chunk copying. + my $self = bless { + ts => 0, + obj => undef, + buf => $is_gzip ? '' : ($opts{body} // ''), + pos => 0, + input => $is_gzip ? $opts{body} : undef, + input_pos => 0, + in_chunk => '', + inflater => $inflater, + eof => $is_gzip ? 0 : 1, + closed => 0, + need_comma => 0, + }, $class; + delete $opts{body}; + + eval { + my $matched = 0; + while (1) { + pos($self->{buf}) = 0; + if ($self->{buf} =~ m/$ENVELOPE_OPEN_RE/gc) { + $self->{pos} = pos($self->{buf}); + $matched = 1; + last; + } + last if length($self->{buf}) >= 4096; + last if !refill($self); + } + die "unexpected response format\n" if !$matched; + }; + if (my $err = $@) { + $self->close(); + die $err; + } + + return $self; +} + +sub next($self) { + return undef if $self->{closed}; + + while (1) { + # Compact PVE metric JSON uses ',{' between objects; skipping whitespace regexes on this + # common separator and matching flat ASCII objects avoids per-metric hash allocations, + # while escapes, UTF-8, nested values, or syntax errors fall back to decode_json. + my $pos = $self->{pos}; + if ($self->{need_comma} == 1 && substr($self->{buf}, $pos, 2) eq ',{') { + $pos++; + $self->{pos} = $pos; + $self->{need_comma} = 2; + } else { + pos($self->{buf}) = $pos; + $self->{buf} =~ /\G[ \t\r\n]*/gc; + $pos = pos($self->{buf}); + + if ($pos >= length($self->{buf})) { + $self->{pos} = $pos; + next if refill($self); + die "truncated metrics array\n"; + } + + my $ch = substr($self->{buf}, $pos, 1); + if ($ch eq ']') { + die "unexpected token in metrics array\n" if $self->{need_comma} == 2; + $self->{pos} = $pos + 1; + while (!$self->{eof}) { + die "unexpected trailing data\n" if length($self->{buf}) - $self->{pos} > 4096; + last if !refill($self); + } + die "unexpected trailing data\n" if length($self->{buf}) - $self->{pos} > 4096; + pos($self->{buf}) = $self->{pos}; + if ($self->{buf} !~ m/$ENVELOPE_CLOSE_RE/gc) { + die "unexpected trailing data\n"; + } + $self->close(); + return undef; + } + + if ($self->{need_comma} == 1) { + die "unexpected token in metrics array\n" if $ch ne ','; + $self->{need_comma} = 2; + pos($self->{buf}) = $pos + 1; + $self->{buf} =~ /\G[ \t\r\n]*/gc; + $pos = pos($self->{buf}); + if ($pos >= length($self->{buf})) { + $self->{pos} = $pos; + next if refill($self); + die "truncated metrics array\n"; + } + $ch = substr($self->{buf}, $pos, 1); + } + + die "unexpected token in metrics array\n" if $ch ne '{'; + $self->{pos} = $pos; + } + + # Fast path: flat printable-ASCII RFC 8259 object with a unique integer timestamp, + # validated and captured in a single non-backtracking pass without Perl hash allocation. + pos($self->{buf}) = $pos; + if ($self->{buf} =~ m/$FLAT_JSON_OBJ_RE/gc) { + my ($obj, $ts) = ($1, $2); + $self->{ts} = $ts + 0; + $self->{pos} = pos($self->{buf}); + $self->{need_comma} = 1; + $self->{obj} = $obj; + return $obj; + } + + # Fallback: full object scan + strict decode_json for escapes, UTF-8, nesting, or errors. + my $end = find_json_object_end(\$self->{buf}, $pos); + if (defined($end)) { + my $obj = substr($self->{buf}, $pos, $end - $pos); + my $decoded = decode_json($obj); + die "unexpected metric object\n" if ref($decoded) ne 'HASH'; + if ( + !defined($decoded->{timestamp}) + || ref($decoded->{timestamp}) + || $decoded->{timestamp} !~ /^-?[0-9]+$/ + ) { + die "missing integer timestamp\n"; + } + $self->{ts} = $decoded->{timestamp} + 0; + $self->{pos} = $end; + $self->{need_comma} = 1; + $self->{obj} = $obj; + return $obj; + } + + if (length($self->{buf}) - $self->{pos} > 4 * 1024 * 1024) { + die "metric object exceeds maximum size\n"; + } + next if refill($self); + die "truncated metric object\n"; + } +} + +sub obj($self) { + return $self->{obj}; +} + +sub ts($self) { + return $self->{ts}; +} + +sub close($self) { + return if !$self || $self->{closed}; + $self->{closed} = 1; + delete @{$self}{qw(input in_chunk inflater buf obj)}; +} + +1; -- 2.47.3