1
// @@ begin lint list maintained by maint/add_warning @@
2
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
3
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
4
#![warn(missing_docs)]
5
#![warn(noop_method_call)]
6
#![warn(unreachable_pub)]
7
#![warn(clippy::all)]
8
#![deny(clippy::await_holding_lock)]
9
#![deny(clippy::cargo_common_metadata)]
10
#![deny(clippy::cast_lossless)]
11
#![deny(clippy::checked_conversions)]
12
#![allow(clippy::cognitive_complexity)] // See arti#2556
13
#![deny(clippy::debug_assert_with_mut_call)]
14
#![deny(clippy::exhaustive_enums)]
15
#![deny(clippy::exhaustive_structs)]
16
#![deny(clippy::expl_impl_clone_on_copy)]
17
#![deny(clippy::fallible_impl_from)]
18
#![deny(clippy::implicit_clone)]
19
#![deny(clippy::large_stack_arrays)]
20
#![warn(clippy::manual_ok_or)]
21
#![deny(clippy::missing_docs_in_private_items)]
22
#![warn(clippy::needless_borrow)]
23
#![warn(clippy::needless_pass_by_value)]
24
#![warn(clippy::option_option)]
25
#![warn(clippy::or_fun_call)]
26
#![deny(clippy::print_stderr)]
27
#![deny(clippy::print_stdout)]
28
#![warn(clippy::rc_buffer)]
29
#![deny(clippy::ref_option_ref)]
30
#![warn(clippy::semicolon_if_nothing_returned)]
31
#![warn(clippy::trait_duplication_in_bounds)]
32
#![deny(clippy::unchecked_time_subtraction)]
33
#![deny(clippy::unnecessary_wraps)]
34
#![warn(clippy::unseparated_literal_suffix)]
35
#![deny(clippy::unwrap_used)]
36
#![deny(clippy::mod_module_files)]
37
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
38
#![allow(clippy::uninlined_format_args)]
39
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
40
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
41
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
42
#![allow(clippy::needless_lifetimes)] // See arti#1765
43
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
44
#![allow(clippy::collapsible_if)] // See arti#2342
45
#![deny(clippy::unused_async)]
46
#![deny(clippy::string_slice)] // See arti#2571
47
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
48
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
49

            
50
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
51
#![warn(unnameable_types)]
52

            
53
//! Tracing exporter to write spans to a file in the OTLP JSON format.
54

            
55
// TODO: If https://github.com/open-telemetry/opentelemetry-rust/issues/2602 gets fixed, we can
56
// replace this entire file with whatever upstream has for doing this.
57

            
58
use opentelemetry_proto::transform::common::tonic::ResourceAttributesWithSchema;
59
use opentelemetry_proto::transform::trace::tonic::group_spans_by_resource_and_scope;
60
use opentelemetry_sdk::{
61
    Resource,
62
    error::{OTelSdkError, OTelSdkResult},
63
    trace::SpanExporter,
64
};
65
use std::{
66
    fmt::Debug,
67
    io::{LineWriter, Write},
68
    sync::{Arc, Mutex},
69
};
70

            
71
/// Tracing exporter to write OTLP JSON to a file (or anything else that implements [`LineWriter`].
72
#[derive(Debug)]
73
pub struct FileExporter<W: Write + Send + Debug> {
74
    /// The [`LineWriter`] to write to.
75
    writer: Arc<Mutex<LineWriter<W>>>,
76
    /// The [`Resource`] to associate spans with.
77
    resource: Resource,
78
}
79

            
80
impl<W: Write + Send + Debug> FileExporter<W> {
81
    /// Create a new [`FileExporter`]
82
    pub fn new(writer: W, resource: Resource) -> Self {
83
        Self {
84
            writer: Arc::new(Mutex::new(LineWriter::new(writer))),
85
            resource,
86
        }
87
    }
88
}
89

            
90
// Note that OpenTelemetry can only represent events as children of spans, so this exporter only
91
// works on spans. If you want a event to be exported, you need to make sure it exists within some
92
// span.
93
impl<W: Write + Send + Debug> SpanExporter for FileExporter<W> {
94
    fn export(
95
        &self,
96
        batch: Vec<opentelemetry_sdk::trace::SpanData>,
97
    ) -> impl futures::Future<
98
        Output = std::result::Result<(), opentelemetry_sdk::error::OTelSdkError>,
99
    > + std::marker::Send {
100
        let resource = ResourceAttributesWithSchema::from(&self.resource);
101
        let data = group_spans_by_resource_and_scope(batch, &resource);
102
        let mut writer = self.writer.lock().expect("Lock poisoned");
103
        Box::pin(std::future::ready('write: {
104
            // See https://opentelemetry.io/docs/specs/otel/protocol/file-exporter/ for format
105

            
106
            if let Err(err) = serde_json::to_writer(
107
                writer.get_mut(),
108
                &serde_json::json!({"resourceSpans": data}),
109
            ) {
110
                break 'write Err(OTelSdkError::InternalFailure(err.to_string()));
111
            }
112

            
113
            if let Err(err) = writer.write(b"\n") {
114
                break 'write Err(OTelSdkError::InternalFailure(err.to_string()));
115
            }
116

            
117
            Ok(())
118
        }))
119
    }
120

            
121
    fn force_flush(&self) -> OTelSdkResult {
122
        let mut writer = self
123
            .writer
124
            .lock()
125
            .map_err(|e| OTelSdkError::InternalFailure(e.to_string()))?;
126

            
127
        writer
128
            .flush()
129
            .map_err(|e| OTelSdkError::InternalFailure(e.to_string()))
130
    }
131

            
132
    fn set_resource(&mut self, res: &opentelemetry_sdk::Resource) {
133
        self.resource = res.clone();
134
    }
135
}