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
use crate::MetricSink;
use std::fs;
use std::io::{self, ErrorKind};
use std::os::unix::net::UnixDatagram;
use std::panic::RefUnwindSafe;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::Duration;
use std::{env, thread};
#[derive(Debug)]
pub struct TempDir {
base: PathBuf,
}
impl TempDir {
pub fn new<P>(prefix: P) -> io::Result<Self>
where
P: AsRef<Path>,
{
let base = env::temp_dir().join(prefix);
fs::create_dir_all(&base)?;
Ok(TempDir { base })
}
pub fn new_path<P>(&self, name: P) -> PathBuf
where
P: AsRef<Path>,
{
self.base.join(name)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.base);
}
}
pub trait DatagramConsumer {
fn accept(&self, datagram: String);
}
impl<F> DatagramConsumer for F
where
F: Fn(String),
{
fn accept(&self, datagram: String) {
(self)(datagram);
}
}
pub struct UnixSocketServer {
ready: AtomicBool,
shutdown: AtomicBool,
path: PathBuf,
consumer: Arc<dyn DatagramConsumer + Send + Sync + 'static>,
interval: Duration,
}
impl UnixSocketServer {
pub fn new<P, C>(path: P, interval: Duration, consumer: C) -> Self
where
P: AsRef<Path>,
C: DatagramConsumer + Send + Sync + 'static,
{
UnixSocketServer {
ready: AtomicBool::new(false),
shutdown: AtomicBool::new(false),
path: path.as_ref().to_path_buf(),
consumer: Arc::new(consumer),
interval,
}
}
pub fn is_ready(&self) -> bool {
self.ready.load(Ordering::Acquire)
}
pub fn run(&self) -> io::Result<()> {
let _ = fs::remove_file(&self.path);
let socket = UnixDatagram::bind(&self.path)?;
socket.set_read_timeout(Some(self.interval))?;
let mut buf = [0u8; 1024];
self.ready.store(true, Ordering::Release);
loop {
match socket.recv(&mut buf) {
Ok(v) => match std::str::from_utf8(&buf[0..v]) {
Ok(s) => self.consumer.accept(s.to_owned()),
Err(e) => eprintln!("Error: Couldn't decode string to utf-8 {}", e),
},
Err(e) => {
if e.kind() == ErrorKind::WouldBlock {
if self.shutdown.load(Ordering::Acquire) {
break;
}
} else {
eprintln!("Error: {} - {:?}", e, e.kind());
}
}
}
}
Ok(())
}
pub fn shutdown(&self) {
self.shutdown.store(true, Ordering::Release);
}
}
pub struct UnixServerHarness {
base: PathBuf,
server: Option<Arc<UnixSocketServer>>,
thread: Option<JoinHandle<()>>,
}
impl UnixServerHarness {
pub fn new<P>(prefix: P) -> Self
where
P: AsRef<Path>,
{
UnixServerHarness {
base: prefix.as_ref().to_path_buf(),
server: None,
thread: None,
}
}
pub fn run<C, F>(mut self, consumer: C, body: F)
where
C: DatagramConsumer + Send + Sync + 'static,
F: FnOnce(&Path),
{
let temp = TempDir::new(&self.base).unwrap();
let socket = temp.new_path("cadence.sock");
let server = Arc::new(UnixSocketServer::new(&socket, Duration::from_millis(100), consumer));
let server_local = Arc::clone(&server);
let t = thread::spawn(move || {
server_local.run().unwrap();
});
while !server.is_ready() {
thread::yield_now();
}
self.server = Some(server);
self.thread = Some(t);
body(&socket);
}
pub fn run_quiet<F>(self, body: F)
where
F: FnOnce(&Path),
{
self.run(|_| (), body)
}
}
impl Drop for UnixServerHarness {
fn drop(&mut self) {
if let Some(s) = self.server.take() {
s.shutdown();
}
if let Some(t) = self.thread.take() {
let _ = t.join();
}
}
}
pub struct DelegatingMetricSink {
delegate: Arc<dyn MetricSink + Send + Sync + RefUnwindSafe>,
}
impl DelegatingMetricSink {
pub fn new<S>(delegate: Arc<S>) -> Self
where
S: MetricSink + Send + Sync + RefUnwindSafe + 'static,
{
DelegatingMetricSink { delegate }
}
}
impl MetricSink for DelegatingMetricSink {
fn emit(&self, metric: &str) -> io::Result<usize> {
self.delegate.emit(metric)
}
}