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
//! Break down the cost of Relay by its components and individual features it handles.
//!
//! Relay is a one stop shop for all different kinds of events Sentry supports, Errors,
//! Performance, Metrics, Replays, Crons and more. A single shared resource.
//!
//! This module intends to make it possible to give insights how much time and resources
//! Relay spends processing individual features. The measurements collected can be later used
//! for increased observability and accounting purposes.
//!
//! `relay-cogs` provides a way to give an answer to the questions:
//!  - What portion of Relay's costs can be attributed to feature X?
//!  - How much does feature X cost?
//!
//! ## Collecting COGs Measurements
//!
//! Measurements are collected through [`Cogs`] which attributes the measurement to either a single
//! or to multiple different [app features](AppFeature) belonging to a [resource](ResourceId).
//!
//! Collected and [attributed measurements](CogsMeasurement) then are recorded by a [`CogsRecorder`].
//!
//! ```
//! use relay_cogs::{AppFeature, Cogs, FeatureWeights, ResourceId};
//!
//! enum Message {
//!     Span,
//!     Transaction,
//!     TransactionWithSpans { num_spans: usize },
//! }
//!
//! struct Processor {
//!     cogs: Cogs
//! }
//!
//! impl From<&Message> for FeatureWeights {
//!     fn from(value: &Message) -> Self {
//!         match value {
//!             Message::Span => FeatureWeights::new(AppFeature::Spans),
//!             Message::Transaction => FeatureWeights::new(AppFeature::Transactions),
//!             Message::TransactionWithSpans { num_spans } => FeatureWeights::builder()
//!                 .weight(AppFeature::Spans, *num_spans)
//!                 .weight(AppFeature::Transactions, 1)
//!                 .build(),
//!         }
//!     }
//! }
//!
//! impl Processor {
//!     fn handle_message(&self, mut message: Message) {
//!         let _cogs = self.cogs.timed(ResourceId::Relay, &message);
//!
//!         self.step1(&mut message);
//!         self.step2(&mut message);
//!
//!         // Measurement automatically recorded here.
//!     }
//! #   fn step1(&self, _: &mut Message) {}
//! #   fn step2(&self, _: &mut Message) {}
//! }
//! ```
#![warn(missing_docs)]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/getsentry/relay/master/artwork/relay-icon.png",
    html_favicon_url = "https://raw.githubusercontent.com/getsentry/relay/master/artwork/relay-icon.png"
)]

use std::time::Duration;

mod cogs;
mod recorder;
#[cfg(test)]
mod test;

pub use cogs::*;
pub use recorder::*;
#[cfg(test)]
pub use test::*;

/// Resource ID as tracked in COGS.
///
/// Infrastructure costs are labeled with a resource id,
/// these costs need to be broken down further by the application
/// by [app features](AppFeature).
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum ResourceId {
    /// The Relay resource.
    ///
    /// This includes all computational costs required for running Relay.
    Relay,
}

/// App feature a COGS measurement is related to.
///
/// App features break down the cost of a [`ResourceId`], the
/// app features do no need to directly match a Sentry product.
/// Multiple app features are later grouped and aggregated to determine
/// the cost of a product.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AppFeature {
    /// A placeholder which should not be emitted but can be emitted in rare cases,
    /// for example error scenarios.
    ///
    /// It can be useful to start a COGS measurement before it is known
    /// what the measurement should be attributed to.
    /// For example when parsing data, the measurement should be started
    /// before parsing, but only after parsing it is known what to attribute
    /// the measurement to.
    Unattributed,

    /// Metrics are attributed by their namespace, whenever this is not possible
    /// or feasible, this app feature is emitted instead.
    UnattributedMetrics,
    /// When processing an envelope cannot be attributed or is not feasible to be attributed
    /// to a more specific category, this app feature is emitted instead.
    UnattributedEnvelope,

    /// Transactions.
    Transactions,
    /// Errors.
    Errors,
    /// Spans.
    Spans,
    /// Sessions.
    Sessions,
    /// Client reports.
    ClientReports,
    /// Crons check ins.
    CheckIns,
    /// Replays.
    Replays,
    /// Profiles.
    ///
    /// This app feature is for continuous profiling.
    Profiles,

    /// Metrics in the transactions namespace.
    MetricsTransactions,
    /// Metrics in the spans namespace.
    MetricsSpans,
    /// Metrics in the profiles namespace.
    MetricsProfiles,
    /// Metrics in the sessions namespace.
    MetricsSessions,
    /// Metrics in the custom namespace.
    MetricsCustom,
    /// Metrics in the `metric_stats` namespace.
    MetricsStats,
    /// Metrics in the unsupported namespace.
    ///
    /// This is usually not emitted, since metrics in the unsupported
    /// namespace should be dropped before any processing occurs.
    MetricsUnsupported,
}

impl AppFeature {
    /// Returns the string representation for this app feature.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Unattributed => "unattributed",
            Self::UnattributedMetrics => "unattributed_metrics",
            Self::UnattributedEnvelope => "unattributed_envelope",
            Self::Transactions => "transactions",
            Self::Errors => "errors",
            Self::Spans => "spans",
            Self::Sessions => "sessions",
            Self::ClientReports => "client_reports",
            Self::CheckIns => "check_ins",
            Self::Replays => "replays",
            Self::MetricsTransactions => "metrics_transactions",
            Self::MetricsSpans => "metrics_spans",
            Self::MetricsProfiles => "metrics_profiles",
            Self::MetricsSessions => "metrics_sessions",
            Self::MetricsCustom => "metrics_custom",
            Self::MetricsStats => "metrics_metric_stats",
            Self::MetricsUnsupported => "metrics_unsupported",
            Self::Profiles => "profiles",
        }
    }
}

/// A COGS measurement.
///
/// The measurement has already been attributed to a specific feature.
#[derive(Debug, Clone, Copy)]
pub struct CogsMeasurement {
    /// The measured resource.
    pub resource: ResourceId,
    /// The measured app feature.
    pub feature: AppFeature,
    /// The measurement value.
    pub value: Value,
}

/// A COGS measurement value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Value {
    /// A time measurement.
    Time(Duration),
}