/
resources.rs
327 lines (291 loc) · 9.6 KB
/
resources.rs
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
use crate::intern::{self, InternedStr};
use crate::state::{format_location, Field, Metadata, Visibility};
use crate::view;
use console_api as proto;
use std::{
cell::RefCell,
collections::HashMap,
convert::{TryFrom, TryInto},
rc::{Rc, Weak},
time::{Duration, SystemTime},
};
use tui::{
style::{Color, Modifier},
text::Span,
};
#[derive(Default, Debug)]
pub(crate) struct ResourcesState {
resources: HashMap<u64, Rc<RefCell<Resource>>>,
new_resources: Vec<ResourceRef>,
}
#[derive(Debug, Copy, Clone)]
#[repr(usize)]
pub(crate) enum SortBy {
Rid = 0,
Kind = 1,
ConcreteType = 2,
Target = 3,
Total = 4,
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub(crate) enum Kind {
Timer,
Other(InternedStr),
}
#[derive(Debug)]
pub(crate) struct Resource {
id: u64,
meta_id: u64,
kind: Kind,
stats: ResourceStats,
target: InternedStr,
concrete_type: InternedStr,
location: String,
}
pub(crate) type ResourceRef = Weak<RefCell<Resource>>;
#[derive(Debug)]
pub(crate) struct Attribute {
field: Field,
unit: Option<String>,
}
#[derive(Debug)]
struct ResourceStats {
created_at: SystemTime,
dropped_at: Option<SystemTime>,
total: Option<Duration>,
attributes: Vec<Attribute>,
formatted_attributes: Vec<Vec<Span<'static>>>,
}
impl Default for SortBy {
fn default() -> Self {
Self::Rid
}
}
impl SortBy {
pub fn sort(&self, now: SystemTime, resources: &mut Vec<Weak<RefCell<Resource>>>) {
match self {
Self::Rid => {
resources.sort_unstable_by_key(|resource| resource.upgrade().map(|r| r.borrow().id))
}
Self::Kind => resources.sort_unstable_by_key(|resource| {
resource.upgrade().map(|r| r.borrow().kind.clone())
}),
Self::ConcreteType => resources.sort_unstable_by_key(|resource| {
resource.upgrade().map(|r| r.borrow().concrete_type.clone())
}),
Self::Target => resources.sort_unstable_by_key(|resource| {
resource.upgrade().map(|r| r.borrow().target.clone())
}),
Self::Total => resources
.sort_unstable_by_key(|resource| resource.upgrade().map(|r| r.borrow().total(now))),
}
}
}
impl TryFrom<usize> for SortBy {
type Error = ();
fn try_from(idx: usize) -> Result<Self, Self::Error> {
match idx {
idx if idx == Self::Rid as usize => Ok(Self::Rid),
idx if idx == Self::Kind as usize => Ok(Self::Kind),
idx if idx == Self::ConcreteType as usize => Ok(Self::ConcreteType),
idx if idx == Self::Target as usize => Ok(Self::Target),
idx if idx == Self::Total as usize => Ok(Self::Total),
_ => Err(()),
}
}
}
impl view::SortBy for SortBy {
fn as_column(&self) -> usize {
*self as usize
}
}
impl ResourcesState {
pub(crate) fn take_new_resources(&mut self) -> impl Iterator<Item = ResourceRef> + '_ {
self.new_resources.drain(..)
}
pub(crate) fn update_resources(
&mut self,
styles: &view::Styles,
strings: &mut intern::Strings,
metas: &HashMap<u64, Metadata>,
update: proto::resources::ResourceUpdate,
visibility: Visibility,
) {
let mut stats_update = update.stats_update;
let new_list = &mut self.new_resources;
if matches!(visibility, Visibility::Show) {
new_list.clear();
}
let new_resources = update.new_resources.into_iter().filter_map(|resource| {
if resource.id.is_none() {
tracing::warn!(?resource, "skipping resource with no id");
}
let meta_id = match resource.metadata.as_ref() {
Some(id) => id.id,
None => {
tracing::warn!(?resource, "resource has no metadata ID, skipping");
return None;
}
};
let meta = match metas.get(&meta_id) {
Some(meta) => meta,
None => {
tracing::warn!(?resource, meta_id, "no metadata for resource, skipping");
return None;
}
};
let kind = match Kind::from_proto(resource.kind?, strings) {
Ok(kind) => kind,
Err(err) => {
tracing::warn!(%err, "resource kind cannot be parsed");
return None;
}
};
let id = resource.id?.id;
let stats = ResourceStats::from_proto(stats_update.remove(&id)?, meta, styles, strings);
let location = format_location(resource.location);
let resource = Resource {
id,
kind,
stats,
target: meta.target.clone(),
concrete_type: strings.string(resource.concrete_type),
meta_id,
location,
};
let resource = Rc::new(RefCell::new(resource));
new_list.push(Rc::downgrade(&resource));
Some((id, resource))
});
self.resources.extend(new_resources);
for (id, stats) in stats_update {
if let Some(resource) = self.resources.get_mut(&id) {
let mut r = resource.borrow_mut();
if let Some(meta) = metas.get(&r.meta_id) {
r.stats = ResourceStats::from_proto(stats, meta, styles, strings);
}
}
}
}
pub(crate) fn retain_active(&mut self, now: SystemTime, retain_for: Duration) {
self.resources.retain(|_, resource| {
let resource = resource.borrow();
resource
.stats
.dropped_at
.map(|d| {
let dropped_for = now.duration_since(d).unwrap();
retain_for > dropped_for
})
.unwrap_or(true)
})
}
}
impl Resource {
pub(crate) fn id(&self) -> u64 {
self.id
}
pub(crate) fn target(&self) -> &str {
&self.target
}
pub(crate) fn concrete_type(&self) -> &str {
&self.concrete_type
}
pub(crate) fn kind(&self) -> &str {
match &self.kind {
Kind::Timer => "Timer",
Kind::Other(other) => other,
}
}
pub(crate) fn formatted_attributes(&self) -> &[Vec<Span<'static>>] {
&self.stats.formatted_attributes
}
pub(crate) fn total(&self, since: SystemTime) -> Duration {
self.stats
.total
.unwrap_or_else(|| since.duration_since(self.stats.created_at).unwrap())
}
pub(crate) fn dropped(&self) -> bool {
self.stats.total.is_some()
}
pub(crate) fn location(&self) -> &str {
&self.location
}
}
impl ResourceStats {
fn from_proto(
pb: proto::resources::Stats,
meta: &Metadata,
styles: &view::Styles,
strings: &mut intern::Strings,
) -> Self {
let mut pb = pb;
let mut attributes = pb
.attributes
.drain(..)
.filter_map(|pb| {
let field = pb.field?;
let field = Field::from_proto(field, meta, strings)?;
Some(Attribute {
field,
unit: pb.unit,
})
})
.collect::<Vec<_>>();
let formatted_attributes = Attribute::make_formatted(styles, &mut attributes);
let created_at = pb
.created_at
.expect("resource span was never created")
.try_into()
.unwrap();
let dropped_at: Option<SystemTime> = pb.dropped_at.map(|v| v.try_into().unwrap());
let total = dropped_at.map(|d| d.duration_since(created_at).unwrap());
Self {
created_at,
dropped_at,
total,
attributes,
formatted_attributes,
}
}
}
impl Kind {
fn from_proto(
pb: proto::resources::resource::Kind,
strings: &mut intern::Strings,
) -> Result<Self, String> {
use proto::resources::resource::kind::Kind::Known as PbKnown;
use proto::resources::resource::kind::Kind::Other as PBOther;
use proto::resources::resource::kind::Known::Timer as PbTimer;
match pb.kind.expect("a resource should have a kind field") {
PbKnown(known) if known == (PbTimer as i32) => Ok(Kind::Timer),
PbKnown(known) => Err(format!("failed to parse known kind from {}", known)),
PBOther(other) => Ok(Kind::Other(strings.string(other))),
}
}
}
impl Attribute {
fn make_formatted(
styles: &view::Styles,
attributes: &mut Vec<Attribute>,
) -> Vec<Vec<Span<'static>>> {
let key_style = styles.fg(Color::LightBlue).add_modifier(Modifier::BOLD);
let delim_style = styles.fg(Color::LightBlue).add_modifier(Modifier::DIM);
let val_style = styles.fg(Color::Yellow);
let unit_style = styles.fg(Color::LightBlue);
let mut formatted = Vec::with_capacity(attributes.len());
let attributes = attributes.iter();
for attr in attributes {
let mut elems = vec![
Span::styled(attr.field.name.to_string(), key_style),
Span::styled("=", delim_style),
Span::styled(format!("{}", attr.field.value), val_style),
];
if let Some(unit) = &attr.unit {
elems.push(Span::styled(unit.clone(), unit_style))
}
formatted.push(elems)
}
formatted
}
}