Repository navigation
Expand file tree
/
Copy pathbatch.rs
More file actions
270 lines (242 loc) · 7.5 KB
/
Copy pathbatch.rs
File metadata and controls
270 lines (242 loc) · 7.5 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
use derivative::Derivative;
use serde::{Deserialize, Serialize};
use snafu::Snafu;
use std::marker::PhantomData;
use std::time::Duration;
#[derive(Debug, Snafu)]
pub enum BatchError {
#[snafu(display("Cannot configure both `max_bytes` and `max_size`"))]
BytesAndSize,
#[snafu(display("Cannot configure both `max_events` and `max_size`"))]
EventsAndSize,
#[snafu(display("This sink does not allow setting `max_bytes`"))]
BytesNotAllowed,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
pub struct BatchConfig {
pub max_bytes: Option<usize>,
pub max_events: Option<usize>,
/// Deprecated. Left in for backwards compatibility, use `max_bytes`
/// or `max_events` instead.
pub max_size: Option<usize>,
pub timeout_secs: Option<u64>,
}
impl BatchConfig {
// This is used internally by new_relic_logs sink, else it could be pub(super) too
pub fn use_size_as_bytes(&self) -> Result<Self, BatchError> {
let max_bytes = match (self.max_bytes, self.max_size) {
(Some(_), Some(_)) => return Err(BatchError::BytesAndSize),
(Some(bytes), None) => Some(bytes),
(None, Some(size)) => Some(size),
(None, None) => None,
};
Ok(Self {
max_bytes,
max_size: None,
..*self
})
}
pub(super) fn disallow_max_bytes(&self) -> Result<Self, BatchError> {
// Sinks that used `max_size` for an event count cannot count
// bytes, so err if `max_bytes` is set.
match self.max_bytes {
Some(_) => Err(BatchError::BytesNotAllowed),
None => Ok(*self),
}
}
pub(super) fn use_size_as_events(&self) -> Result<Self, BatchError> {
let max_events = match (self.max_events, self.max_size) {
(Some(_), Some(_)) => return Err(BatchError::EventsAndSize),
(Some(events), None) => Some(events),
(None, Some(size)) => Some(size),
(None, None) => None,
};
Ok(Self {
max_events,
max_size: None,
..*self
})
}
pub(super) fn get_settings_or_default<T>(
&self,
defaults: BatchSettings<T>,
) -> BatchSettings<T> {
BatchSettings {
size: BatchSize {
bytes: self.max_bytes.unwrap_or(defaults.size.bytes),
events: self.max_events.unwrap_or(defaults.size.events),
..Default::default()
},
timeout: self
.timeout_secs
.map(Duration::from_secs)
.unwrap_or(defaults.timeout),
}
}
}
#[derive(Debug, Derivative)]
#[derivative(Clone(bound = ""))]
#[derivative(Copy(bound = ""))]
#[derivative(Default(bound = ""))]
pub struct BatchSize<B> {
#[derivative(Default(value = "usize::max_value()"))]
pub bytes: usize,
#[derivative(Default(value = "usize::max_value()"))]
pub events: usize,
// This type marker is used to drive type inference, which allows us
// to call the right Batch::get_settings_defaults without explicitly
// naming the type in BatchSettings::parse_config.
_type_marker: PhantomData<B>,
}
#[derive(Debug, Derivative)]
#[derivative(Clone(bound = ""))]
#[derivative(Copy(bound = ""))]
#[derivative(Default(bound = ""))]
pub struct BatchSettings<B> {
pub size: BatchSize<B>,
pub timeout: Duration,
}
impl<B: Batch> BatchSettings<B> {
pub fn parse_config(self, config: BatchConfig) -> Result<Self, BatchError> {
B::get_settings_defaults(config, self)
}
}
impl<B> BatchSettings<B> {
// Fake the builder pattern
pub const fn bytes(self, bytes: u64) -> Self {
Self {
size: BatchSize {
bytes: bytes as usize,
..self.size
},
..self
}
}
pub const fn events(self, events: usize) -> Self {
Self {
size: BatchSize {
events,
..self.size
},
..self
}
}
pub const fn timeout(self, secs: u64) -> Self {
Self {
timeout: Duration::from_secs(secs),
..self
}
}
// Would like to use `trait From` here, but that results in
// "conflicting implementations of trait"
pub const fn into<B2>(self) -> BatchSettings<B2> {
BatchSettings {
size: BatchSize {
bytes: self.size.bytes,
events: self.size.events,
_type_marker: PhantomData,
},
timeout: self.timeout,
}
}
}
pub(super) fn err_event_too_large<T>(length: usize) -> PushResult<T> {
error!(message = "Event larger than batch size, dropping.", length = %length, rate_limit_secs = 1);
PushResult::Ok(false)
}
/// This enum provides the result of a push operation, indicating if the
/// event was added and the fullness state of the buffer.
#[must_use]
#[derive(Debug, Eq, PartialEq)]
pub enum PushResult<T> {
/// Event was added, with an indicator if the buffer is now full
Ok(bool),
/// Event could not be added because it would overflow the
/// buffer. Since push takes ownership of the event, it must be
/// returned here.
Overflow(T),
}
pub trait Batch: Sized {
type Input;
type Output;
/// Turn the batch configuration into an actualized set of settings,
/// and deal with the proper behavior of `max_size` and if
/// `max_bytes` may be set. This is in the trait to ensure all batch
/// buffers implement it.
fn get_settings_defaults(
_config: BatchConfig,
_defaults: BatchSettings<Self>,
) -> Result<BatchSettings<Self>, BatchError>;
fn push(&mut self, item: Self::Input) -> PushResult<Self::Input>;
fn is_empty(&self) -> bool;
fn fresh(&self) -> Self;
fn finish(self) -> Self::Output;
fn num_items(&self) -> usize;
/// Replace the current batch with a fresh one, returning the old one.
fn fresh_replace(&mut self) -> Self
where
Self: Sized,
{
let fresh = self.fresh();
std::mem::replace(self, fresh)
}
}
#[derive(Clone, Debug)]
pub struct StatefulBatch<B> {
inner: B,
was_full: bool,
}
impl<B> From<B> for StatefulBatch<B> {
fn from(inner: B) -> Self {
Self {
inner,
was_full: false,
}
}
}
impl<B> StatefulBatch<B> {
pub fn was_full(&self) -> bool {
self.was_full
}
pub fn into_inner(self) -> B {
self.inner
}
}
impl<B> Batch for StatefulBatch<B>
where
B: Batch,
{
type Input = B::Input;
type Output = B::Output;
fn get_settings_defaults(
config: BatchConfig,
defaults: BatchSettings<Self>,
) -> Result<BatchSettings<Self>, BatchError> {
Ok(B::get_settings_defaults(config, defaults.into())?.into())
}
fn push(&mut self, item: Self::Input) ->
49D8
PushResult<Self::Input> {
if self.was_full {
PushResult::Overflow(item)
} else {
let result = self.inner.push(item);
self.was_full =
matches!(result, PushResult::Overflow(_)) || matches!(result, PushResult::Ok(true));
result
}
}
fn is_empty(&self) -> bool {
!self.was_full && self.inner.is_empty()
}
fn fresh(&self) -> Self {
Self {
inner: self.inner.fresh(),
was_full: false,
}
}
fn finish(self) -> Self::Output {
self.inner.finish()
}
fn num_items(&self) -> usize {
self.inner.num_items()
}
}