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
use std::{
    collections::{BTreeMap, HashMap},
    sync::Arc,
};

use tokio::task::JoinHandle;
use tokio_stream::StreamExt;
use vector_lib::api_client::{
    gql::{ComponentsQueryExt, ComponentsSubscriptionExt, MetricsSubscriptionExt},
    Client, SubscriptionClient,
};

use super::state::{self, OutputMetrics};
use crate::{config::ComponentKey, top::state::SentEventsMetric};

/// Components that have been added
async fn component_added(client: Arc<SubscriptionClient>, tx: state::EventTx) {
    tokio::pin! {
        let stream = client.component_added();
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_added;
            let key = ComponentKey::from(c.component_id);
            _ = tx
                .send(state::EventType::ComponentAdded(state::ComponentRow {
                    key,
                    kind: c.on.to_string(),
                    component_type: c.component_type,
                    outputs: HashMap::new(),
                    received_bytes_total: 0,
                    received_bytes_throughput_sec: 0,
                    received_events_total: 0,
                    received_events_throughput_sec: 0,
                    sent_bytes_total: 0,
                    sent_bytes_throughput_sec: 0,
                    sent_events_total: 0,
                    sent_events_throughput_sec: 0,
                    #[cfg(feature = "allocation-tracing")]
                    allocated_bytes: 0,
                    errors: 0,
                }))
                .await;
        }
    }
}

/// Allocated bytes per component
#[cfg(feature = "allocation-tracing")]
async fn allocated_bytes(client: Arc<SubscriptionClient>, tx: state::EventTx, interval: i64) {
    tokio::pin! {
        let stream = client.component_allocated_bytes_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_allocated_bytes;
            _ = tx
                .send(state::EventType::AllocatedBytes(
                    c.into_iter()
                        .map(|c| {
                            (
                                ComponentKey::from(c.component_id.as_str()),
                                c.metric.allocated_bytes as i64,
                            )
                        })
                        .collect(),
                ))
                .await;
        }
    }
}
/// Components that have been removed
async fn component_removed(client: Arc<SubscriptionClient>, tx: state::EventTx) {
    tokio::pin! {
        let stream = client.component_removed();
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_removed;
            let id = ComponentKey::from(c.component_id.as_str());
            _ = tx.send(state::EventType::ComponentRemoved(id)).await;
        }
    }
}

async fn received_bytes_totals(client: Arc<SubscriptionClient>, tx: state::EventTx, interval: i64) {
    tokio::pin! {
        let stream = client.component_received_bytes_totals_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_received_bytes_totals;
            _ = tx
                .send(state::EventType::ReceivedBytesTotals(
                    c.into_iter()
                        .map(|c| {
                            (
                                ComponentKey::from(c.component_id.as_str()),
                                c.metric.received_bytes_total as i64,
                            )
                        })
                        .collect(),
                ))
                .await;
        }
    }
}

async fn received_bytes_throughputs(
    client: Arc<SubscriptionClient>,
    tx: state::EventTx,
    interval: i64,
) {
    tokio::pin! {
        let stream = client.component_received_bytes_throughputs_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_received_bytes_throughputs;
            _ = tx
                .send(state::EventType::ReceivedBytesThroughputs(
                    interval,
                    c.into_iter()
                        .map(|c| (ComponentKey::from(c.component_id.as_str()), c.throughput))
                        .collect(),
                ))
                .await;
        }
    }
}

async fn received_events_totals(
    client: Arc<SubscriptionClient>,
    tx: state::EventTx,
    interval: i64,
) {
    tokio::pin! {
        let stream = client.component_received_events_totals_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_received_events_totals;
            _ = tx
                .send(state::EventType::ReceivedEventsTotals(
                    c.into_iter()
                        .map(|c| {
                            (
                                ComponentKey::from(c.component_id.as_str()),
                                c.metric.received_events_total as i64,
                            )
                        })
                        .collect(),
                ))
                .await;
        }
    }
}

async fn received_events_throughputs(
    client: Arc<SubscriptionClient>,
    tx: state::EventTx,
    interval: i64,
) {
    tokio::pin! {
        let stream = client.component_received_events_throughputs_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_received_events_throughputs;
            _ = tx
                .send(state::EventType::ReceivedEventsThroughputs(
                    interval,
                    c.into_iter()
                        .map(|c| (ComponentKey::from(c.component_id.as_str()), c.throughput))
                        .collect(),
                ))
                .await;
        }
    }
}

async fn sent_bytes_totals(client: Arc<SubscriptionClient>, tx: state::EventTx, interval: i64) {
    tokio::pin! {
        let stream = client.component_sent_bytes_totals_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_sent_bytes_totals;
            _ = tx
                .send(state::EventType::SentBytesTotals(
                    c.into_iter()
                        .map(|c| {
                            (
                                ComponentKey::from(c.component_id.as_str()),
                                c.metric.sent_bytes_total as i64,
                            )
                        })
                        .collect(),
                ))
                .await;
        }
    }
}

async fn sent_bytes_throughputs(
    client: Arc<SubscriptionClient>,
    tx: state::EventTx,
    interval: i64,
) {
    tokio::pin! {
        let stream = client.component_sent_bytes_throughputs_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_sent_bytes_throughputs;
            _ = tx
                .send(state::EventType::SentBytesThroughputs(
                    interval,
                    c.into_iter()
                        .map(|c| (ComponentKey::from(c.component_id.as_str()), c.throughput))
                        .collect(),
                ))
                .await;
        }
    }
}

async fn sent_events_totals(client: Arc<SubscriptionClient>, tx: state::EventTx, interval: i64) {
    tokio::pin! {
        let stream = client.component_sent_events_totals_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_sent_events_totals;
            _ = tx
                .send(state::EventType::SentEventsTotals(
                    c.into_iter()
                        .map(|c| SentEventsMetric {
                            key: ComponentKey::from(c.component_id.as_str()),
                            total: c.metric.sent_events_total as i64,
                            outputs: c.outputs().into_iter().collect(),
                        })
                        .collect(),
                ))
                .await;
        }
    }
}

async fn sent_events_throughputs(
    client: Arc<SubscriptionClient>,
    tx: state::EventTx,
    interval: i64,
) {
    tokio::pin! {
        let stream = client.component_sent_events_throughputs_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_sent_events_throughputs;
            _ = tx
                .send(state::EventType::SentEventsThroughputs(
                    interval,
                    c.into_iter()
                        .map(|c| SentEventsMetric {
                            key: ComponentKey::from(c.component_id.as_str()),
                            total: c.throughput,
                            outputs: c.outputs().into_iter().collect(),
                        })
                        .collect(),
                ))
                .await;
        }
    }
}

async fn errors_totals(client: Arc<SubscriptionClient>, tx: state::EventTx, interval: i64) {
    tokio::pin! {
        let stream = client.component_errors_totals_subscription(interval);
    };

    while let Some(Some(res)) = stream.next().await {
        if let Some(d) = res.data {
            let c = d.component_errors_totals;
            _ = tx
                .send(state::EventType::ErrorsTotals(
                    c.into_iter()
                        .map(|c| {
                            (
                                ComponentKey::from(c.component_id.as_str()),
                                c.metric.errors_total as i64,
                            )
                        })
                        .collect(),
                ))
                .await;
        }
    }
}

/// Subscribe to each metrics channel through a separate client. This is a temporary workaround
/// until client multiplexing is fixed. In future, we should be able to use a single client
pub fn subscribe(
    client: SubscriptionClient,
    tx: state::EventTx,
    interval: i64,
) -> Vec<JoinHandle<()>> {
    let client = Arc::new(client);

    vec![
        tokio::spawn(component_added(Arc::clone(&client), tx.clone())),
        tokio::spawn(component_removed(Arc::clone(&client), tx.clone())),
        tokio::spawn(received_bytes_totals(
            Arc::clone(&client),
            tx.clone(),
            interval,
        )),
        tokio::spawn(received_bytes_throughputs(
            Arc::clone(&client),
            tx.clone(),
            interval,
        )),
        tokio::spawn(received_events_totals(
            Arc::clone(&client),
            tx.clone(),
            interval,
        )),
        tokio::spawn(received_events_throughputs(
            Arc::clone(&client),
            tx.clone(),
            interval,
        )),
        tokio::spawn(sent_bytes_totals(Arc::clone(&client), tx.clone(), interval)),
        tokio::spawn(sent_bytes_throughputs(
            Arc::clone(&client),
            tx.clone(),
            interval,
        )),
        tokio::spawn(sent_events_totals(
            Arc::clone(&client),
            tx.clone(),
            interval,
        )),
        tokio::spawn(sent_events_throughputs(
            Arc::clone(&client),
            tx.clone(),
            interval,
        )),
        #[cfg(feature = "allocation-tracing")]
        tokio::spawn(allocated_bytes(Arc::clone(&client), tx.clone(), interval)),
        tokio::spawn(errors_totals(Arc::clone(&client), tx, interval)),
    ]
}

/// Retrieve the initial components/metrics for first paint. Further updating the metrics
/// will be handled by subscriptions.
pub async fn init_components(client: &Client) -> Result<state::State, ()> {
    // Execute a query to get the latest components, and aggregate metrics for each resource.
    // Since we don't know currently have a mechanism for scrolling/paging through results,
    // we're using an artificially high page size to capture all likely component configurations.
    let rows = client
        .components_query(i16::MAX as i64)
        .await
        .map_err(|_| ())?
        .data
        .ok_or(())?
        .components
        .edges
        .into_iter()
        .flat_map(|edge| {
            let d = edge.node;
            let key = ComponentKey::from(d.component_id);
            Some((
                key.clone(),
                state::ComponentRow {
                    key,
                    kind: d.on.to_string(),
                    component_type: d.component_type,
                    outputs: d
                        .on
                        .outputs()
                        .into_iter()
                        .map(|(id, sent_events_total)| (id, OutputMetrics::from(sent_events_total)))
                        .collect(),
                    received_bytes_total: d.on.received_bytes_total(),
                    received_bytes_throughput_sec: 0,
                    received_events_total: d.on.received_events_total(),
                    received_events_throughput_sec: 0,
                    sent_bytes_total: d.on.sent_bytes_total(),
                    sent_bytes_throughput_sec: 0,
                    sent_events_total: d.on.sent_events_total(),
                    sent_events_throughput_sec: 0,
                    #[cfg(feature = "allocation-tracing")]
                    allocated_bytes: 0,
                    errors: 0,
                },
            ))
        })
        .collect::<BTreeMap<_, _>>();

    Ok(state::State::new(rows))
}