File size: 13,150 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use std::{
    net::{SocketAddr, SocketAddrV4, TcpListener, TcpStream},
    sync::{Arc, Mutex},
    thread::spawn,
};

use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use tungstenite::{Message, accept};

use crate::{
    store::SpanId,
    store_container::StoreContainer,
    timestamp::Timestamp,
    u64_string,
    viewer::{Update, ViewLineUpdate, ViewMode, Viewer},
};

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
#[serde(rename_all = "kebab-case")]
pub enum ServerToClientMessage {
    ViewLine {
        #[serde(flatten)]
        update: ViewLineUpdate,
    },
    ViewLinesCount {
        count: usize,
        max: u64,
    },
    #[serde(rename_all = "camelCase")]
    QueryResult {
        #[serde(with = "u64_string")]
        id: SpanId,
        is_graph: bool,
        start: Timestamp,
        end: Timestamp,
        duration: Timestamp,
        cpu: Timestamp,
        allocations: u64,
        deallocations: u64,
        allocation_count: u64,
        persistent_allocations: u64,
        args: Vec<(String, String)>,
        path: Vec<String>,
    },
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
#[serde(rename_all = "kebab-case")]
pub enum ClientToServerMessage {
    #[serde(rename_all = "camelCase")]
    ViewRect {
        view_rect: ViewRect,
    },
    ViewMode {
        #[serde(with = "u64_string")]
        id: SpanId,
        mode: String,
        inherit: bool,
    },
    ResetViewMode {
        #[serde(with = "u64_string")]
        id: SpanId,
    },
    Query {
        #[serde(with = "u64_string")]
        id: SpanId,
    },
    Ack,
    CheckForMoreData,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct SpanViewEvent {
    pub start: Timestamp,
    pub duration: Timestamp,
    pub name: String,
    pub id: Option<SpanId>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Filter {
    pub op: Op,
    pub value: u64,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum Op {
    Gt,
    Lt,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ViewRect {
    pub x: u64,
    pub y: u64,
    pub width: u64,
    pub height: u64,
    pub horizontal_pixels: u64,
    pub query: String,
    pub view_mode: String,
    pub value_mode: String,
    pub value_filter: Option<Filter>,
    pub count_filter: Option<Filter>,
}

struct ConnectionState {
    store: Arc<StoreContainer>,
    viewer: Viewer,
    view_rect: ViewRect,
    last_update_generation: usize,
}

pub fn serve(store: Arc<StoreContainer>, port: u16) {
    let server = TcpListener::bind(SocketAddr::V4(SocketAddrV4::new(
        std::net::Ipv4Addr::new(127, 0, 0, 1),
        port,
    )))
    .unwrap();
    for stream in server.incoming() {
        let store = store.clone();

        spawn(move || {
            let websocket = accept(stream.unwrap()).unwrap();
            if let Err(err) = handle_connection(websocket, store) {
                eprintln!("Error: {err:?}");
            }
        });
    }
}

fn handle_connection(
    mut websocket: tungstenite::WebSocket<TcpStream>,
    store: Arc<StoreContainer>,
) -> Result<()> {
    let state = Arc::new(Mutex::new(ConnectionState {
        store,
        viewer: Viewer::new(),
        view_rect: ViewRect {
            x: 0,
            y: 0,
            width: 1,
            height: 1,
            horizontal_pixels: 1,
            query: String::new(),
            view_mode: "aggregated".to_string(),
            value_mode: "duration".to_string(),
            count_filter: None,
            value_filter: None,
        },
        last_update_generation: 0,
    }));
    let mut update_skipped = false;
    let mut ready_for_update = true;

    fn send_update(
        websocket: &mut tungstenite::WebSocket<TcpStream>,
        state: &mut ConnectionState,
        force_send: bool,
        ready_for_update: &mut bool,
        update_skipped: &mut bool,
    ) -> Result<()> {
        if !*ready_for_update {
            if force_send {
                *update_skipped = true;
            }
            return Ok(());
        }
        let store = state.store.read();
        if !force_send && state.last_update_generation == store.generation() {
            return Ok(());
        }
        state.last_update_generation = store.generation();
        let Update {
            lines: updates,
            max,
        } = state.viewer.compute_update(&store, &state.view_rect);
        let count = updates.len();
        for update in updates {
            let message = ServerToClientMessage::ViewLine { update };
            let message = serde_json::to_string(&message).unwrap();
            websocket.send(Message::Text(message))?;
        }
        let message = ServerToClientMessage::ViewLinesCount { count, max };
        let message = serde_json::to_string(&message).unwrap();
        websocket.send(Message::Text(message))?;
        *ready_for_update = false;
        Ok(())
    }
    loop {
        match websocket.read()? {
            Message::Frame(_frame) => {}
            Message::Text(text) => {
                let message: ClientToServerMessage = serde_json::from_str(&text)?;
                let mut state = state.lock().unwrap();
                match message {
                    ClientToServerMessage::CheckForMoreData => {
                        send_update(
                            &mut websocket,
                            &mut state,
                            false,
                            &mut ready_for_update,
                            &mut update_skipped,
                        )?;
                    }
                    ClientToServerMessage::ViewRect { view_rect } => {
                        state.view_rect = view_rect;
                        send_update(
                            &mut websocket,
                            &mut state,
                            true,
                            &mut ready_for_update,
                            &mut update_skipped,
                        )?;
                    }
                    ClientToServerMessage::ViewMode { id, mode, inherit } => {
                        let (mode, sorted) = if let Some(mode) = mode.strip_suffix("-sorted") {
                            (mode, true)
                        } else {
                            (mode.as_str(), false)
                        };
                        match mode {
                            "raw-spans" => {
                                state.viewer.set_view_mode(
                                    id,
                                    Some((ViewMode::RawSpans { sorted }, inherit)),
                                );
                            }
                            "aggregated" => {
                                state.viewer.set_view_mode(
                                    id,
                                    Some((ViewMode::Aggregated { sorted }, inherit)),
                                );
                            }
                            "bottom-up" => {
                                state.viewer.set_view_mode(
                                    id,
                                    Some((ViewMode::BottomUp { sorted }, inherit)),
                                );
                            }
                            "aggregated-bottom-up" => {
                                state.viewer.set_view_mode(
                                    id,
                                    Some((ViewMode::AggregatedBottomUp { sorted }, inherit)),
                                );
                            }
                            _ => {
                                bail!("unknown view mode: {}", mode)
                            }
                        }
                        send_update(
                            &mut websocket,
                            &mut state,
                            true,
                            &mut ready_for_update,
                            &mut update_skipped,
                        )?;
                    }
                    ClientToServerMessage::ResetViewMode { id } => {
                        state.viewer.set_view_mode(id, None);
                        send_update(
                            &mut websocket,
                            &mut state,
                            true,
                            &mut ready_for_update,
                            &mut update_skipped,
                        )?;
                    }
                    ClientToServerMessage::Query { id } => {
                        let message = {
                            let store = state.store.read();
                            if let Some((span, is_graph)) = store.span(id) {
                                let root_start = store.root_span().start();
                                let span_start = span.start() - root_start;
                                let span_end = span.end() - root_start;
                                let duration = span.corrected_total_time();
                                let cpu = span.total_time();
                                let allocations = span.total_allocations();
                                let deallocations = span.total_deallocations();
                                let allocation_count = span.total_allocation_count();
                                let persistent_allocations = span.total_persistent_allocations();
                                let args = span
                                    .args()
                                    .map(|(k, v)| (k.to_string(), v.to_string()))
                                    .collect();
                                let mut path = Vec::new();
                                let mut current = span;
                                while let Some(parent) = current.parent() {
                                    path.push(parent.nice_name().1.to_string());
                                    current = parent;
                                }
                                path.reverse();
                                ServerToClientMessage::QueryResult {
                                    id,
                                    is_graph,
                                    start: span_start,
                                    end: span_end,
                                    duration,
                                    cpu,
                                    allocations,
                                    deallocations,
                                    allocation_count,
                                    persistent_allocations,
                                    args,
                                    path,
                                }
                            } else {
                                ServerToClientMessage::QueryResult {
                                    id,
                                    is_graph: false,
                                    start: Timestamp::ZERO,
                                    end: Timestamp::ZERO,
                                    duration: Timestamp::ZERO,
                                    cpu: Timestamp::ZERO,
                                    allocations: 0,
                                    deallocations: 0,
                                    allocation_count: 0,
                                    persistent_allocations: 0,
                                    args: Vec::new(),
                                    path: Vec::new(),
                                }
                            }
                        };
                        let message = serde_json::to_string(&message).unwrap();
                        websocket.send(Message::Text(message))?;
                        send_update(
                            &mut websocket,
                            &mut state,
                            true,
                            &mut ready_for_update,
                            &mut update_skipped,
                        )?;

                        continue;
                    }
                    ClientToServerMessage::Ack => {
                        ready_for_update = true;
                        if update_skipped {
                            update_skipped = false;
                            send_update(
                                &mut websocket,
                                &mut state,
                                true,
                                &mut ready_for_update,
                                &mut update_skipped,
                            )?;
                        }
                    }
                }
            }
            Message::Binary(_) => {
                // This doesn't happen
            }
            Message::Close(_) => {
                return Ok(());
            }
            Message::Ping(d) => {
                websocket.send(Message::Pong(d))?;
            }
            Message::Pong(_) => {
                // thanks for the fish
            }
        }
    }
}