flareapp-core 0.2.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Test helpers for this crate and for the integration crates.
//!
//! Only available in this crate's tests and behind the `testing` feature,
//! which integration crates turn on in their `dev-dependencies`. Not part of the
//! public API.
#![expect(
    clippy::unwrap_used,
    clippy::panic,
    reason = "these helpers are only used in tests, where a panic is a clear failure"
)]

use std::collections::VecDeque;
use std::panic::Location;
use std::pin::pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Waker};
use std::time::{Duration, Instant};

use serde_json::{Value, json};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::registry::LookupSpan;
use tracing_subscriber::{Layer, Registry};

use flareapp_otlp::{
    AnyValue, KeyValue, LogRecord, Severity, Span, SpanId, SpanKind, TraceId, find_attribute,
};

use crate::config::{Config, OtlpProtocol};
use crate::entry_point::{EntryPoint, SpanEntryPoint};
use crate::report::Report;
use crate::scope::set_global_entry_point;
use crate::transport::{Request, Response, Transport, TransportError};

/// A fake transport for tests.
///
/// The fake transport stores every request that it gets. It answers with the
/// responses that `respond_with` and `fail_with` queued, in order. When no
/// responses are queued, it answers `201 Created`.
#[derive(Debug, Clone, Default)]
pub struct FakeTransport {
    state: Arc<Mutex<State>>,
}

#[derive(Debug, Default)]
struct State {
    requests: Vec<Request>,
    responses: VecDeque<Result<Response, String>>,
}

impl FakeTransport {
    /// Queues a response. Queued responses answer requests in order.
    pub fn respond_with(&self, response: Response) -> &Self {
        self.state.lock().unwrap().responses.push_back(Ok(response));

        self
    }

    /// Queues a failure, as if the connection broke.
    pub fn fail_with(&self, error: &str) -> &Self {
        self.state
            .lock()
            .unwrap()
            .responses
            .push_back(Err(error.to_owned()));

        self
    }

    /// Forgets all requests received so far.
    pub fn clear(&self) {
        self.state.lock().unwrap().requests.clear();
    }

    /// Returns the JSON bodies of all requests received so far whose URL ends with
    /// `path`, like `/v1/logs`.
    pub fn bodies(&self, path: &str) -> Vec<Value> {
        self.requests()
            .iter()
            .filter(|request| request.url.ends_with(path))
            .map(json)
            .collect()
    }

    /// Returns the spans of all trace requests received so far, from every batch,
    /// in OTLP/JSON.
    pub fn spans(&self) -> Vec<Value> {
        self.bodies("/v1/traces")
            .iter()
            .flat_map(|body| list(&body["resourceSpans"]))
            .flat_map(|resource| list(&resource["scopeSpans"]))
            .flat_map(|scope| list(&scope["spans"]))
            .cloned()
            .collect()
    }

    /// Returns the log records of all log requests received so far, from every
    /// batch, in OTLP/JSON.
    pub fn log_records(&self) -> Vec<Value> {
        self.bodies("/v1/logs")
            .iter()
            .flat_map(|body| list(&body["resourceLogs"]))
            .flat_map(|resource| list(&resource["scopeLogs"]))
            .flat_map(|scope| list(&scope["logRecords"]))
            .cloned()
            .collect()
    }

    /// Returns a copy of all requests received so far.
    pub fn requests(&self) -> Vec<Request> {
        self.state.lock().unwrap().requests.clone()
    }

    /// Waits until at least `count` requests have arrived, or until `timeout` has
    /// passed. Returns the requests received so far.
    pub fn wait_for_requests(&self, count: usize, timeout: Duration) -> Vec<Request> {
        let deadline = Instant::now() + timeout;

        loop {
            let requests = self.requests();
            if requests.len() >= count || Instant::now() > deadline {
                return requests;
            }
            std::thread::sleep(Duration::from_millis(5));
        }
    }
}

impl Transport for FakeTransport {
    fn send(&self, request: &Request) -> Result<Response, TransportError> {
        let mut state = self.state.lock().unwrap();
        state.requests.push(request.clone());

        match state.responses.pop_front() {
            Some(Ok(response)) => Ok(response),
            Some(Err(error)) => Err(TransportError::new(error)),
            None => Ok(Response::new(201)),
        }
    }
}

/// A transport that holds each request until [`GatedTransport::open`] runs.
///
/// The [`FakeTransport`] inside stores each request first, and then this
/// transport waits. Tests use this transport to keep the worker thread busy, so
/// that the queue fills up.
#[derive(Debug, Clone)]
pub struct GatedTransport {
    inner: FakeTransport,
    open: Arc<AtomicBool>,
}

impl GatedTransport {
    /// Creates a closed gate in front of `inner`.
    pub fn new(inner: &FakeTransport) -> Self {
        Self {
            inner: inner.clone(),
            open: Arc::default(),
        }
    }

    /// Lets every request through, also the request that waits now.
    pub fn open(&self) {
        self.open.store(true, Ordering::SeqCst);
    }
}

impl Transport for GatedTransport {
    fn send(&self, request: &Request) -> Result<Response, TransportError> {
        let response = self.inner.send(request);
        while !self.open.load(Ordering::SeqCst) {
            std::thread::sleep(Duration::from_millis(1));
        }

        response
    }
}

/// A transport that answers `200 OK` to every request and keeps nothing.
///
/// Benchmarks use this transport. No request goes over the network, and the
/// memory does not grow with each request, as it does with [`FakeTransport`].
#[derive(Debug, Clone, Copy, Default)]
pub struct DiscardTransport;

impl Transport for DiscardTransport {
    fn send(&self, _request: &Request) -> Result<Response, TransportError> {
        Ok(Response::new(200))
    }
}

/// Parses the JSON body of a request.
pub fn json(request: &Request) -> Value {
    serde_json::from_slice(&request.body).unwrap()
}

/// Returns the items of a JSON list, or no items when `value` is not a list.
fn list(value: &Value) -> &[Value] {
    value.as_array().map_or(&[], Vec::as_slice)
}

/// Returns the value of the attribute `key` of a span, a span event, a log record
/// or a resource in OTLP/JSON, like `{"stringValue": "GET"}`.
pub fn json_attribute<'a>(item: &'a Value, key: &str) -> Option<&'a Value> {
    list(&item["attributes"])
        .iter()
        .find(|attribute| attribute["key"] == key)
        .map(|attribute| &attribute["value"])
}

/// Returns the attributes of a span, a span event, a log record or a resource in
/// OTLP/JSON as one JSON object, from each key to its value. A snapshot of this
/// object is easier to read than the list of OTLP/JSON.
pub fn json_attributes(item: &Value) -> Value {
    let attributes = list(&item["attributes"])
        .iter()
        .filter_map(|attribute| {
            let key = attribute["key"].as_str()?;

            Some((key.to_owned(), attribute["value"].clone()))
        })
        .collect();

    Value::Object(attributes)
}

/// Returns an OTLP/JSON string value, like `{"stringValue": "GET"}`.
pub fn string_value(text: &str) -> Value {
    json!({ "stringValue": text })
}

/// Returns the first span named `name`. Fails with the list of spans when no span
/// has that name.
pub fn span_named<'a>(spans: &'a [Value], name: &str) -> &'a Value {
    spans
        .iter()
        .find(|span| span["name"] == name)
        .unwrap_or_else(|| panic!("no span named {name} in {spans:#?}"))
}

/// A `traceparent` header of a sampled trace with the trace id
/// `5b8efaf69a4d3c2b1e0f6a7b8c9daebf`. Tests send this header to continue a
/// remote trace.
pub const TRACEPARENT: &str = "00-5b8efaf69a4d3c2b1e0f6a7b8c9daebf-051a2b3c4d5e6f70-01";

/// The prefixes of the report attributes that hold the request data, like
/// `url.full`.
const REQUEST_DATA: &[&str] = &["http.", "url.", "server.", "user_agent.", "client."];

/// Returns the attributes of a report that hold the request data, for a
/// snapshot. The other attributes describe the process and the machine, which
/// differ from one computer to the next.
pub fn request_data(attributes: &Value) -> Value {
    let data = attributes
        .as_object()
        .unwrap()
        .iter()
        .filter(|(key, _)| REQUEST_DATA.iter().any(|prefix| key.starts_with(prefix)))
        .map(|(key, value)| (key.clone(), value.clone()))
        .collect();

    Value::Object(data)
}

/// Sends an error report with the class `my_app::Failed` to the Flare client that
/// `init` started, like a handler that failed. Panics when no Flare client runs.
#[track_caller]
pub fn report_error() {
    let client = crate::current().unwrap();
    client.send_report(Report::new("my_app::Failed", "failed", Location::caller()));
}

/// Polls `future` until it is ready, and returns its output.
///
/// The waker does nothing, so this function only suits futures that finish
/// without waiting for I/O or a timer.
pub fn block_on<F: Future>(future: F) -> F::Output {
    let mut future = pin!(future);
    let mut context = Context::from_waker(Waker::noop());

    loop {
        if let Poll::Ready(output) = future.as_mut().poll(&mut context) {
            return output;
        }
    }
}

/// Returns an info log record with `body` as its message.
pub fn log(body: &str) -> LogRecord {
    LogRecord::new(Severity::Info, body.to_owned())
}

/// Returns a duration of `seconds` seconds.
pub fn secs(seconds: u64) -> Duration {
    Duration::from_secs(seconds)
}

/// Returns the value of the attribute called `key`, if there is one.
pub fn attribute<'a>(attributes: &'a [KeyValue], key: &str) -> Option<&'a AnyValue> {
    find_attribute(attributes, key)
}

/// Returns a short span without a parent.
pub fn span() -> Span {
    Span {
        start_time_unix_nano: 1,
        end_time_unix_nano: 2,
        ..Span::new(
            TraceId::random(),
            SpanId::random(),
            "test",
            SpanKind::Internal,
        )
    }
}

/// Takes the lock that makes tests take turns. Tests share the global Flare
/// client, so a test that starts the Flare client holds this lock until the test
/// is done.
pub fn serial() -> MutexGuard<'static, ()> {
    static SERIAL: Mutex<()> = Mutex::new(());

    SERIAL.lock().unwrap_or_else(PoisonError::into_inner)
}

/// Removes the entry point of the app-wide scope when dropped.
#[derive(Debug)]
#[must_use]
pub struct GlobalEntryPoint;

impl Drop for GlobalEntryPoint {
    fn drop(&mut self) {
        set_global_entry_point(None);
    }
}

/// Sets the entry point of the app-wide scope, like `configure_scope` outside
/// any `with_scope`. The returned guard removes it again.
///
/// The app-wide scope is shared by all tests, so hold [`serial`] or run inside
/// [`run`] while the guard lives.
#[must_use = "dropping the guard removes the entry point again"]
pub fn global_entry_point(entry_point: EntryPoint) -> GlobalEntryPoint {
    set_global_entry_point(Some(entry_point));

    GlobalEntryPoint
}

/// Runs `work` inside a `tracing` span whose [`SpanEntryPoint`] is the queue
/// entry point `send-invoice`. The span lives in a registry subscriber for the
/// current thread only.
pub fn in_queue_span<R, W: FnOnce() -> R>(work: W) -> R {
    tracing::subscriber::with_default(tracing_subscriber::registry(), || {
        let span = tracing::info_span!("job");
        span.with_subscriber(|(id, dispatch)| {
            let registry = dispatch.downcast_ref::<Registry>().unwrap();
            let span = registry.span(id).unwrap();
            span.extensions_mut()
                .insert(SpanEntryPoint(EntryPoint::queue("send-invoice")));
        });
        let _entered = span.enter();

        work()
    })
}

/// Starts the Flare client with a [`FakeTransport`], runs `work`, flushes, stops
/// the Flare client, and returns the transport with everything that was sent.
///
/// The config has the API key `secret`, and sends logs and traces as JSON, so
/// tests can read them with [`FakeTransport::bodies`]. `configure` can change
/// both. Tests take turns, because they share the global client.
pub fn run<C: FnOnce(Config) -> Config, W: FnOnce()>(configure: C, work: W) -> FakeTransport {
    let config = Config::new()
        .api_key("secret")
        .otlp_protocol(OtlpProtocol::HttpJson);

    run_with(configure(config), work)
}

/// Like [`run`], with traces on and with `layer` on a `tracing` subscriber.
///
/// Pass `flareapp_tracing::layer()` as `layer`. This crate cannot depend on
/// `flareapp-tracing`, because `flareapp-tracing` depends on this crate.
///
/// The config sends every trace. `configure` runs after that, so it can change the
/// sample rate. The subscriber is set for the current thread only, while `work`
/// runs, so events on other threads do not reach the layer.
pub fn run_traced<L, C, W>(layer: L, configure: C, work: W) -> FakeTransport
where
    L: Layer<Registry> + Send + Sync + 'static,
    C: FnOnce(Config) -> Config,
    W: FnOnce(),
{
    run(
        |config| configure(config.traces_sample_rate(1.0)),
        || {
            let subscriber = tracing_subscriber::registry().with(layer);
            tracing::subscriber::with_default(subscriber, work);
        },
    )
}

/// Like [`run`], for a config you made yourself, like one from `flareapp::config!`.
/// The config must have an API key. `run_with` replaces its transport with a
/// [`FakeTransport`].
pub fn run_with<W: FnOnce()>(config: Config, work: W) -> FakeTransport {
    let _serial = serial();
    let transport = FakeTransport::default();
    let flare = crate::init(config.transport(transport.clone()));

    work();

    crate::flush(Duration::from_secs(2));
    drop(flare);

    transport
}