forked from shotover/shotover-proxy
/
chain.rs
382 lines (334 loc) · 12.9 KB
/
chain.rs
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use crate::error::ChainResponse;
use crate::message::Messages;
use crate::transforms::{Transforms, Wrapper};
use anyhow::{anyhow, Result};
use derivative::Derivative;
use futures::TryFutureExt;
use itertools::Itertools;
use metrics::{histogram, register_counter, register_histogram, Counter};
use std::net::SocketAddr;
use tokio::sync::{mpsc, oneshot};
use tokio::time::{Duration, Instant};
use tracing::{debug, error, info, trace, Instrument};
type InnerChain = Vec<Transforms>;
#[derive(Debug)]
pub struct BufferedChainMessages {
pub local_addr: SocketAddr,
pub messages: Messages,
pub flush: bool,
pub return_chan: Option<oneshot::Sender<crate::error::ChainResponse>>,
}
impl BufferedChainMessages {
pub fn new_with_no_return(m: Messages, local_addr: SocketAddr) -> Self {
BufferedChainMessages {
local_addr,
messages: m,
flush: false,
return_chan: None,
}
}
pub fn new(
m: Messages,
local_addr: SocketAddr,
flush: bool,
return_chan: oneshot::Sender<ChainResponse>,
) -> Self {
BufferedChainMessages {
local_addr,
messages: m,
flush,
return_chan: Some(return_chan),
}
}
}
//TODO explore running the transform chain on a LocalSet for better locality to a given OS thread
//Will also mean we can have `!Send` types in our transform chain
/// A transform chain is a ordered list of transforms that a message will pass through.
/// Transform chains can be of arbitary complexity and a transform can even have its own set of child transform chains.
/// Transform chains are defined by the user in Shotover's configuration file and are linked to sources.
///
/// The transform chain is a vector of mutable references to the enum [Transforms] (which is an enum dispatch wrapper around the various transform types).
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct TransformChain {
pub name: String,
pub chain: InnerChain,
#[derivative(Debug = "ignore")]
chain_total: Counter,
#[derivative(Debug = "ignore")]
chain_failures: Counter,
}
#[derive(Debug, Clone)]
pub struct BufferedChain {
pub original_chain: TransformChain,
send_handle: mpsc::Sender<BufferedChainMessages>,
#[cfg(test)]
pub count: std::sync::Arc<std::sync::atomic::AtomicU64>,
}
impl BufferedChain {
#[must_use]
pub fn to_new_instance(&self, buffer_size: usize) -> Self {
self.original_chain.clone().into_buffered_chain(buffer_size)
}
pub async fn process_request(
&mut self,
wrapper: Wrapper<'_>,
buffer_timeout_micros: Option<u64>,
) -> ChainResponse {
self.process_request_with_receiver(wrapper, buffer_timeout_micros)
.await?
.await?
}
async fn process_request_with_receiver(
&mut self,
wrapper: Wrapper<'_>,
buffer_timeout_micros: Option<u64>,
) -> Result<oneshot::Receiver<ChainResponse>> {
let (one_tx, one_rx) = oneshot::channel::<ChainResponse>();
match buffer_timeout_micros {
None => {
self.send_handle
.send(BufferedChainMessages::new(
wrapper.messages,
wrapper.local_addr,
wrapper.flush,
one_tx,
))
.map_err(|e| anyhow!("Couldn't send message to wrapped chain {:?}", e))
.await?
}
Some(timeout) => {
self.send_handle
.send_timeout(
BufferedChainMessages::new(
wrapper.messages,
wrapper.local_addr,
wrapper.flush,
one_tx,
),
Duration::from_micros(timeout),
)
.map_err(|e| anyhow!("Couldn't send message to wrapped chain {:?}", e))
.await?
}
}
Ok(one_rx)
}
pub async fn process_request_no_return(
&mut self,
wrapper: Wrapper<'_>,
buffer_timeout_micros: Option<u64>,
) -> Result<()> {
if wrapper.flush {
// To obey flush request we need to ensure messages have completed sending before returning.
// In order to achieve that we need to use the regular process_request method.
self.process_request(wrapper, buffer_timeout_micros).await?;
} else {
// When there is no flush we can return much earlier by not waiting for a response.
match buffer_timeout_micros {
None => {
self.send_handle
.send(BufferedChainMessages::new_with_no_return(
wrapper.messages,
wrapper.local_addr,
))
.map_err(|e| anyhow!("Couldn't send message to wrapped chain {:?}", e))
.await?
}
Some(timeout) => {
self.send_handle
.send_timeout(
BufferedChainMessages::new_with_no_return(
wrapper.messages,
wrapper.local_addr,
),
Duration::from_micros(timeout),
)
.map_err(|e| anyhow!("Couldn't send message to wrapped chain {:?}", e))
.await?
}
}
}
Ok(())
}
}
impl TransformChain {
pub fn into_buffered_chain(self, buffer_size: usize) -> BufferedChain {
let (tx, mut rx) = mpsc::channel::<BufferedChainMessages>(buffer_size);
#[cfg(test)]
let count = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
#[cfg(test)]
let count_clone = count.clone();
// Even though we don't keep the join handle, this thread will wrap up once all corresponding senders have been dropped.
let mut chain = self.clone();
let _jh = tokio::spawn(
async move {
while let Some(BufferedChainMessages {
local_addr,
return_chan,
messages,
flush,
}) = rx.recv().await
{
#[cfg(test)]
{
count_clone.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
let mut wrapper = Wrapper::new_with_chain_name(messages, chain.name.clone(), local_addr);
wrapper.flush = flush;
let chain_response = chain.process_request(wrapper, chain.name.clone()).await;
if let Err(e) = &chain_response {
error!("Internal error in buffered chain: {e:?}");
};
match return_chan {
None => trace!("Ignoring response due to lack of return chan"),
Some(tx) => {
if let Err(message) = tx.send(chain_response) {
trace!("Failed to send response message over return chan. Message was: {message:?}");
}
}
};
}
debug!("buffered chain processing thread exiting, stopping chain loop and dropping");
match chain
.process_request(
Wrapper::flush_with_chain_name(chain.name.clone()),
"".into(),
)
.await
{
Ok(_) => info!("Buffered chain {} was shutdown", chain.name),
Err(e) => error!(
"Buffered chain {} encountered an error when flushing the chain for shutdown: {}",
chain.name, e
),
}
}
.in_current_span(),
);
BufferedChain {
send_handle: tx,
#[cfg(test)]
count,
original_chain: self,
}
}
pub fn new(transform_list: Vec<Transforms>, name: String) -> Self {
for transform in &transform_list {
register_counter!("shotover_transform_total", "transform" => transform.get_name());
register_counter!("shotover_transform_failures", "transform" => transform.get_name());
register_histogram!("shotover_transform_latency", "transform" => transform.get_name());
}
let chain_total = register_counter!("shotover_chain_total", "chain" => name.clone());
let chain_failures = register_counter!("shotover_chain_failures", "chain" => name.clone());
register_histogram!("shotover_chain_latency", "chain" => name.clone());
TransformChain {
name,
chain: transform_list,
chain_total,
chain_failures,
}
}
pub fn validate(&self) -> Vec<String> {
if self.chain.is_empty() {
return vec![
format!("{}:", self.name),
" Chain cannot be empty".to_string(),
];
}
let last_index = self.chain.len() - 1;
let mut errors = self
.chain
.iter()
.enumerate()
.flat_map(|(i, transform)| {
let mut errors = vec![];
if i == last_index && !transform.is_terminating() {
errors.push(format!(
" Non-terminating transform {:?} is last in chain. Last transform must be terminating.",
transform.get_name()
));
} else if i != last_index && transform.is_terminating() {
errors.push(format!(
" Terminating transform {:?} is not last in chain. Terminating transform must be last in chain.",
transform.get_name()
));
}
errors.extend(transform.validate().iter().map(|x| format!(" {x}")));
errors
})
.collect::<Vec<String>>();
if !errors.is_empty() {
errors.insert(0, format!("{}:", self.name));
}
errors
}
pub fn get_inner_chain_refs(&mut self) -> Vec<&mut Transforms> {
self.chain.iter_mut().collect_vec()
}
pub async fn process_request(
&mut self,
mut wrapper: Wrapper<'_>,
client_details: String,
) -> ChainResponse {
let start = Instant::now();
wrapper.reset(&mut self.chain);
let result = wrapper.call_next_transform().await;
self.chain_total.increment(1);
if result.is_err() {
self.chain_failures.increment(1);
}
histogram!("shotover_chain_latency", start.elapsed(), "chain" => self.name.clone(), "client_details" => client_details);
result
}
pub async fn process_request_rev(&mut self, mut wrapper: Wrapper<'_>) -> ChainResponse {
let start = Instant::now();
let mut chain: Vec<_> = self.chain.iter().cloned().rev().collect();
wrapper.reset(&mut chain);
let result = wrapper.call_next_transform_pushed().await;
self.chain_total.increment(1);
if result.is_err() {
self.chain_failures.increment(1);
}
histogram!("shotover_chain_latency", start.elapsed(), "chain" => self.name.clone());
result
}
/// Clone the chain while adding a producer for the pushed messages channel
pub fn clone_with_pushed_messages_tx(
&self,
pushed_messages_tx: mpsc::UnboundedSender<Messages>,
) -> Self {
let mut result = self.clone();
for transform in &mut result.chain {
transform.set_pushed_messages_tx(pushed_messages_tx.clone());
}
result
}
}
#[cfg(test)]
mod chain_tests {
use crate::transforms::chain::TransformChain;
use crate::transforms::debug::printer::DebugPrinter;
use crate::transforms::null::Null;
use crate::transforms::Transforms;
#[tokio::test]
async fn test_validate_invalid_chain() {
let chain = TransformChain::new(vec![], "test-chain".to_string());
assert_eq!(
chain.validate(),
vec!["test-chain:", " Chain cannot be empty"]
);
}
#[tokio::test]
async fn test_validate_valid_chain() {
let chain = TransformChain::new(
vec![
Transforms::DebugPrinter(DebugPrinter::new()),
Transforms::DebugPrinter(DebugPrinter::new()),
Transforms::Null(Null::default()),
],
"test-chain".to_string(),
);
assert_eq!(chain.validate(), Vec::<String>::new());
}
}