1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use std::fmt;

use vector_lib::byte_size_of::ByteSizeOf;
use vector_lib::event::Metric;
use vector_lib::stream::batcher::{data::BatchData, limiter::ByteSizeOfItemSize};

use crate::sinks::{prelude::*, util::buffer::metrics::MetricSet};

use super::{
    request_builder::{RemoteWriteEncoder, RemoteWriteRequest, RemoteWriteRequestBuilder},
    PartitionKey, PrometheusMetricNormalize,
};

pub(super) struct RemoteWriteMetric {
    pub(super) metric: Metric,
    tenant_id: Option<String>,
}

impl Finalizable for RemoteWriteMetric {
    fn take_finalizers(&mut self) -> EventFinalizers {
        self.metric.take_finalizers()
    }
}

impl GetEventCountTags for RemoteWriteMetric {
    fn get_tags(&self) -> TaggedEventsSent {
        self.metric.get_tags()
    }
}

impl EstimatedJsonEncodedSizeOf for RemoteWriteMetric {
    fn estimated_json_encoded_size_of(&self) -> JsonSize {
        self.metric.estimated_json_encoded_size_of()
    }
}

impl ByteSizeOf for RemoteWriteMetric {
    fn allocated_bytes(&self) -> usize {
        self.metric.allocated_bytes()
    }
}

#[derive(Clone, Copy, Debug, Default)]
pub struct PrometheusRemoteWriteDefaultBatchSettings;

impl SinkBatchSettings for PrometheusRemoteWriteDefaultBatchSettings {
    const MAX_EVENTS: Option<usize> = Some(1_000);
    const MAX_BYTES: Option<usize> = None;
    const TIMEOUT_SECS: f64 = 1.0;
}

pub(super) struct PrometheusTenantIdPartitioner;

impl Partitioner for PrometheusTenantIdPartitioner {
    type Item = RemoteWriteMetric;
    type Key = PartitionKey;

    fn partition(&self, item: &Self::Item) -> Self::Key {
        PartitionKey {
            tenant_id: item.tenant_id.clone(),
        }
    }
}

pub(super) enum BatchedMetrics {
    Aggregated(MetricSet),
    Unaggregated(Vec<Metric>),
}

impl BatchedMetrics {
    pub(super) fn into_metrics(self) -> Vec<Metric> {
        match self {
            BatchedMetrics::Aggregated(metrics) => metrics.into_metrics(),
            BatchedMetrics::Unaggregated(metrics) => metrics,
        }
    }

    pub(super) fn insert_update(&mut self, metric: Metric) {
        match self {
            BatchedMetrics::Aggregated(metrics) => metrics.insert_update(metric),
            BatchedMetrics::Unaggregated(metrics) => metrics.push(metric),
        }
    }

    pub(super) fn len(&self) -> usize {
        match self {
            BatchedMetrics::Aggregated(metrics) => metrics.len(),
            BatchedMetrics::Unaggregated(metrics) => metrics.len(),
        }
    }
}

pub(super) struct EventCollection {
    pub(super) finalizers: EventFinalizers,
    pub(super) events: BatchedMetrics,
    pub(super) events_byte_size: usize,
    pub(super) events_json_byte_size: GroupedCountByteSize,
}

impl EventCollection {
    /// Creates a new event collection that will either aggregate the incremental metrics
    /// or store all the metrics, depending on the value of the `aggregate` parameter.
    fn new(aggregate: bool) -> Self {
        Self {
            finalizers: Default::default(),
            events: if aggregate {
                BatchedMetrics::Aggregated(Default::default())
            } else {
                BatchedMetrics::Unaggregated(Default::default())
            },
            events_byte_size: Default::default(),
            events_json_byte_size: telemetry().create_request_count_byte_size(),
        }
    }

    const fn is_aggregated(&self) -> bool {
        matches!(self.events, BatchedMetrics::Aggregated(_))
    }
}

impl BatchData<RemoteWriteMetric> for EventCollection {
    type Batch = Self;

    fn len(&self) -> usize {
        self.events.len()
    }

    fn take_batch(&mut self) -> Self::Batch {
        let mut new = Self::new(self.is_aggregated());
        std::mem::swap(self, &mut new);
        new
    }

    fn push_item(&mut self, mut item: RemoteWriteMetric) {
        self.finalizers
            .merge(item.metric.metadata_mut().take_finalizers());
        self.events_byte_size += item.size_of();
        self.events_json_byte_size
            .add_event(&item.metric, item.estimated_json_encoded_size_of());
        self.events.insert_update(item.metric);
    }
}

pub(super) struct RemoteWriteSink<S> {
    pub(super) tenant_id: Option<Template>,
    pub(super) batch_settings: BatcherSettings,
    pub(super) aggregate: bool,
    pub(super) compression: super::Compression,
    pub(super) default_namespace: Option<String>,
    pub(super) buckets: Vec<f64>,
    pub(super) quantiles: Vec<f64>,
    pub(super) service: S,
}

impl<S> RemoteWriteSink<S>
where
    S: Service<RemoteWriteRequest> + Send + 'static,
    S::Future: Send + 'static,
    S::Response: DriverResponse + Send + 'static,
    S::Error: fmt::Debug + Into<crate::Error> + Send,
{
    async fn run_inner(self: Box<Self>, input: BoxStream<'_, Event>) -> Result<(), ()> {
        let request_builder = RemoteWriteRequestBuilder {
            compression: self.compression,
            encoder: RemoteWriteEncoder {
                default_namespace: self.default_namespace.clone(),
                buckets: self.buckets.clone(),
                quantiles: self.quantiles.clone(),
            },
        };

        let batch_settings = self.batch_settings;
        let tenant_id = self.tenant_id.clone();
        let service = self.service;

        input
            .filter_map(|event| future::ready(event.try_into_metric()))
            .normalized_with_default::<PrometheusMetricNormalize>()
            .filter_map(move |event| {
                future::ready(make_remote_write_event(tenant_id.as_ref(), event))
            })
            .batched_partitioned(PrometheusTenantIdPartitioner, || {
                batch_settings
                    .as_reducer_config(ByteSizeOfItemSize, EventCollection::new(self.aggregate))
            })
            .request_builder(default_request_builder_concurrency_limit(), request_builder)
            .filter_map(|request| async move {
                match request {
                    Err(e) => {
                        error!("Failed to build Remote Write request: {:?}.", e);
                        None
                    }
                    Ok(req) => Some(req),
                }
            })
            .into_driver(service)
            .run()
            .await
    }
}

#[async_trait]
impl<S> StreamSink<Event> for RemoteWriteSink<S>
where
    S: Service<RemoteWriteRequest> + Send + 'static,
    S::Future: Send + 'static,
    S::Response: DriverResponse + Send + 'static,
    S::Error: fmt::Debug + Into<crate::Error> + Send,
{
    async fn run(self: Box<Self>, input: BoxStream<'_, Event>) -> Result<(), ()> {
        self.run_inner(input).await
    }
}

fn make_remote_write_event(
    tenant_id: Option<&Template>,
    metric: Metric,
) -> Option<RemoteWriteMetric> {
    let tenant_id = tenant_id.and_then(|template| {
        template
            .render_string(&metric)
            .map_err(|error| {
                emit!(TemplateRenderingError {
                    error,
                    field: Some("tenant_id"),
                    drop_event: true,
                })
            })
            .ok()
    });

    Some(RemoteWriteMetric { metric, tenant_id })
}