Skip to main content

servers/http/
prom_store.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15mod exemplar;
16
17use std::sync::Arc;
18
19use api::prom_store::remote::ReadRequest;
20use api::v1::RowInsertRequests;
21use async_trait::async_trait;
22use axum::Extension;
23use axum::body::Bytes;
24use axum::extract::{Query, State};
25use axum::http::{Extensions, HeaderMap, HeaderValue, StatusCode, header};
26use axum::response::IntoResponse;
27use axum_extra::TypedHeader;
28use common_catalog::consts::DEFAULT_SCHEMA_NAME;
29use common_error::ext::BoxedError;
30use common_memory_manager::OnExhaustedPolicy;
31use common_query::prelude::GREPTIME_PHYSICAL_TABLE;
32use common_telemetry::tracing;
33use mime_guess::mime;
34use pipeline::util::to_pipeline_version;
35use pipeline::{ContextReq, PipelineDefinition};
36use prometheus::HistogramTimer;
37use prost::Message;
38use serde::{Deserialize, Serialize};
39use session::context::{Channel, QueryContext, QueryContextRef};
40use snafu::IntoError;
41use snafu::prelude::*;
42use table::requests::{
43    METADATA_QUALITY_INFERRED, SEMANTIC_METRIC_METADATA_QUALITY, SEMANTIC_PER_TABLE_INDEX_KEY,
44    SEMANTIC_SIGNAL_TYPE, SEMANTIC_SOURCE, SEMANTIC_SOURCE_VERSION, SIGNAL_TYPE_METRIC,
45    SOURCE_PROMETHEUS,
46};
47
48use crate::batcher::logical_table::LogicalTablePendingRowsBatcher;
49use crate::error::{self, InternalSnafu, PipelineSnafu, Result};
50use crate::http::extractor::PipelineInfo;
51use crate::http::header::{
52    CONTENT_TYPE_PROTOBUF_STR, GREPTIME_DB_HEADER_METRICS, write_cost_header_map,
53};
54use crate::http::memory_limit::BodyMemoryAccounting;
55use crate::prom_remote_write::decode::PromSeriesProcessor;
56use crate::prom_remote_write::v2::decode_remote_write_v2;
57use crate::prom_remote_write::validation::PromValidationMode;
58use crate::prom_remote_write::{
59    self, REMOTE_WRITE_V1_VERSION, REMOTE_WRITE_V2_VERSION, decode_remote_write_request,
60};
61use crate::prom_store::{MAX_DECOMPRESSED_REQUEST_SIZE, snappy_decompress_limited};
62use crate::query_handler::{PipelineHandlerRef, PromStoreProtocolHandlerRef, PromStoreResponse};
63use crate::request_memory_limiter::ServerMemoryLimiter;
64
65pub const PHYSICAL_TABLE_PARAM: &str = "physical_table";
66pub const DEFAULT_ENCODING: &str = "snappy";
67pub const VM_ENCODING: &str = "zstd";
68pub const VM_PROTO_VERSION: &str = "1";
69const REMOTE_WRITE_V1_PROTO: &str = "prometheus.WriteRequest";
70const REMOTE_WRITE_V2_PROTO: &str = "io.prometheus.write.v2.Request";
71const CONTENT_TYPE_PROTO_PARAM: &str = "proto";
72const REMOTE_WRITE_V2_SAMPLES_WRITTEN_HEADER: &str = "x-prometheus-remote-write-samples-written";
73const REMOTE_WRITE_V2_HISTOGRAMS_WRITTEN_HEADER: &str =
74    "x-prometheus-remote-write-histograms-written";
75const REMOTE_WRITE_V2_EXEMPLARS_WRITTEN_HEADER: &str =
76    "x-prometheus-remote-write-exemplars-written";
77
78#[derive(Clone)]
79pub struct PromStoreState {
80    pub prom_store_handler: PromStoreProtocolHandlerRef,
81    pub pipeline_handler: Option<PipelineHandlerRef>,
82    pub prom_store_with_metric_engine: bool,
83    pub prom_validation_mode: PromValidationMode,
84    pub pending_rows_batcher: Option<Arc<LogicalTablePendingRowsBatcher>>,
85    /// Shared request-memory limiter used to charge decompressed remote
86    /// read/write bodies against the aggregate quota.
87    pub memory_limiter: ServerMemoryLimiter,
88}
89
90#[derive(Debug, Serialize, Deserialize)]
91pub struct RemoteWriteQuery {
92    pub db: Option<String>,
93    /// Specify which physical table to use for storing metrics.
94    /// This only works on remote write requests.
95    pub physical_table: Option<String>,
96    /// For VictoriaMetrics modified remote write protocol
97    pub get_vm_proto_version: Option<String>,
98}
99
100impl Default for RemoteWriteQuery {
101    fn default() -> RemoteWriteQuery {
102        Self {
103            db: Some(DEFAULT_SCHEMA_NAME.to_string()),
104            physical_table: Some(GREPTIME_PHYSICAL_TABLE.to_string()),
105            get_vm_proto_version: None,
106        }
107    }
108}
109
110#[axum_macros::debug_handler]
111#[tracing::instrument(
112    skip_all,
113    fields(protocol = "prometheus", request_type = "remote_write")
114)]
115pub async fn remote_write(
116    State(state): State<PromStoreState>,
117    Query(params): Query<RemoteWriteQuery>,
118    (Extension(query_ctx), extensions): (Extension<QueryContext>, Extensions),
119    content_type: Option<TypedHeader<headers::ContentType>>,
120    pipeline_info: PipelineInfo,
121    content_encoding: TypedHeader<headers::ContentEncoding>,
122    body: Bytes,
123) -> Result<axum::response::Response> {
124    let is_zstd = content_encoding.contains(VM_ENCODING);
125    // Read after Bytes has collected every frame, including chunked-body reservations.
126    let body_reserved_bytes = extensions
127        .get::<BodyMemoryAccounting>()
128        .map_or(0, BodyMemoryAccounting::reserved_bytes);
129
130    match remote_write_proto(content_type) {
131        RemoteWriteProto::V1 => {
132            remote_write_v1(
133                state,
134                params,
135                query_ctx,
136                pipeline_info,
137                is_zstd,
138                body,
139                body_reserved_bytes,
140            )
141            .await
142        }
143        RemoteWriteProto::V2 => {
144            if let Some(response) = unsupported_remote_write_v2_encoding_response(&content_encoding)
145            {
146                return Ok(response);
147            }
148            remote_write_v2(
149                state,
150                params,
151                query_ctx,
152                pipeline_info,
153                is_zstd,
154                body,
155                body_reserved_bytes,
156            )
157            .await
158        }
159        RemoteWriteProto::Unsupported(content_type) => Ok((
160            StatusCode::UNSUPPORTED_MEDIA_TYPE,
161            format!("unsupported prometheus remote write content type: {content_type}"),
162        )
163            .into_response()),
164    }
165}
166
167async fn remote_write_v1(
168    state: PromStoreState,
169    params: RemoteWriteQuery,
170    query_ctx: QueryContext,
171    pipeline_info: PipelineInfo,
172    is_zstd: bool,
173    body: Bytes,
174    body_reserved_bytes: u64,
175) -> Result<axum::response::Response> {
176    if let Some(response) = vm_proto_version_response(&params) {
177        return Ok(response);
178    }
179
180    let (db, query_ctx, _timer) =
181        prepare_remote_write_context(&params, query_ctx, REMOTE_WRITE_V1_VERSION);
182    let query_ctx = Arc::new(query_ctx);
183
184    match ingest_remote_write_v1(
185        &state,
186        &db,
187        pipeline_info,
188        is_zstd,
189        query_ctx,
190        body,
191        body_reserved_bytes,
192    )
193    .await
194    {
195        Ok(outcome) => {
196            Ok((StatusCode::NO_CONTENT, write_cost_header_map(outcome.cost)).into_response())
197        }
198        Err(error) => Err(error.error),
199    }
200}
201
202/// The axum-free core of a remote-write v1 ingestion, shared with
203/// `COPY FROM STDIN WITH (FORMAT promwrite)`: decode, convert and write
204/// exactly as the HTTP endpoint does.
205pub(crate) async fn ingest_remote_write_v1(
206    state: &PromStoreState,
207    db: &str,
208    pipeline_info: PipelineInfo,
209    is_zstd: bool,
210    query_ctx: QueryContextRef,
211    body: Bytes,
212    body_reserved_bytes: u64,
213) -> std::result::Result<PromWriteResult, PromWriteError> {
214    let result = ingest_remote_write_v1_inner(
215        state,
216        pipeline_info,
217        is_zstd,
218        query_ctx,
219        body,
220        body_reserved_bytes,
221    )
222    .await;
223    // Account for partial writes as well as successful requests, regardless of transport.
224    let (samples, exemplars) = match &result {
225        Ok(outcome) => (outcome.written[0], outcome.written[2]),
226        Err(error) => (error.rows_written, error.exemplars_written),
227    };
228    record_remote_write_samples(db, REMOTE_WRITE_V1_VERSION, samples);
229    record_remote_write_exemplars(db, REMOTE_WRITE_V1_VERSION, exemplars);
230    result
231}
232
233async fn ingest_remote_write_v1_inner(
234    state: &PromStoreState,
235    pipeline_info: PipelineInfo,
236    is_zstd: bool,
237    query_ctx: QueryContextRef,
238    body: Bytes,
239    body_reserved_bytes: u64,
240) -> std::result::Result<PromWriteResult, PromWriteError> {
241    let PromStoreState {
242        prom_store_handler,
243        pipeline_handler,
244        prom_store_with_metric_engine,
245        prom_validation_mode,
246        pending_rows_batcher,
247        memory_limiter,
248    } = state;
249
250    let no_progress = |error: error::Error| PromWriteError {
251        error,
252        rows_written: 0,
253        exemplars_written: 0,
254    };
255    let mut processor = PromSeriesProcessor::default_processor();
256
257    if let Some(pipeline_name) = pipeline_info.pipeline_name {
258        let pipeline_def = PipelineDefinition::from_name(
259            &pipeline_name,
260            to_pipeline_version(pipeline_info.pipeline_version.as_deref())
261                .context(PipelineSnafu)
262                .map_err(no_progress)?,
263            None,
264        )
265        .context(PipelineSnafu)
266        .map_err(no_progress)?;
267        let Some(pipeline_handler) = pipeline_handler else {
268            return Err(no_progress(error::Error::Internal {
269                err_msg: "pipeline handler is not set".to_string(),
270            }));
271        };
272
273        processor.set_pipeline(pipeline_handler.clone(), query_ctx.clone(), pipeline_def);
274    }
275
276    // Keep the decode guards alive until the batches are built: the
277    // `TablesBuilder` retains the decompressed buffer as its raw data.
278    let (mut decoded, decode_guards) = decode_remote_write_request(
279        is_zstd,
280        body,
281        *prom_validation_mode,
282        &mut processor,
283        memory_limiter,
284        body_reserved_bytes,
285    )
286    .await
287    .map_err(no_progress)?;
288
289    // Parsing borrows the decode buffer, but row building copies out of it: tag
290    // values through `decode_string`, column names through `to_owned`, and the
291    // borrowing `col_indexes` dies inside `as_insert_requests`. Nothing below
292    // references the buffer, so it need not span the write — the same goes for
293    // the decode guards charged against the aggregate memory quota.
294    let exemplars = std::mem::take(&mut decoded.exemplars);
295    let req = if processor.use_pipeline {
296        drop(decoded);
297        processor.exec_pipeline().await.map_err(no_progress)?
298    } else {
299        let req = decoded.as_insert_requests();
300        drop(decoded);
301        req
302    };
303    drop(decode_guards);
304    let query_ctx = if exemplars.is_empty() {
305        query_ctx
306    } else {
307        // Reserve for row expansion before copying shared metric names and series labels.
308        let bytes = crate::exemplar::estimated_row_bytes(exemplars.values().map(Vec::as_slice))
309            .and_then(|bytes| u64::try_from(bytes).ok())
310            .ok_or_else(|| {
311                no_progress(error::MemoryLimitExceededSnafu.into_error(
312                    common_memory_manager::Error::MemoryLimitExceeded {
313                        requested_bytes: u64::MAX,
314                        limit_bytes: memory_limiter.limit_bytes(),
315                    },
316                ))
317            })?;
318        memory_limiter
319            .check_request_fits(bytes, body_reserved_bytes)
320            .map_err(no_progress)?;
321        // Holding body permits while waiting for expansion can stall concurrent requests.
322        let reservation = Arc::new(if body_reserved_bytes > 0 {
323            memory_limiter
324                .try_acquire(bytes)
325                .ok_or_else(|| {
326                    let source = common_memory_manager::Error::MemoryLimitExceeded {
327                        requested_bytes: bytes,
328                        limit_bytes: memory_limiter.limit_bytes(),
329                    };
330                    // Wait-policy contention must remain retryable by Remote Write senders.
331                    match memory_limiter.policy() {
332                        OnExhaustedPolicy::Wait { .. } => {
333                            error::OtherSnafu.into_error(BoxedError::new(source))
334                        }
335                        OnExhaustedPolicy::Fail => {
336                            error::MemoryLimitExceededSnafu.into_error(source)
337                        }
338                    }
339                })
340                .map_err(no_progress)?
341        } else {
342            memory_limiter
343                .acquire(bytes)
344                .await
345                .map_err(prom_remote_write::map_memory_acquire_timeout)
346                .map_err(no_progress)?
347        });
348        let mut ctx = query_ctx.fork();
349        ctx.set_write_progress(Arc::new(
350            session::write_progress::WriteProgress::with_reservation(
351                reservation.granted_bytes(),
352                reservation,
353            ),
354        ));
355        Arc::new(ctx)
356    };
357    let batches = into_prom_write_batches(req, query_ctx.clone());
358    if !exemplars.is_empty() {
359        let outcome = exemplar::write(
360            prom_store_handler.clone(),
361            pending_rows_batcher.clone(),
362            *prom_store_with_metric_engine,
363            batches,
364            Vec::new(),
365            exemplars,
366            query_ctx,
367        )
368        .await;
369        if let Some(error) = outcome.error {
370            return Err(PromWriteError {
371                error,
372                rows_written: outcome.written[0],
373                exemplars_written: outcome.written[2],
374            });
375        }
376        return Ok(PromWriteResult {
377            written: outcome.written,
378            cost: outcome.cost,
379            accepted: outcome.accepted,
380        });
381    }
382
383    write_prometheus_rows_with_progress(
384        prom_store_handler.clone(),
385        pending_rows_batcher.clone(),
386        *prom_store_with_metric_engine,
387        batches,
388    )
389    .await
390    .map(|outcome| PromWriteResult {
391        written: [outcome.rows_written, 0, 0],
392        cost: outcome.write_cost,
393        accepted: false,
394    })
395}
396
397async fn remote_write_v2(
398    state: PromStoreState,
399    params: RemoteWriteQuery,
400    query_ctx: QueryContext,
401    pipeline_info: PipelineInfo,
402    is_zstd: bool,
403    body: Bytes,
404    body_reserved_bytes: u64,
405) -> Result<axum::response::Response> {
406    if let Some(response) = vm_proto_version_response(&params) {
407        return Ok(response);
408    }
409
410    // Pipeline processing is not supported for remote write v2 yet. Only the
411    // pipeline presence matters, for the exemplar restriction below.
412    let has_pipeline = pipeline_info.pipeline_name.is_some();
413
414    let (db, query_ctx, _timer) =
415        prepare_remote_write_context(&params, query_ctx, REMOTE_WRITE_V2_VERSION);
416
417    match ingest_remote_write_v2(
418        &state,
419        &db,
420        has_pipeline,
421        is_zstd,
422        query_ctx,
423        body,
424        body_reserved_bytes,
425    )
426    .await
427    {
428        Ok(PromWriteResult {
429            written,
430            cost,
431            accepted,
432        }) => {
433            let mut headers = write_cost_header_map(cost);
434            append_remote_write_v2_written_headers(
435                &mut headers,
436                written[0],
437                written[1],
438                written[2],
439            );
440            let status = if accepted {
441                StatusCode::ACCEPTED
442            } else {
443                StatusCode::NO_CONTENT
444            };
445            Ok((status, headers).into_response())
446        }
447        Err(error) => Ok(remote_write_v2_error_response(
448            error.error,
449            error.samples_written,
450            error.histograms_written,
451            error.exemplars_written,
452        )),
453    }
454}
455
456/// The axum-free core of a remote-write v2 ingestion, shared with
457/// `COPY FROM STDIN WITH (FORMAT promwrite, version 2)`. `db` labels the
458/// per-batch write-progress counters exactly as the HTTP route does.
459pub(crate) async fn ingest_remote_write_v2(
460    state: &PromStoreState,
461    db: &str,
462    has_pipeline: bool,
463    is_zstd: bool,
464    query_ctx: QueryContext,
465    body: Bytes,
466    body_reserved_bytes: u64,
467) -> std::result::Result<PromWriteResult, PromWriteV2Error> {
468    let PromStoreState {
469        prom_store_handler,
470        pending_rows_batcher,
471        prom_store_with_metric_engine,
472        memory_limiter,
473        ..
474    } = state;
475
476    let mut query_ctx = query_ctx;
477    let req = match decode_remote_write_v2(is_zstd, body, memory_limiter, body_reserved_bytes).await
478    {
479        Ok(req) => req,
480        Err(error) => {
481            return Err(PromWriteV2Error {
482                error,
483                samples_written: 0,
484                histograms_written: 0,
485                exemplars_written: 0,
486            });
487        }
488    };
489    if has_pipeline && req.exemplar_count > 0 {
490        return Err(PromWriteV2Error {
491            error: error::NotSupportedSnafu {
492                feat: "pipelines with exemplars",
493            }
494            .build(),
495            samples_written: 0,
496            histograms_written: 0,
497            exemplars_written: 0,
498        });
499    }
500    // The v2 per-series metadata upgrades the written tables' semantic options
501    // (metric type/unit, declared quality) at auto-create time.
502    if let Some(index) = req.semantic_index.encode(&query_ctx.current_schema()) {
503        query_ctx.set_extension(SEMANTIC_PER_TABLE_INDEX_KEY, index);
504    }
505    if req.exemplar_count > 0 {
506        let counter = crate::metrics::PROM_STORE_REMOTE_WRITE_EXEMPLARS
507            .with_label_values(&[db, REMOTE_WRITE_V2_VERSION]);
508        query_ctx.set_write_progress(Arc::new(
509            session::write_progress::WriteProgress::with_reservation(
510                req.memory_guard.granted_bytes(),
511                req.memory_guard.clone(),
512            )
513            .with_observer(move |rows| counter.inc_by(rows)),
514        ));
515    }
516    let query_ctx = Arc::new(query_ctx);
517    let (sample_count, histogram_count) = (req.sample_count, req.histogram_count);
518    let mut sample_batches = into_prom_write_batches(req.samples, query_ctx.clone());
519    let mut histogram_batches = into_prom_write_batches(req.histograms, query_ctx.clone());
520    for (batches, histogram) in [(&mut sample_batches, false), (&mut histogram_batches, true)] {
521        let counter = if histogram {
522            crate::metrics::PROM_STORE_REMOTE_WRITE_HISTOGRAMS
523                .with_label_values(&[db, REMOTE_WRITE_V2_VERSION])
524        } else {
525            crate::metrics::PROM_STORE_REMOTE_WRITE_SAMPLES
526                .with_label_values(&[db, REMOTE_WRITE_V2_VERSION])
527        };
528        for (ctx, _) in batches {
529            let counter = counter.clone();
530            let progress = session::write_progress::WriteProgress::with_reservation(
531                req.memory_guard.granted_bytes(),
532                req.memory_guard.clone(),
533            )
534            .with_observer(move |rows| counter.inc_by(rows));
535            let mut fork = ctx.fork();
536            fork.set_write_progress(Arc::new(progress));
537            *ctx = Arc::new(fork);
538        }
539    }
540    if req.exemplar_count > 0 {
541        let outcome = exemplar::write(
542            prom_store_handler.clone(),
543            pending_rows_batcher.clone(),
544            *prom_store_with_metric_engine,
545            sample_batches,
546            histogram_batches,
547            req.exemplars,
548            query_ctx,
549        )
550        .await;
551        if let Some(error) = outcome.error {
552            return Err(PromWriteV2Error {
553                error,
554                samples_written: outcome.written[0],
555                histograms_written: outcome.written[1],
556                exemplars_written: outcome.written[2],
557            });
558        }
559        return Ok(PromWriteResult {
560            written: outcome.written,
561            cost: outcome.cost,
562            accepted: outcome.accepted,
563        });
564    }
565    let outcome = write_prometheus_v2_rows_with_progress(
566        prom_store_handler.clone(),
567        pending_rows_batcher.clone(),
568        *prom_store_with_metric_engine,
569        sample_batches,
570        histogram_batches,
571    )
572    .await?;
573    debug_assert!(outcome.samples_written <= sample_count);
574    debug_assert!(outcome.histograms_written <= histogram_count);
575    Ok(PromWriteResult {
576        written: [outcome.samples_written, outcome.histograms_written, 0],
577        cost: outcome.write_cost,
578        accepted: outcome.accepted,
579    })
580}
581
582fn vm_proto_version_response(params: &RemoteWriteQuery) -> Option<axum::response::Response> {
583    params
584        .get_vm_proto_version
585        .as_ref()
586        .map(|_| VM_PROTO_VERSION.into_response())
587}
588
589/// Returns the context still un-shared so the caller can attach
590/// request-derived extensions (the v2 per-table metadata index) before
591/// wrapping it in an `Arc`.
592fn prepare_remote_write_context(
593    params: &RemoteWriteQuery,
594    mut query_ctx: QueryContext,
595    remote_write_version: &str,
596) -> (String, QueryContext, HistogramTimer) {
597    let db = params.db.clone().unwrap_or_default();
598    query_ctx.set_channel(Channel::Prometheus);
599    stamp_remote_write_extensions(
600        &mut query_ctx,
601        params.physical_table.as_deref(),
602        remote_write_version,
603    );
604    let timer = crate::metrics::METRIC_HTTP_PROM_STORE_WRITE_ELAPSED
605        .with_label_values(&[db.as_str(), remote_write_version])
606        .start_timer();
607
608    (db, query_ctx, timer)
609}
610
611/// Stamps the remote-write context extensions shared by the HTTP
612/// endpoint and COPY FROM STDIN: physical table and the Prometheus
613/// semantic identity the batched and direct write paths both rely on.
614pub(crate) fn stamp_remote_write_extensions(
615    query_ctx: &mut QueryContext,
616    physical_table: Option<&str>,
617    remote_write_version: &str,
618) {
619    let physical_table = physical_table
620        .map(String::from)
621        .unwrap_or_else(|| GREPTIME_PHYSICAL_TABLE.to_string());
622    query_ctx.set_extension(PHYSICAL_TABLE_PARAM, physical_table);
623    // Stamp the Prometheus metric identity here, before `as_req_iter` splits into the
624    // batched and direct write paths, so both inherit it (the batched path bypasses
625    // `PromStoreProtocolHandler::write`). Prometheus remote-write metadata is weak
626    // here, so the type is inferred from naming; v2 upgrades tables whose series
627    // carry inline metadata via the per-table index.
628    query_ctx.set_extension(SEMANTIC_SIGNAL_TYPE, SIGNAL_TYPE_METRIC);
629    query_ctx.set_extension(SEMANTIC_SOURCE, SOURCE_PROMETHEUS);
630    query_ctx.set_extension(SEMANTIC_SOURCE_VERSION, remote_write_version);
631    query_ctx.set_extension(SEMANTIC_METRIC_METADATA_QUALITY, METADATA_QUALITY_INFERRED);
632}
633
634struct PromWriteOutcome {
635    write_cost: usize,
636    rows_written: u64,
637}
638
639pub(crate) struct PromWriteError {
640    pub(crate) error: error::Error,
641    pub(crate) rows_written: u64,
642    pub(crate) exemplars_written: u64,
643}
644
645/// Transport-independent remote-write outcome for samples, histograms and exemplars.
646pub(crate) struct PromWriteResult {
647    /// Written counts, or accepted counts when v2 asynchronous batching is enabled.
648    pub(crate) written: [u64; 3],
649    pub(crate) cost: usize,
650    pub(crate) accepted: bool,
651}
652
653struct PromWriteV2Outcome {
654    accepted: bool,
655    write_cost: usize,
656    samples_written: u64,
657    histograms_written: u64,
658}
659
660pub(crate) struct PromWriteV2Error {
661    pub(crate) error: error::Error,
662    pub(crate) samples_written: u64,
663    pub(crate) histograms_written: u64,
664    pub(crate) exemplars_written: u64,
665}
666
667type PromWriteBatch = (QueryContextRef, RowInsertRequests);
668
669#[async_trait]
670trait PromWriteBatcher: Send + Sync {
671    async fn submit(&self, requests: RowInsertRequests, ctx: QueryContextRef) -> Result<u64>;
672}
673
674#[async_trait]
675impl PromWriteBatcher for LogicalTablePendingRowsBatcher {
676    async fn submit(&self, requests: RowInsertRequests, ctx: QueryContextRef) -> Result<u64> {
677        LogicalTablePendingRowsBatcher::submit(self, requests, ctx).await
678    }
679}
680
681fn into_prom_write_batches(req: ContextReq, query_ctx: QueryContextRef) -> Vec<PromWriteBatch> {
682    req.as_req_iter(query_ctx).collect()
683}
684
685async fn preflight_prometheus_rows(
686    prom_store_handler: &PromStoreProtocolHandlerRef,
687    batches: &mut [PromWriteBatch],
688) -> Result<()> {
689    for (ctx, reqs) in batches.iter_mut() {
690        prom_store_handler.pre_write(reqs, ctx.clone()).await?;
691        // Detach from context clones retained by pre-write hooks so the checked
692        // schema cannot change before this prepared batch is written.
693        *ctx = Arc::new(ctx.fork());
694    }
695    operator::insert::admit_row_insert_batches(batches)
696        .await
697        .map_err(BoxedError::new)
698        .context(error::ExecuteGrpcQuerySnafu)?;
699    Ok(())
700}
701
702/// Writes preflighted PRW batches and keeps the number of persisted rows on error.
703///
704/// The v2 handler uses that partial progress to return Prometheus' written
705/// sample/histogram headers even when a later table write fails.
706async fn write_prometheus_rows_with_progress(
707    prom_store_handler: PromStoreProtocolHandlerRef,
708    pending_rows_batcher: Option<Arc<LogicalTablePendingRowsBatcher>>,
709    prom_store_with_metric_engine: bool,
710    mut batches: Vec<PromWriteBatch>,
711) -> std::result::Result<PromWriteOutcome, PromWriteError> {
712    if prom_store_with_metric_engine && let Some(batcher) = pending_rows_batcher {
713        // Preflight before the bulk eligibility decision: pre_write hooks
714        // may redirect the contexts (e.g. to a per-tenant schema), so
715        // eligibility must be evaluated against the prepared batches —
716        // and the fallback below reuses them without re-running hooks or
717        // admission.
718        preflight_prometheus_rows(&prom_store_handler, &mut batches)
719            .await
720            .map_err(|error| PromWriteError {
721                error,
722                rows_written: 0,
723                exemplars_written: 0,
724            })?;
725        // Destinations bound to another physical table must stay on the
726        // ordinary insert path, which routes per destination; time index
727        // units need no check — the bulk encode converts each request to
728        // its destination's unit.
729        if batcher
730            .accepts_bulk_destinations(batches.iter().map(|(ctx, request)| (ctx, request)))
731            .await
732        {
733            let mut rows_written = 0;
734            for (temp_ctx, reqs) in batches {
735                let rows =
736                    batcher
737                        .submit(reqs, temp_ctx)
738                        .await
739                        .map_err(|error| PromWriteError {
740                            error,
741                            rows_written,
742                            exemplars_written: 0,
743                        })?;
744                rows_written += rows;
745            }
746            return Ok(PromWriteOutcome {
747                write_cost: 0,
748                rows_written,
749            });
750        }
751        return write_prepared_prometheus_rows_with_progress(
752            prom_store_handler,
753            batches,
754            prom_store_with_metric_engine,
755        )
756        .await;
757    }
758
759    let row_counts = batches
760        .iter()
761        .map(|(_, request)| prom_write_row_count(request))
762        .collect::<Vec<_>>();
763    let batch_count = batches.len();
764    let outputs = prom_store_handler
765        .write_all(batches, prom_store_with_metric_engine)
766        .await
767        .map_err(|error| PromWriteError {
768            error,
769            rows_written: 0,
770            exemplars_written: 0,
771        })?;
772    let output_count = outputs.len();
773    let mut write_cost = 0;
774    let mut rows_written = 0;
775    for (output, rows) in outputs.into_iter().zip(row_counts) {
776        let output = output.map_err(|error| PromWriteError {
777            error,
778            rows_written,
779            exemplars_written: 0,
780        })?;
781        write_cost += output.meta.cost;
782        rows_written += rows;
783    }
784    if output_count != batch_count {
785        return Err(PromWriteError {
786            error: incomplete_prom_write_error(),
787            rows_written,
788            exemplars_written: 0,
789        });
790    }
791
792    Ok(PromWriteOutcome {
793        write_cost,
794        rows_written,
795    })
796}
797
798/// Writes already-preflighted batches through the ordinary (prepared) write
799/// path; the pre_write hooks and admission have already run.
800async fn write_prepared_prometheus_rows_with_progress(
801    prom_store_handler: PromStoreProtocolHandlerRef,
802    batches: Vec<PromWriteBatch>,
803    prom_store_with_metric_engine: bool,
804) -> std::result::Result<PromWriteOutcome, PromWriteError> {
805    let mut write_cost = 0;
806    let mut rows_written = 0;
807    for (ctx, request) in batches {
808        let rows = prom_write_row_count(&request);
809        let output = prom_store_handler
810            .write_prepared(request, ctx, prom_store_with_metric_engine)
811            .await
812            .map_err(|error| PromWriteError {
813                error,
814                rows_written,
815                exemplars_written: 0,
816            })?;
817        write_cost += output.meta.cost;
818        rows_written += rows;
819    }
820    Ok(PromWriteOutcome {
821        write_cost,
822        rows_written,
823    })
824}
825
826async fn write_prometheus_v2_rows_with_progress(
827    prom_store_handler: PromStoreProtocolHandlerRef,
828    pending_rows_batcher: Option<Arc<LogicalTablePendingRowsBatcher>>,
829    prom_store_with_metric_engine: bool,
830    sample_batches: Vec<PromWriteBatch>,
831    histogram_batches: Vec<PromWriteBatch>,
832) -> std::result::Result<PromWriteV2Outcome, PromWriteV2Error> {
833    let sample_batch_count = sample_batches.len();
834    let mut batches = sample_batches;
835    batches.extend(histogram_batches);
836    preflight_prometheus_rows(&prom_store_handler, &mut batches)
837        .await
838        .map_err(|error| PromWriteV2Error {
839            error,
840            samples_written: 0,
841            histograms_written: 0,
842            exemplars_written: 0,
843        })?;
844    let batcher = if prom_store_with_metric_engine
845        && let Some(batcher) = pending_rows_batcher.as_ref()
846        && batcher
847            .accepts_bulk_destinations(batches.iter().map(|(ctx, request)| (ctx, request)))
848            .await
849    {
850        Some(batcher.as_ref() as &dyn PromWriteBatcher)
851    } else {
852        None
853    };
854    write_batched_prometheus_v2_rows_with_progress(
855        prom_store_handler,
856        batcher,
857        prom_store_with_metric_engine,
858        sample_batch_count,
859        batches,
860    )
861    .await
862}
863
864async fn write_batched_prometheus_v2_rows_with_progress(
865    prom_store_handler: PromStoreProtocolHandlerRef,
866    batcher: Option<&dyn PromWriteBatcher>,
867    prom_store_with_metric_engine: bool,
868    sample_batch_count: usize,
869    mut batches: Vec<PromWriteBatch>,
870) -> std::result::Result<PromWriteV2Outcome, PromWriteV2Error> {
871    let progress = batches
872        .iter_mut()
873        .map(|(ctx, _)| {
874            if ctx.write_progress().is_none() {
875                let mut fork = ctx.fork();
876                fork.set_write_progress(
877                    Arc::new(session::write_progress::WriteProgress::default()),
878                );
879                *ctx = Arc::new(fork);
880            }
881            ctx.write_progress().cloned().unwrap_or_default()
882        })
883        .collect::<Vec<_>>();
884    let counts = || {
885        let samples = progress[..sample_batch_count]
886            .iter()
887            .map(|p| p.written())
888            .sum();
889        let histograms = progress[sample_batch_count..]
890            .iter()
891            .map(|p| p.written())
892            .sum();
893        (samples, histograms)
894    };
895    let mut write_cost = 0;
896    let mut samples_accepted = 0;
897    let mut histograms_accepted = 0;
898    for (index, (ctx, requests)) in batches.into_iter().enumerate() {
899        let result = if index < sample_batch_count
900            && let Some(batcher) = batcher
901        {
902            batcher
903                .submit(requests, ctx)
904                .await
905                .map(|rows| (rows, 0, false))
906        } else {
907            prom_store_handler
908                .write_prepared(requests, ctx, prom_store_with_metric_engine)
909                .await
910                .map(|output| {
911                    let pending = !output.meta.write_completions.is_empty();
912                    let (rows, cost) = output.extract_rows_and_cost();
913                    (rows as u64, cost, pending)
914                })
915        };
916        match result {
917            Ok((rows, cost, pending)) => {
918                write_cost += cost;
919                if index < sample_batch_count {
920                    samples_accepted += rows;
921                } else {
922                    histograms_accepted += rows;
923                }
924                if pending {
925                    progress[index].mark_accepted();
926                }
927                if !progress[index].accepted() {
928                    progress[index].confirm(rows);
929                }
930            }
931            Err(error) => {
932                for progress in &progress {
933                    progress.wait().await;
934                }
935                let (samples_written, histograms_written) = counts();
936                return Err(PromWriteV2Error {
937                    error,
938                    samples_written,
939                    histograms_written,
940                    exemplars_written: 0,
941                });
942            }
943        }
944    }
945    Ok(PromWriteV2Outcome {
946        write_cost,
947        // PRW counts accepted rows on success; errors above report confirmed storage writes.
948        samples_written: samples_accepted,
949        histograms_written: histograms_accepted,
950        accepted: progress.iter().any(|p| p.accepted()),
951    })
952}
953
954fn prom_write_row_count(request: &RowInsertRequests) -> u64 {
955    request
956        .inserts
957        .iter()
958        .filter_map(|insert| insert.rows.as_ref().map(|rows| rows.rows.len() as u64))
959        .sum()
960}
961
962fn incomplete_prom_write_error() -> error::Error {
963    InternalSnafu {
964        err_msg: "prometheus write handler returned before processing every batch".to_string(),
965    }
966    .build()
967}
968
969fn record_remote_write_samples(db: &str, version: &str, rows: u64) {
970    if rows == 0 {
971        return;
972    }
973    crate::metrics::PROM_STORE_REMOTE_WRITE_SAMPLES
974        .with_label_values(&[db, version])
975        .inc_by(rows);
976}
977
978fn record_remote_write_exemplars(db: &str, version: &str, rows: u64) {
979    if rows != 0 {
980        crate::metrics::PROM_STORE_REMOTE_WRITE_EXEMPLARS
981            .with_label_values(&[db, version])
982            .inc_by(rows);
983    }
984}
985
986fn remote_write_v2_error_response(
987    error: error::Error,
988    samples: u64,
989    histograms: u64,
990    exemplars: u64,
991) -> axum::response::Response {
992    let mut response = error.into_response();
993    append_remote_write_v2_written_headers(response.headers_mut(), samples, histograms, exemplars);
994    response
995}
996
997fn append_remote_write_v2_written_headers(
998    headers: &mut HeaderMap,
999    samples: u64,
1000    histograms: u64,
1001    exemplars: u64,
1002) {
1003    headers.insert(
1004        REMOTE_WRITE_V2_SAMPLES_WRITTEN_HEADER,
1005        HeaderValue::from_str(&samples.to_string()).expect("u64 header value is valid"),
1006    );
1007    headers.insert(
1008        REMOTE_WRITE_V2_HISTOGRAMS_WRITTEN_HEADER,
1009        HeaderValue::from_str(&histograms.to_string()).expect("u64 header value is valid"),
1010    );
1011    headers.insert(
1012        REMOTE_WRITE_V2_EXEMPLARS_WRITTEN_HEADER,
1013        HeaderValue::from_str(&exemplars.to_string()).expect("u64 header value is valid"),
1014    );
1015}
1016
1017enum RemoteWriteProto {
1018    V1,
1019    V2,
1020    Unsupported(mime::Mime),
1021}
1022
1023// ref: https://github.com/prometheus/client_golang/blob/74560058a7af7a695db8196c8e84a0754032c6af/exp/api/remote/remote_api.go#L544
1024fn remote_write_proto(content_type: Option<TypedHeader<headers::ContentType>>) -> RemoteWriteProto {
1025    let Some(TypedHeader(content_type)) = content_type else {
1026        return RemoteWriteProto::V1;
1027    };
1028
1029    let mime_type: mime::Mime = content_type.into();
1030    if !mime_type
1031        .essence_str()
1032        .eq_ignore_ascii_case(CONTENT_TYPE_PROTOBUF_STR)
1033    {
1034        return RemoteWriteProto::Unsupported(mime_type);
1035    }
1036
1037    for (name, value) in mime_type.params() {
1038        if !name.as_str().eq_ignore_ascii_case(CONTENT_TYPE_PROTO_PARAM) {
1039            continue;
1040        }
1041
1042        return match value.as_str() {
1043            REMOTE_WRITE_V1_PROTO => RemoteWriteProto::V1,
1044            REMOTE_WRITE_V2_PROTO => RemoteWriteProto::V2,
1045            _ => RemoteWriteProto::Unsupported(mime_type.clone()),
1046        };
1047    }
1048
1049    RemoteWriteProto::V1
1050}
1051
1052fn unsupported_remote_write_v2_encoding_response(
1053    content_encoding: &headers::ContentEncoding,
1054) -> Option<axum::response::Response> {
1055    if content_encoding.contains(DEFAULT_ENCODING) || content_encoding.contains(VM_ENCODING) {
1056        return None;
1057    }
1058
1059    Some((
1060        StatusCode::UNSUPPORTED_MEDIA_TYPE,
1061        format!(
1062            "unsupported prometheus remote write content encoding: only {DEFAULT_ENCODING} and {VM_ENCODING} are supported"
1063        ),
1064    )
1065        .into_response())
1066}
1067
1068impl IntoResponse for PromStoreResponse {
1069    fn into_response(self) -> axum::response::Response {
1070        let mut header_map = HeaderMap::new();
1071        header_map.insert(&header::CONTENT_TYPE, self.content_type);
1072        header_map.insert(&header::CONTENT_ENCODING, self.content_encoding);
1073
1074        let metrics = if self.resp_metrics.is_empty() {
1075            None
1076        } else {
1077            serde_json::to_string(&self.resp_metrics).ok()
1078        };
1079        if let Some(m) = metrics.and_then(|m| HeaderValue::from_str(&m).ok()) {
1080            header_map.insert(&GREPTIME_DB_HEADER_METRICS, m);
1081        }
1082
1083        (header_map, self.body).into_response()
1084    }
1085}
1086
1087#[axum_macros::debug_handler]
1088#[tracing::instrument(
1089    skip_all,
1090    fields(protocol = "prometheus", request_type = "remote_read")
1091)]
1092pub async fn remote_read(
1093    State(state): State<PromStoreState>,
1094    Query(params): Query<RemoteWriteQuery>,
1095    Extension(mut query_ctx): Extension<QueryContext>,
1096    body: Bytes,
1097) -> Result<PromStoreResponse> {
1098    let db = params.db.clone().unwrap_or_default();
1099    query_ctx.set_channel(Channel::Prometheus);
1100
1101    let request = decode_remote_read_request(body, &state.memory_limiter).await?;
1102
1103    let query_ctx = Arc::new(query_ctx);
1104    let _timer = crate::metrics::METRIC_HTTP_PROM_STORE_READ_ELAPSED
1105        .with_label_values(&[db.as_str()])
1106        .start_timer();
1107
1108    state.prom_store_handler.read(request, query_ctx).await
1109}
1110
1111async fn decode_remote_read_request(
1112    body: Bytes,
1113    limiter: &ServerMemoryLimiter,
1114) -> Result<ReadRequest> {
1115    // Holds the memory permits for the decompressed bytes until the protobuf
1116    // decoding is finished.
1117    let buf =
1118        snappy_decompress_limited(&body[..], MAX_DECOMPRESSED_REQUEST_SIZE, limiter, 0).await?;
1119
1120    ReadRequest::decode(&buf[..]).context(error::DecodePromRemoteRequestSnafu)
1121}
1122
1123#[cfg(test)]
1124mod exemplar_accounting_tests {
1125    use super::*;
1126    use crate::http::{HttpOptions, HttpServerBuilder};
1127    use crate::query_handler::PromStoreProtocolHandler;
1128    use common_memory_manager::OnExhaustedPolicy;
1129    use common_query::Output;
1130    use tower::ServiceExt;
1131
1132    use axum::body::Body;
1133    use axum::http::Request;
1134
1135    /// Reports written rows without touching counters, with an optional exemplar
1136    /// failure, so ingestion accounting can be observed in isolation.
1137    struct RecordingHandler {
1138        fail_exemplars: bool,
1139    }
1140
1141    #[async_trait]
1142    impl PromStoreProtocolHandler for RecordingHandler {
1143        async fn pre_write(&self, _: &RowInsertRequests, _: QueryContextRef) -> Result<()> {
1144            Ok(())
1145        }
1146        async fn pre_write_exemplars(
1147            &self,
1148            _: &operator::insert::ExemplarBatch,
1149            _: QueryContextRef,
1150        ) -> Result<()> {
1151            Ok(())
1152        }
1153        async fn write_exemplars_prepared(
1154            &self,
1155            exemplars: operator::insert::ExemplarBatch,
1156            _: QueryContextRef,
1157        ) -> Result<Output> {
1158            if self.fail_exemplars {
1159                return Err(crate::error::NotSupportedSnafu {
1160                    feat: "injected failure",
1161                }
1162                .build());
1163            }
1164            Ok(Output::new_with_affected_rows(exemplars.len()))
1165        }
1166        async fn write_prepared(
1167            &self,
1168            request: RowInsertRequests,
1169            _: QueryContextRef,
1170            _: bool,
1171        ) -> Result<Output> {
1172            Ok(Output::new_with_affected_rows(
1173                prom_write_row_count(&request) as usize,
1174            ))
1175        }
1176        async fn write(&self, _: RowInsertRequests, _: QueryContextRef, _: bool) -> Result<Output> {
1177            unreachable!()
1178        }
1179        async fn write_all(&self, _: Vec<PromWriteBatch>, _: bool) -> Result<Vec<Result<Output>>> {
1180            unreachable!()
1181        }
1182        async fn read(&self, _: ReadRequest, _: QueryContextRef) -> Result<PromStoreResponse> {
1183            unreachable!()
1184        }
1185    }
1186
1187    async fn post_v1_exemplars(
1188        db: &str,
1189        handler: Arc<RecordingHandler>,
1190        sample_count: usize,
1191        exemplar_count: usize,
1192        through_http: bool,
1193    ) -> StatusCode {
1194        use api::prom_store::remote;
1195
1196        let request = remote::WriteRequest {
1197            // Separate sources keep sample writes on write_prepared rather than
1198            // requiring the stub to resolve real metric-engine table identities.
1199            timeseries: vec![
1200                remote::TimeSeries {
1201                    labels: vec![remote::Label {
1202                        name: "__name__".into(),
1203                        value: "counter_test_samples".into(),
1204                    }],
1205                    samples: (0..sample_count)
1206                        .map(|i| remote::Sample {
1207                            value: i as f64,
1208                            timestamp: i as i64,
1209                        })
1210                        .collect(),
1211                    ..Default::default()
1212                },
1213                remote::TimeSeries {
1214                    labels: vec![remote::Label {
1215                        name: "__name__".into(),
1216                        value: "counter_test_metric".into(),
1217                    }],
1218                    exemplars: vec![remote::Exemplar::default(); exemplar_count],
1219                    ..Default::default()
1220                },
1221            ],
1222            ..Default::default()
1223        };
1224        let body = crate::prom_store::snappy_compress(&request.encode_to_vec()).unwrap();
1225        let memory_limiter = ServerMemoryLimiter::new(1024 * 1024, OnExhaustedPolicy::Fail);
1226        if !through_http {
1227            let state = PromStoreState {
1228                prom_store_handler: handler,
1229                pipeline_handler: None,
1230                prom_store_with_metric_engine: true,
1231                prom_validation_mode: PromValidationMode::Strict,
1232                pending_rows_batcher: None,
1233                memory_limiter,
1234            };
1235            let result = ingest_remote_write_v1(
1236                &state,
1237                db,
1238                PipelineInfo {
1239                    pipeline_name: None,
1240                    pipeline_version: None,
1241                    pipeline_params: Default::default(),
1242                },
1243                false,
1244                QueryContext::arc(),
1245                Bytes::from(body),
1246                0,
1247            )
1248            .await;
1249            return if result.is_ok() {
1250                StatusCode::NO_CONTENT
1251            } else {
1252                StatusCode::BAD_REQUEST
1253            };
1254        }
1255        let server = HttpServerBuilder::new(HttpOptions::default())
1256            .with_memory_limiter(memory_limiter)
1257            .with_prom_handler(handler, None, true, PromValidationMode::Strict, None)
1258            .build();
1259        server
1260            .build(server.make_app())
1261            .unwrap()
1262            .oneshot(
1263                Request::post(format!("/v1/prometheus/write?db={db}"))
1264                    .header(header::CONTENT_TYPE, "application/x-protobuf")
1265                    .header(header::CONTENT_ENCODING, DEFAULT_ENCODING)
1266                    .body(Body::from(body))
1267                    .unwrap(),
1268            )
1269            .await
1270            .unwrap()
1271            .status()
1272    }
1273
1274    fn counter(db: &str, version: &str, exemplars: bool) -> u64 {
1275        if exemplars {
1276            crate::metrics::PROM_STORE_REMOTE_WRITE_EXEMPLARS
1277                .with_label_values(&[db, version])
1278                .get()
1279        } else {
1280            crate::metrics::PROM_STORE_REMOTE_WRITE_SAMPLES
1281                .with_label_values(&[db, version])
1282                .get()
1283        }
1284    }
1285
1286    /// HTTP and direct core callers (COPY) count successful and partial writes
1287    /// exactly once; transport wrappers must not duplicate core accounting.
1288    #[tokio::test]
1289    async fn v1_exemplar_counters_are_recorded_once() {
1290        // Counters are process-global, so use an isolated db label and deltas.
1291        let db = format!("once-{}", std::process::id());
1292        for (through_http, fail_exemplars, samples, exemplars) in [
1293            (true, false, 10, 2),
1294            (true, true, 3, 1),
1295            (false, false, 10, 2),
1296            (false, true, 3, 1),
1297        ] {
1298            let samples_before = counter(&db, REMOTE_WRITE_V1_VERSION, false);
1299            let exemplars_before = counter(&db, REMOTE_WRITE_V1_VERSION, true);
1300            let response = post_v1_exemplars(
1301                &db,
1302                Arc::new(RecordingHandler { fail_exemplars }),
1303                samples,
1304                exemplars,
1305                through_http,
1306            )
1307            .await;
1308            assert_eq!(
1309                response,
1310                if fail_exemplars {
1311                    StatusCode::BAD_REQUEST
1312                } else {
1313                    StatusCode::NO_CONTENT
1314                }
1315            );
1316            // A failed exemplar write still leaves the successful samples counted.
1317            assert_eq!(
1318                counter(&db, REMOTE_WRITE_V1_VERSION, false) - samples_before,
1319                samples as u64
1320            );
1321            assert_eq!(
1322                counter(&db, REMOTE_WRITE_V1_VERSION, true) - exemplars_before,
1323                if fail_exemplars { 0 } else { exemplars as u64 }
1324            );
1325        }
1326    }
1327}
1328
1329#[cfg(test)]
1330mod tests {
1331    use std::sync::Mutex;
1332    use std::time::Duration;
1333
1334    use api::prom_store::remote::ReadRequest;
1335    use api::v1::{Row, RowInsertRequest, Rows};
1336    use async_trait::async_trait;
1337    use axum::body::Body;
1338    use axum::http::Request;
1339    use axum::{Router, middleware, routing};
1340    use common_query::Output;
1341    use pipeline::GreptimePipelineParams;
1342    use session::context::{QueryContext, QueryContextRef};
1343    use tower::ServiceExt;
1344
1345    use super::*;
1346    use crate::http::memory_limit::memory_limit_middleware;
1347    use crate::prom_remote_write::validation::PromValidationMode;
1348    use crate::query_handler::PromStoreProtocolHandler;
1349
1350    #[test]
1351    fn test_remote_write_proto() {
1352        assert!(matches!(
1353            remote_write_proto(content_type(
1354                "application/x-protobuf;proto=io.prometheus.write.v2.Request"
1355            )),
1356            RemoteWriteProto::V2
1357        ));
1358        assert!(matches!(
1359            remote_write_proto(content_type(
1360                "application/x-protobuf; proto=\"io.prometheus.write.v2.Request\""
1361            )),
1362            RemoteWriteProto::V2
1363        ));
1364        assert!(matches!(
1365            remote_write_proto(content_type(
1366                "APPLICATION/X-PROTOBUF;proto=io.prometheus.write.v2.Request"
1367            )),
1368            RemoteWriteProto::V2
1369        ));
1370        assert!(matches!(
1371            remote_write_proto(content_type("application/x-protobuf")),
1372            RemoteWriteProto::V1
1373        ));
1374        assert!(matches!(
1375            remote_write_proto(content_type(
1376                "application/x-protobuf;proto=prometheus.WriteRequest"
1377            )),
1378            RemoteWriteProto::V1
1379        ));
1380        assert!(matches!(
1381            remote_write_proto(content_type(
1382                "application/x-protobuf;proto=unknown.WriteRequest"
1383            )),
1384            RemoteWriteProto::Unsupported(_)
1385        ));
1386        assert!(matches!(
1387            remote_write_proto(content_type(
1388                "application/json;proto=io.prometheus.write.v2.Request"
1389            )),
1390            RemoteWriteProto::Unsupported(_)
1391        ));
1392        assert!(matches!(remote_write_proto(None), RemoteWriteProto::V1));
1393    }
1394
1395    fn content_type(value: &str) -> Option<TypedHeader<headers::ContentType>> {
1396        Some(TypedHeader(std::str::FromStr::from_str(value).unwrap()))
1397    }
1398
1399    #[test]
1400    fn test_prepare_remote_write_context_stamps_semantics() {
1401        let (_, query_ctx, _timer) = prepare_remote_write_context(
1402            &RemoteWriteQuery::default(),
1403            QueryContext::with("greptime", "public"),
1404            REMOTE_WRITE_V2_VERSION,
1405        );
1406
1407        assert_eq!(
1408            query_ctx.extension(SEMANTIC_SIGNAL_TYPE),
1409            Some(SIGNAL_TYPE_METRIC)
1410        );
1411        assert_eq!(
1412            query_ctx.extension(SEMANTIC_SOURCE),
1413            Some(SOURCE_PROMETHEUS)
1414        );
1415        assert_eq!(
1416            query_ctx.extension(SEMANTIC_SOURCE_VERSION),
1417            Some(REMOTE_WRITE_V2_VERSION)
1418        );
1419        assert_eq!(
1420            query_ctx.extension(SEMANTIC_METRIC_METADATA_QUALITY),
1421            Some(METADATA_QUALITY_INFERRED)
1422        );
1423    }
1424
1425    #[tokio::test]
1426    async fn test_mixed_v2_preflights_all_then_batches_only_samples() {
1427        let events = Arc::new(Mutex::new(Vec::new()));
1428        let handler: PromStoreProtocolHandlerRef = Arc::new(RecordingPromStoreHandler {
1429            events: events.clone(),
1430        });
1431        let batcher = RecordingPromWriteBatcher {
1432            events: events.clone(),
1433        };
1434
1435        let mut batches = vec![
1436            test_prom_write_batch("sample"),
1437            test_prom_write_batch("histogram"),
1438        ];
1439        // The caller preflights before choosing the bulk path; the batched
1440        // writer consumes the prepared batches.
1441        preflight_prometheus_rows(&handler, &mut batches)
1442            .await
1443            .unwrap();
1444        let Ok(outcome) = write_batched_prometheus_v2_rows_with_progress(
1445            handler,
1446            Some(&batcher),
1447            true,
1448            1,
1449            batches,
1450        )
1451        .await
1452        else {
1453            panic!("mixed remote write should succeed")
1454        };
1455
1456        assert_eq!(1, outcome.samples_written);
1457        assert_eq!(1, outcome.histograms_written);
1458        assert_eq!(
1459            vec![
1460                "pre:sample".to_string(),
1461                "pre:histogram".to_string(),
1462                "batch:sample".to_string(),
1463                "direct:histogram".to_string(),
1464            ],
1465            *events.lock().unwrap()
1466        );
1467    }
1468
1469    fn test_prom_write_batch(table_name: &str) -> PromWriteBatch {
1470        (
1471            Arc::new(QueryContext::with("greptime", "public")),
1472            RowInsertRequests {
1473                inserts: vec![RowInsertRequest {
1474                    table_name: table_name.to_string(),
1475                    rows: Some(Rows {
1476                        schema: Vec::new(),
1477                        rows: vec![Row { values: Vec::new() }],
1478                    }),
1479                }],
1480            },
1481        )
1482    }
1483
1484    #[tokio::test]
1485    async fn test_mixed_write_requires_exemplar_destination_preflight() {
1486        let handler = Arc::new(RecordingPromStoreHandler {
1487            events: Default::default(),
1488        });
1489        let exemplar = crate::exemplar::Exemplar {
1490            metric: "exemplar_source".into(),
1491            series_labels: Default::default(),
1492            labels: Default::default(),
1493            timestamp: 1,
1494            value: 1.0,
1495        };
1496        let outcome = exemplar::write(
1497            handler.clone(),
1498            None,
1499            true,
1500            vec![test_prom_write_batch("sample")],
1501            vec![],
1502            [(None, vec![exemplar])].into(),
1503            QueryContext::arc(),
1504        )
1505        .await;
1506
1507        assert_eq!(outcome.written, [0, 0, 0]);
1508        assert!(
1509            matches!(outcome.error, Some(error::Error::NotSupported { feat }) if feat == "exemplar destination preflight")
1510        );
1511        let events = handler.events.lock().unwrap();
1512        assert!(
1513            events.iter().all(|event| event.starts_with("pre:")),
1514            "{events:?}"
1515        );
1516    }
1517
1518    #[tokio::test]
1519    async fn test_async_v2_counts_acceptance_without_confirming_storage() {
1520        let handler: PromStoreProtocolHandlerRef = Arc::new(RecordingPromStoreHandler {
1521            events: Default::default(),
1522        });
1523        let mut batches = vec![
1524            test_prom_write_batch("queued"),
1525            test_prom_write_batch("queued"),
1526        ];
1527        let mut progress = Vec::new();
1528        for (ctx, _) in &mut batches {
1529            let tracker = Arc::new(session::write_progress::WriteProgress::default());
1530            Arc::get_mut(ctx)
1531                .unwrap()
1532                .set_write_progress(tracker.clone());
1533            progress.push(tracker);
1534        }
1535        preflight_prometheus_rows(&handler, &mut batches)
1536            .await
1537            .unwrap();
1538        let Ok(outcome) =
1539            write_batched_prometheus_v2_rows_with_progress(handler, None, true, 1, batches).await
1540        else {
1541            panic!("queued writes should be accepted")
1542        };
1543        assert!(outcome.accepted);
1544        assert_eq!(outcome.samples_written, 1);
1545        assert_eq!(outcome.histograms_written, 1);
1546        assert!(progress.iter().all(|tracker| tracker.written() == 0));
1547    }
1548
1549    fn record_write_event(events: &Mutex<Vec<String>>, phase: &str, request: &RowInsertRequests) {
1550        events.lock().unwrap().push(format!(
1551            "{phase}:{}",
1552            request.inserts.first().unwrap().table_name
1553        ));
1554    }
1555
1556    #[tokio::test]
1557    async fn test_failed_request_waits_for_earlier_queued_writes() {
1558        struct DelayedBatcher(
1559            Mutex<
1560                Option<(
1561                    Arc<session::write_progress::WriteProgress>,
1562                    session::write_progress::PendingWrite,
1563                )>,
1564            >,
1565        );
1566        #[async_trait]
1567        impl PromWriteBatcher for DelayedBatcher {
1568            async fn submit(
1569                &self,
1570                request: RowInsertRequests,
1571                ctx: QueryContextRef,
1572            ) -> Result<u64> {
1573                let progress = ctx.write_progress().unwrap().clone();
1574                let pending = progress.start();
1575                progress.mark_accepted();
1576                *self.0.lock().unwrap() = Some((progress, pending));
1577                Ok(prom_write_row_count(&request))
1578            }
1579        }
1580        let handler: PromStoreProtocolHandlerRef = Arc::new(RecordingPromStoreHandler {
1581            events: Default::default(),
1582        });
1583        let batcher = DelayedBatcher(Mutex::new(None));
1584        let mut batches = vec![
1585            test_prom_write_batch("queued"),
1586            test_prom_write_batch("partial"),
1587        ];
1588        preflight_prometheus_rows(&handler, &mut batches)
1589            .await
1590            .unwrap();
1591        let write = write_batched_prometheus_v2_rows_with_progress(
1592            handler,
1593            Some(&batcher),
1594            true,
1595            1,
1596            batches,
1597        );
1598        tokio::pin!(write);
1599        assert!(futures::poll!(write.as_mut()).is_pending());
1600        let (progress, pending) = batcher.0.lock().unwrap().take().unwrap();
1601        progress.add_written(1);
1602        drop(pending);
1603        let Err(error) = write.await else {
1604            panic!("the second batch must fail")
1605        };
1606        assert_eq!(error.samples_written, 1);
1607        assert_eq!(error.histograms_written, 1);
1608    }
1609
1610    struct RecordingPromWriteBatcher {
1611        events: Arc<Mutex<Vec<String>>>,
1612    }
1613
1614    #[async_trait]
1615    impl PromWriteBatcher for RecordingPromWriteBatcher {
1616        async fn submit(&self, requests: RowInsertRequests, ctx: QueryContextRef) -> Result<u64> {
1617            assert_eq!(ctx.write_rows_to_admit("greptime", "public", 1), 0);
1618            record_write_event(&self.events, "batch", &requests);
1619            Ok(prom_write_row_count(&requests))
1620        }
1621    }
1622
1623    struct RecordingPromStoreHandler {
1624        events: Arc<Mutex<Vec<String>>>,
1625    }
1626
1627    #[async_trait]
1628    impl PromStoreProtocolHandler for RecordingPromStoreHandler {
1629        async fn pre_write(
1630            &self,
1631            request: &RowInsertRequests,
1632            _ctx: QueryContextRef,
1633        ) -> Result<()> {
1634            record_write_event(&self.events, "pre", request);
1635            Ok(())
1636        }
1637
1638        async fn write_exemplars_prepared(
1639            &self,
1640            exemplars: operator::insert::ExemplarBatch,
1641            _: QueryContextRef,
1642        ) -> Result<Output> {
1643            self.events.lock().unwrap().push("exemplar".into());
1644            Ok(Output::new_with_affected_rows(exemplars.len()))
1645        }
1646
1647        async fn write_prepared(
1648            &self,
1649            request: RowInsertRequests,
1650            ctx: QueryContextRef,
1651            _with_metric_engine: bool,
1652        ) -> Result<Output> {
1653            assert_eq!(ctx.write_rows_to_admit("greptime", "public", 1), 0);
1654            record_write_event(&self.events, "direct", &request);
1655            match request.inserts[0].table_name.as_str() {
1656                "partial" => {
1657                    ctx.write_progress().unwrap().add_written(1);
1658                    return Err(InternalSnafu {
1659                        err_msg: "one region failed",
1660                    }
1661                    .build());
1662                }
1663                "queued" => ctx.write_progress().unwrap().mark_accepted(),
1664                _ => {}
1665            }
1666            Ok(Output::new_with_affected_rows(
1667                prom_write_row_count(&request) as usize,
1668            ))
1669        }
1670
1671        async fn write(
1672            &self,
1673            _request: RowInsertRequests,
1674            _ctx: QueryContextRef,
1675            _with_metric_engine: bool,
1676        ) -> Result<Output> {
1677            unreachable!("mixed v2 writes use preflighted execution")
1678        }
1679
1680        async fn write_all(
1681            &self,
1682            _requests: Vec<(QueryContextRef, RowInsertRequests)>,
1683            _with_metric_engine: bool,
1684        ) -> Result<Vec<Result<Output>>> {
1685            unreachable!("mixed v2 writes preserve sample and histogram routing")
1686        }
1687
1688        async fn read(
1689            &self,
1690            _request: ReadRequest,
1691            _ctx: QueryContextRef,
1692        ) -> Result<PromStoreResponse> {
1693            unimplemented!()
1694        }
1695    }
1696
1697    #[tokio::test]
1698    async fn test_remote_write_v2_reports_confirmed_partial_and_queued_writes() {
1699        for (name, expected_status, expected_count) in [
1700            ("confirmed", StatusCode::NO_CONTENT, "2"),
1701            ("partial", StatusCode::INTERNAL_SERVER_ERROR, "1"),
1702            ("queued", StatusCode::ACCEPTED, "2"),
1703        ] {
1704            let request = crate::prom_remote_write::v2::test_util::request_with_labels_and_samples(
1705                vec![("__name__", name)],
1706                vec![api::greptime_proto::io::prometheus::write::v2::Sample::default(); 2],
1707            );
1708            let body =
1709                Bytes::from(crate::prom_store::snappy_compress(&request.encode_to_vec()).unwrap());
1710            let mut state = test_state();
1711            state.prom_store_handler = Arc::new(RecordingPromStoreHandler {
1712                events: Default::default(),
1713            });
1714            let response = remote_write_v2(
1715                state,
1716                RemoteWriteQuery::default(),
1717                QueryContext::with("greptime", "public"),
1718                pipeline_info(None),
1719                false,
1720                body,
1721                0,
1722            )
1723            .await
1724            .unwrap();
1725            assert_eq!(response.status(), expected_status);
1726            assert_eq!(
1727                response.headers()[REMOTE_WRITE_V2_SAMPLES_WRITTEN_HEADER],
1728                expected_count
1729            );
1730            assert_eq!(
1731                response.headers()[REMOTE_WRITE_V2_HISTOGRAMS_WRITTEN_HEADER],
1732                "0"
1733            );
1734            assert_eq!(
1735                response.headers()[REMOTE_WRITE_V2_EXEMPLARS_WRITTEN_HEADER],
1736                "0"
1737            );
1738        }
1739    }
1740
1741    struct ExemplarMemoryHandler {
1742        limiter: ServerMemoryLimiter,
1743        progress: Mutex<Option<Arc<session::write_progress::WriteProgress>>>,
1744    }
1745
1746    #[async_trait]
1747    impl PromStoreProtocolHandler for ExemplarMemoryHandler {
1748        async fn pre_write(&self, _: &RowInsertRequests, _: QueryContextRef) -> Result<()> {
1749            unreachable!()
1750        }
1751
1752        async fn pre_write_exemplars(
1753            &self,
1754            exemplars: &operator::insert::ExemplarBatch,
1755            _: QueryContextRef,
1756        ) -> Result<()> {
1757            let estimated =
1758                crate::exemplar::estimated_row_bytes(std::iter::once(exemplars.exemplars()))
1759                    .unwrap();
1760            assert!(self.limiter.used_bytes() >= estimated as u64);
1761            Ok(())
1762        }
1763
1764        async fn write_exemplars_prepared(
1765            &self,
1766            exemplars: operator::insert::ExemplarBatch,
1767            ctx: QueryContextRef,
1768        ) -> Result<Output> {
1769            *self.progress.lock().unwrap() = Some(ctx.write_progress().unwrap().clone());
1770            Ok(Output::new_with_affected_rows(exemplars.len()))
1771        }
1772
1773        async fn write_prepared(
1774            &self,
1775            _: RowInsertRequests,
1776            _: QueryContextRef,
1777            _: bool,
1778        ) -> Result<Output> {
1779            unreachable!()
1780        }
1781
1782        async fn write(&self, _: RowInsertRequests, _: QueryContextRef, _: bool) -> Result<Output> {
1783            unreachable!()
1784        }
1785
1786        async fn write_all(&self, _: Vec<PromWriteBatch>, _: bool) -> Result<Vec<Result<Output>>> {
1787            unreachable!()
1788        }
1789
1790        async fn read(&self, _: ReadRequest, _: QueryContextRef) -> Result<PromStoreResponse> {
1791            unreachable!()
1792        }
1793    }
1794
1795    #[tokio::test]
1796    async fn test_v1_exemplar_shared_series_expansion_is_charged() {
1797        use api::prom_store::remote;
1798
1799        use crate::http::{HttpOptions, HttpServerBuilder};
1800
1801        for large_field in ["__name__", "host"] {
1802            for count in [128, 1] {
1803                let request = remote::WriteRequest {
1804                    timeseries: vec![remote::TimeSeries {
1805                        labels: ["__name__", "host"]
1806                            .into_iter()
1807                            .map(|name| remote::Label {
1808                                name: name.into(),
1809                                value: if name == large_field {
1810                                    "x".repeat(64 * 1024)
1811                                } else {
1812                                    "metric".into()
1813                                },
1814                            })
1815                            .collect(),
1816                        exemplars: vec![remote::Exemplar::default(); count],
1817                        ..Default::default()
1818                    }],
1819                    ..Default::default()
1820                };
1821                let limiter = ServerMemoryLimiter::new(1024 * 1024, OnExhaustedPolicy::Fail);
1822                let handler = Arc::new(ExemplarMemoryHandler {
1823                    limiter: limiter.clone(),
1824                    progress: Mutex::new(None),
1825                });
1826                let server = HttpServerBuilder::new(HttpOptions::default())
1827                    .with_memory_limiter(limiter.clone())
1828                    .with_prom_handler(
1829                        handler.clone(),
1830                        None,
1831                        true,
1832                        PromValidationMode::Strict,
1833                        None,
1834                    )
1835                    .build();
1836                let response = server
1837                    .build(server.make_app())
1838                    .unwrap()
1839                    .oneshot(
1840                        Request::post("/v1/prometheus/write")
1841                            .header(header::CONTENT_TYPE, "application/x-protobuf")
1842                            .header(header::CONTENT_ENCODING, DEFAULT_ENCODING)
1843                            .body(Body::from(
1844                                crate::prom_store::snappy_compress(&request.encode_to_vec())
1845                                    .unwrap(),
1846                            ))
1847                            .unwrap(),
1848                    )
1849                    .await
1850                    .unwrap();
1851                let progress = handler.progress.lock().unwrap().take();
1852                if count == 1 {
1853                    assert_eq!(response.status(), StatusCode::NO_CONTENT);
1854                    assert!(progress.is_some());
1855                    assert!(limiter.used_bytes() >= 64 * 1024);
1856                } else {
1857                    assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
1858                    assert!(progress.is_none());
1859                }
1860                drop(progress);
1861                assert_eq!(limiter.used_bytes(), 0);
1862            }
1863        }
1864    }
1865
1866    #[tokio::test(start_paused = true)]
1867    async fn test_exemplar_v1_concurrent_body_reservations() {
1868        use api::prom_store::remote;
1869
1870        use crate::http::{HttpOptions, HttpServerBuilder};
1871
1872        let wire = remote::WriteRequest {
1873            timeseries: vec![remote::TimeSeries {
1874                labels: vec![
1875                    remote::Label {
1876                        name: "__name__".into(),
1877                        value: "metric".into(),
1878                    },
1879                    remote::Label {
1880                        name: "job".into(),
1881                        value: "api".into(),
1882                    },
1883                ],
1884                exemplars: vec![remote::Exemplar::default()],
1885                ..Default::default()
1886            }],
1887            ..Default::default()
1888        }
1889        .encode_to_vec();
1890        let body = Bytes::from(crate::prom_store::snappy_compress(&wire).unwrap());
1891        let body_length = body.len();
1892        let request = |body: Body| {
1893            Request::post("/v1/prometheus/write")
1894                .header(header::CONTENT_TYPE, "application/x-protobuf")
1895                .header(header::CONTENT_ENCODING, DEFAULT_ENCODING)
1896                .header(header::CONTENT_LENGTH, body_length)
1897                .body(body)
1898                .unwrap()
1899        };
1900
1901        for policy in [OnExhaustedPolicy::default(), OnExhaustedPolicy::Fail] {
1902            // Each request fits alone: 1 KiB for its body and 5 KiB for exemplar rows.
1903            let limiter = ServerMemoryLimiter::new(6 * 1024, policy);
1904            let handler = Arc::new(ExemplarMemoryHandler {
1905                limiter: limiter.clone(),
1906                progress: Mutex::new(None),
1907            });
1908            let server = HttpServerBuilder::new(HttpOptions::default())
1909                .with_memory_limiter(limiter.clone())
1910                .with_prom_handler(
1911                    handler.clone(),
1912                    None,
1913                    true,
1914                    PromValidationMode::Strict,
1915                    None,
1916                )
1917                .build();
1918            let app = server.build(server.make_app()).unwrap();
1919            let single = app
1920                .clone()
1921                .oneshot(request(Body::from(body.clone())))
1922                .await
1923                .unwrap();
1924            assert_eq!(single.status(), StatusCode::NO_CONTENT);
1925            drop(handler.progress.lock().unwrap().take());
1926            assert_eq!(limiter.used_bytes(), 0);
1927
1928            let (send_body, receive_body) = tokio::sync::oneshot::channel();
1929            let delayed_body = body.clone();
1930            let mut second = Box::pin(app.clone().oneshot(request(Body::from_stream(
1931                futures::stream::once(async move {
1932                    receive_body.await.unwrap();
1933                    Ok::<_, std::io::Error>(delayed_body)
1934                }),
1935            ))));
1936            assert!(futures::poll!(second.as_mut()).is_pending());
1937            assert_eq!(limiter.used_bytes(), 1024);
1938
1939            let started = tokio::time::Instant::now();
1940            let mut first = Box::pin(app.clone().oneshot(request(Body::from(body.clone()))));
1941            let first_poll = futures::poll!(first.as_mut());
1942            assert!(handler.progress.lock().unwrap().is_none());
1943            send_body.send(()).unwrap();
1944            let (first, second) = match first_poll {
1945                std::task::Poll::Ready(first) => (first, second.await),
1946                std::task::Poll::Pending => futures::join!(first, second),
1947            };
1948            assert_eq!(
1949                first.unwrap().status(),
1950                match policy {
1951                    OnExhaustedPolicy::Wait { .. } => StatusCode::INTERNAL_SERVER_ERROR,
1952                    OnExhaustedPolicy::Fail => StatusCode::TOO_MANY_REQUESTS,
1953                }
1954            );
1955            assert_eq!(second.unwrap().status(), StatusCode::NO_CONTENT);
1956            assert_eq!(started.elapsed(), Duration::ZERO);
1957            assert!(handler.progress.lock().unwrap().take().is_some());
1958            assert_eq!(limiter.used_bytes(), 0);
1959
1960            let retry = app
1961                .oneshot(request(Body::from(body.clone())))
1962                .await
1963                .unwrap();
1964            assert_eq!(retry.status(), StatusCode::NO_CONTENT);
1965            assert!(handler.progress.lock().unwrap().take().is_some());
1966            assert_eq!(limiter.used_bytes(), 0);
1967        }
1968    }
1969
1970    #[tokio::test(start_paused = true)]
1971    async fn test_exemplar_row_memory_is_charged_and_retained() {
1972        use api::greptime_proto::io::prometheus::write::v2;
1973        use api::prom_store::remote;
1974
1975        use crate::http::{HttpOptions, HttpServerBuilder};
1976
1977        for (version, holds_body) in [(1, false), (1, true), (2, true)] {
1978            for policy in [OnExhaustedPolicy::Fail, OnExhaustedPolicy::default()] {
1979                for (distinct_tags, contended, expire) in [
1980                    (true, false, false),
1981                    (false, false, false),
1982                    (false, true, false),
1983                    (false, true, true),
1984                ] {
1985                    let mut v1 = remote::WriteRequest::default();
1986                    let mut v2 = v2::Request {
1987                        symbols: vec![String::new()],
1988                        timeseries: vec![],
1989                    };
1990                    for index in 0..1024 {
1991                        let labels = vec![
1992                            remote::Label {
1993                                name: "__name__".into(),
1994                                value: format!("metric_{index}"),
1995                            },
1996                            remote::Label {
1997                                name: format!("tag_{}", if distinct_tags { index } else { 0 }),
1998                                value: "value".into(),
1999                            },
2000                        ];
2001                        let mut labels_refs = Vec::new();
2002                        for label in &labels {
2003                            labels_refs
2004                                .extend([v2.symbols.len() as u32, v2.symbols.len() as u32 + 1]);
2005                            v2.symbols.extend([label.name.clone(), label.value.clone()]);
2006                        }
2007                        v1.timeseries.push(remote::TimeSeries {
2008                            labels,
2009                            samples: if expire {
2010                                vec![remote::Sample::default()]
2011                            } else {
2012                                vec![]
2013                            },
2014                            exemplars: vec![remote::Exemplar::default()],
2015                            ..Default::default()
2016                        });
2017                        v2.timeseries.push(v2::TimeSeries {
2018                            labels_refs,
2019                            samples: if expire {
2020                                vec![v2::Sample::default()]
2021                            } else {
2022                                vec![]
2023                            },
2024                            exemplars: vec![v2::Exemplar::default()],
2025                            ..Default::default()
2026                        });
2027                    }
2028                    let (content_type, wire) = if version == 1 {
2029                        ("application/x-protobuf", v1.encode_to_vec())
2030                    } else {
2031                        (
2032                            "application/x-protobuf;proto=io.prometheus.write.v2.Request",
2033                            v2.encode_to_vec(),
2034                        )
2035                    };
2036                    let limiter = ServerMemoryLimiter::new(16 * 1024 * 1024, policy);
2037                    let mut occupied = contended
2038                        .then(|| limiter.try_acquire(16 * 1024 * 1024 - 256 * 1024).unwrap());
2039                    let handler = Arc::new(ExemplarMemoryHandler {
2040                        limiter: limiter.clone(),
2041                        progress: Mutex::new(None),
2042                    });
2043                    let server = HttpServerBuilder::new(HttpOptions::default())
2044                        .with_memory_limiter(limiter.clone())
2045                        .with_prom_handler(
2046                            handler.clone(),
2047                            None,
2048                            true,
2049                            PromValidationMode::Strict,
2050                            None,
2051                        )
2052                        .build();
2053                    let app = if holds_body {
2054                        server.build(server.make_app()).unwrap()
2055                    } else {
2056                        // Exercise waiting without transport-owned permits.
2057                        server
2058                            .make_app()
2059                            .layer(Extension(QueryContext::with("greptime", "public")))
2060                    };
2061                    let response = app.oneshot(
2062                        Request::post("/v1/prometheus/write")
2063                            .header(header::CONTENT_TYPE, content_type)
2064                            .header(header::CONTENT_ENCODING, DEFAULT_ENCODING)
2065                            .body(Body::from(
2066                                crate::prom_store::snappy_compress(&wire).unwrap(),
2067                            ))
2068                            .unwrap(),
2069                    );
2070                    let started = tokio::time::Instant::now();
2071                    tokio::pin!(response);
2072                    let fail_fast = version == 1
2073                        && holds_body
2074                        && contended
2075                        && matches!(policy, OnExhaustedPolicy::Wait { .. });
2076                    if contended && matches!(policy, OnExhaustedPolicy::Wait { .. }) && !fail_fast {
2077                        assert!(futures::poll!(response.as_mut()).is_pending());
2078                        if !expire {
2079                            drop(occupied.take());
2080                        }
2081                    }
2082                    let response = response.await.unwrap();
2083                    let timed_out =
2084                        expire && matches!(policy, OnExhaustedPolicy::Wait { .. }) && !fail_fast;
2085                    let rejected = timed_out
2086                        || fail_fast
2087                        || (contended && matches!(policy, OnExhaustedPolicy::Fail));
2088                    assert_eq!(
2089                        response.status(),
2090                        if timed_out || fail_fast {
2091                            StatusCode::INTERNAL_SERVER_ERROR
2092                        } else if rejected {
2093                            StatusCode::TOO_MANY_REQUESTS
2094                        } else {
2095                            StatusCode::NO_CONTENT
2096                        },
2097                        "version={version}, holds_body={holds_body}, distinct={distinct_tags}, contended={contended}, expire={expire}, policy={policy:?}"
2098                    );
2099                    if let OnExhaustedPolicy::Wait { timeout } = policy
2100                        && timed_out
2101                    {
2102                        assert_eq!(started.elapsed(), timeout);
2103                    } else {
2104                        assert_eq!(started.elapsed(), Duration::ZERO);
2105                    }
2106                    let progress = handler.progress.lock().unwrap().take();
2107                    if !rejected {
2108                        assert!(progress.is_some());
2109                        assert!(limiter.used_bytes() > 0);
2110                        if version == 2 {
2111                            assert_eq!(
2112                                response.headers()[REMOTE_WRITE_V2_EXEMPLARS_WRITTEN_HEADER],
2113                                "1024"
2114                            );
2115                        }
2116                    } else {
2117                        assert!(progress.is_none());
2118                    }
2119                    drop(progress);
2120                    assert_eq!(
2121                        limiter.used_bytes(),
2122                        occupied.as_ref().map_or(0, |guard| guard.granted_bytes())
2123                    );
2124                    drop(occupied);
2125                    assert_eq!(limiter.used_bytes(), 0);
2126                }
2127            }
2128        }
2129
2130        // Verify linear row/tag charging still rejects requests exceeding a small quota.
2131        let mut small_req = remote::WriteRequest::default();
2132        for index in 0..1024 {
2133            small_req.timeseries.push(remote::TimeSeries {
2134                labels: vec![
2135                    remote::Label {
2136                        name: "__name__".into(),
2137                        value: format!("metric_{index}"),
2138                    },
2139                    remote::Label {
2140                        name: format!("tag_{index}"),
2141                        value: "value".into(),
2142                    },
2143                ],
2144                exemplars: vec![remote::Exemplar::default()],
2145                ..Default::default()
2146            });
2147        }
2148        let limiter = ServerMemoryLimiter::new(512 * 1024, OnExhaustedPolicy::Fail);
2149        let handler = Arc::new(ExemplarMemoryHandler {
2150            limiter: limiter.clone(),
2151            progress: Mutex::new(None),
2152        });
2153        let server = HttpServerBuilder::new(HttpOptions::default())
2154            .with_memory_limiter(limiter.clone())
2155            .with_prom_handler(
2156                handler.clone(),
2157                None,
2158                true,
2159                PromValidationMode::Strict,
2160                None,
2161            )
2162            .build();
2163        let response = server
2164            .build(server.make_app())
2165            .unwrap()
2166            .oneshot(
2167                Request::post("/v1/prometheus/write")
2168                    .header(header::CONTENT_TYPE, "application/x-protobuf")
2169                    .header(header::CONTENT_ENCODING, DEFAULT_ENCODING)
2170                    .body(Body::from(
2171                        crate::prom_store::snappy_compress(&small_req.encode_to_vec()).unwrap(),
2172                    ))
2173                    .unwrap(),
2174            )
2175            .await
2176            .unwrap();
2177        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
2178        assert!(handler.progress.lock().unwrap().is_none());
2179        assert_eq!(limiter.used_bytes(), 0);
2180    }
2181
2182    fn memory_limited_prom_write_app(limiter: ServerMemoryLimiter) -> Router {
2183        let mut state = test_state();
2184        state.memory_limiter = limiter.clone();
2185        Router::new()
2186            .route("/write", routing::post(remote_write))
2187            .with_state(state)
2188            .layer(Extension(QueryContext::with("greptime", "public")))
2189            .layer(middleware::from_fn_with_state(
2190                limiter,
2191                memory_limit_middleware,
2192            ))
2193    }
2194
2195    #[tokio::test(start_paused = true)]
2196    async fn test_exemplar_v1_reservation_accounts_for_chunked_body() {
2197        use api::prom_store::remote;
2198
2199        let wire = remote::WriteRequest {
2200            timeseries: vec![remote::TimeSeries {
2201                labels: vec![
2202                    remote::Label {
2203                        name: "__name__".into(),
2204                        value: "metric".into(),
2205                    },
2206                    remote::Label {
2207                        name: "job".into(),
2208                        value: "api".into(),
2209                    },
2210                ],
2211                exemplars: vec![remote::Exemplar::default()],
2212                ..Default::default()
2213            }],
2214            ..Default::default()
2215        }
2216        .encode_to_vec();
2217        let body = crate::prom_store::snappy_compress(&wire).unwrap();
2218        // Each frame retains a 1 KiB body permit. The rows fit alone, but not alongside both.
2219        let frames = body
2220            .chunks(body.len().div_ceil(2))
2221            .map(Bytes::copy_from_slice)
2222            .collect::<Vec<_>>();
2223        assert_eq!(frames.len(), 2);
2224        let limiter = ServerMemoryLimiter::new(5 * 1024, OnExhaustedPolicy::default());
2225        let started = tokio::time::Instant::now();
2226        let response = memory_limited_prom_write_app(limiter.clone())
2227            .oneshot(
2228                Request::post("/write")
2229                    .header(header::CONTENT_TYPE, "application/x-protobuf")
2230                    .header(header::CONTENT_ENCODING, DEFAULT_ENCODING)
2231                    .body(Body::from_stream(futures::stream::iter(
2232                        frames.into_iter().map(Ok::<_, std::io::Error>),
2233                    )))
2234                    .unwrap(),
2235            )
2236            .await
2237            .unwrap();
2238        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
2239        assert_eq!(started.elapsed(), Duration::ZERO);
2240        assert_eq!(limiter.used_bytes(), 0);
2241    }
2242
2243    #[tokio::test(start_paused = true)]
2244    async fn test_remote_write_v2_accounts_for_body_when_rejecting_or_waiting() {
2245        let wire = api::greptime_proto::io::prometheus::write::v2::Request {
2246            symbols: vec![
2247                String::new(),
2248                format!("{:?}", (0..2048).collect::<Vec<_>>()),
2249            ],
2250            timeseries: Vec::new(),
2251        }
2252        .encode_to_vec();
2253        let decoded_bytes = wire.len().div_ceil(1024) * 1024;
2254
2255        for encoding in [DEFAULT_ENCODING, VM_ENCODING] {
2256            let body = Bytes::from(if encoding == DEFAULT_ENCODING {
2257                crate::prom_store::snappy_compress(&wire).unwrap()
2258            } else {
2259                zstd::stream::encode_all(wire.as_slice(), 3).unwrap()
2260            });
2261            for chunked in [false, true] {
2262                // Small frames make their rounded permits exceed the rounded total body length.
2263                let chunk_size = if chunked { 513 } else { body.len() };
2264                let frames = body
2265                    .chunks(chunk_size)
2266                    .map(Bytes::copy_from_slice)
2267                    .collect::<Vec<_>>();
2268                let body_reserved: usize =
2269                    frames.iter().map(|f| f.len().div_ceil(1024) * 1024).sum();
2270                if chunked {
2271                    assert!(body_reserved > body.len().div_ceil(1024) * 1024);
2272                }
2273                // Reject during decompression or scratch allocation; otherwise wait for contention.
2274                for decoder_quota in [decoded_bytes - 1024, decoded_bytes, decoded_bytes + 1024] {
2275                    let limit = (body_reserved + decoder_quota) as u64;
2276                    let limiter = ServerMemoryLimiter::new(limit, OnExhaustedPolicy::default());
2277                    let fits = decoder_quota > decoded_bytes;
2278                    let occupied = fits.then(|| limiter.try_acquire(1024).unwrap());
2279                    let app = memory_limited_prom_write_app(limiter.clone());
2280                    let mut request = Request::builder()
2281                        .uri("/write")
2282                        .method("POST")
2283                        .header(
2284                            header::CONTENT_TYPE,
2285                            "application/x-protobuf;proto=io.prometheus.write.v2.Request",
2286                        )
2287                        .header(header::CONTENT_ENCODING, encoding);
2288                    let request_body = if chunked {
2289                        Body::from_stream(futures::stream::iter(
2290                            frames.clone().into_iter().map(Ok::<_, std::io::Error>),
2291                        ))
2292                    } else {
2293                        request = request.header(header::CONTENT_LENGTH, body.len().to_string());
2294                        Body::from(body.clone())
2295                    };
2296                    let started = tokio::time::Instant::now();
2297                    let response = app.oneshot(request.body(request_body).unwrap());
2298                    tokio::pin!(response);
2299                    if let Some(occupied) = occupied {
2300                        assert!(futures::poll!(response.as_mut()).is_pending());
2301                        // A failed attempt releases decoder permits, retaining only the HTTP body.
2302                        assert_eq!(limiter.used_bytes(), body_reserved as u64 + 1024);
2303                        drop(occupied);
2304                    }
2305                    let response = response.await.unwrap();
2306                    assert_eq!(
2307                        response.status(),
2308                        if fits {
2309                            StatusCode::NO_CONTENT
2310                        } else {
2311                            StatusCode::TOO_MANY_REQUESTS
2312                        },
2313                        "encoding={encoding}, chunked={chunked}, decoder_quota={decoder_quota}"
2314                    );
2315                    assert_eq!(started.elapsed(), Duration::ZERO);
2316                    assert_eq!(
2317                        response.headers()[REMOTE_WRITE_V2_SAMPLES_WRITTEN_HEADER],
2318                        "0"
2319                    );
2320                    assert_eq!(limiter.used_bytes(), 0);
2321                }
2322            }
2323        }
2324    }
2325
2326    #[tokio::test]
2327    async fn test_remote_write_v2_ignores_pipeline() {
2328        let request = api::greptime_proto::io::prometheus::write::v2::Request {
2329            symbols: vec![String::new()],
2330            timeseries: Vec::new(),
2331        };
2332        let body =
2333            Bytes::from(crate::prom_store::snappy_compress(&request.encode_to_vec()).unwrap());
2334
2335        let response = remote_write_v2(
2336            test_state(),
2337            RemoteWriteQuery::default(),
2338            QueryContext::with("greptime", "public"),
2339            pipeline_info(Some("pipeline")),
2340            false,
2341            body,
2342            0,
2343        )
2344        .await
2345        .unwrap();
2346
2347        assert_eq!(response.status(), StatusCode::NO_CONTENT);
2348        assert_eq!(
2349            Some("0"),
2350            response
2351                .headers()
2352                .get(REMOTE_WRITE_V2_SAMPLES_WRITTEN_HEADER)
2353                .map(|x| x.to_str().unwrap())
2354        );
2355    }
2356
2357    fn test_state() -> PromStoreState {
2358        PromStoreState {
2359            prom_store_handler: Arc::new(NoopPromStoreHandler),
2360            pipeline_handler: None,
2361            prom_store_with_metric_engine: false,
2362            prom_validation_mode: PromValidationMode::Strict,
2363            pending_rows_batcher: None,
2364            memory_limiter: ServerMemoryLimiter::default(),
2365        }
2366    }
2367
2368    fn pipeline_info(pipeline_name: Option<&str>) -> PipelineInfo {
2369        PipelineInfo {
2370            pipeline_name: pipeline_name.map(ToString::to_string),
2371            pipeline_version: None,
2372            pipeline_params: GreptimePipelineParams::default(),
2373        }
2374    }
2375
2376    struct NoopPromStoreHandler;
2377
2378    #[async_trait]
2379    impl PromStoreProtocolHandler for NoopPromStoreHandler {
2380        async fn pre_write(
2381            &self,
2382            _request: &RowInsertRequests,
2383            _ctx: QueryContextRef,
2384        ) -> Result<()> {
2385            Ok(())
2386        }
2387
2388        async fn write_prepared(
2389            &self,
2390            _request: RowInsertRequests,
2391            _ctx: QueryContextRef,
2392            _with_metric_engine: bool,
2393        ) -> Result<Output> {
2394            unreachable!("empty remote write v2 request should not write")
2395        }
2396
2397        async fn write(
2398            &self,
2399            _request: RowInsertRequests,
2400            _ctx: QueryContextRef,
2401            _with_metric_engine: bool,
2402        ) -> Result<Output> {
2403            unreachable!("empty remote write v2 request should not write")
2404        }
2405
2406        async fn write_all(
2407            &self,
2408            requests: Vec<(QueryContextRef, RowInsertRequests)>,
2409            _with_metric_engine: bool,
2410        ) -> Result<Vec<Result<Output>>> {
2411            assert!(requests.is_empty());
2412            Ok(Vec::new())
2413        }
2414
2415        async fn read(
2416            &self,
2417            _request: ReadRequest,
2418            _ctx: QueryContextRef,
2419        ) -> Result<PromStoreResponse> {
2420            unimplemented!()
2421        }
2422    }
2423}