1use std::sync::Arc;
2
3use crate::call_tree::CallTree;
4use crate::call_tree::CallTreeNode;
5use crate::properties::jsonb_dictionary::JsonbDictionary;
6use anyhow::{Context, Result};
7use datafusion::arrow::array::ArrayBuilder;
8use datafusion::arrow::array::PrimitiveBuilder;
9use datafusion::arrow::array::StringDictionaryBuilder;
10use datafusion::arrow::datatypes::DataType;
11use datafusion::arrow::datatypes::Field;
12use datafusion::arrow::datatypes::Int32Type;
13use datafusion::arrow::datatypes::Int64Type;
14use datafusion::arrow::datatypes::Schema;
15use datafusion::arrow::datatypes::TimeUnit;
16use datafusion::arrow::datatypes::TimestampNanosecondType;
17use datafusion::arrow::datatypes::UInt32Type;
18use datafusion::arrow::record_batch::RecordBatch;
19
20#[derive(Debug)]
22pub struct SpanRow {
23 pub id: i64,
24 pub parent: i64,
25 pub depth: u32,
26 pub begin: i64,
27 pub end: i64,
28 pub hash: u32,
29 pub name: Arc<String>,
30 pub target: Arc<String>,
31 pub filename: Arc<String>,
32 pub line: u32,
33}
34
35pub struct SpanRecordBuilder {
37 pub ids: PrimitiveBuilder<Int64Type>,
38 pub parents: PrimitiveBuilder<Int64Type>,
39 pub depths: PrimitiveBuilder<UInt32Type>,
40 pub hashes: PrimitiveBuilder<UInt32Type>,
41 pub begins: PrimitiveBuilder<TimestampNanosecondType>,
42 pub ends: PrimitiveBuilder<TimestampNanosecondType>,
43 pub durations: PrimitiveBuilder<Int64Type>,
44 pub names: StringDictionaryBuilder<Int32Type>,
45 pub targets: StringDictionaryBuilder<Int32Type>,
46 pub filenames: StringDictionaryBuilder<Int32Type>,
47 pub lines: PrimitiveBuilder<UInt32Type>,
48 property_sets: JsonbDictionary,
49 property_keys: Vec<i32>,
50}
51
52pub fn get_spans_schema() -> Schema {
54 Schema::new(vec![
55 Field::new("id", DataType::Int64, false),
56 Field::new("parent", DataType::Int64, false),
57 Field::new("depth", DataType::UInt32, false),
58 Field::new("hash", DataType::UInt32, false),
59 Field::new(
60 "begin",
61 DataType::Timestamp(TimeUnit::Nanosecond, Some("+00:00".into())),
62 false,
63 ),
64 Field::new(
65 "end",
66 DataType::Timestamp(TimeUnit::Nanosecond, Some("+00:00".into())),
67 false,
68 ),
69 Field::new("duration", DataType::Int64, false), Field::new(
71 "name",
72 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
73 false,
74 ),
75 Field::new(
76 "target",
77 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
78 false,
79 ),
80 Field::new(
81 "filename",
82 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
83 false,
84 ),
85 Field::new("line", DataType::UInt32, false),
86 Field::new(
87 "properties",
88 DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Binary)),
89 false,
90 ),
91 ])
92}
93
94impl SpanRecordBuilder {
95 pub fn with_capacity(capacity: usize) -> Self {
96 Self {
97 ids: PrimitiveBuilder::with_capacity(capacity),
98 parents: PrimitiveBuilder::with_capacity(capacity),
99 depths: PrimitiveBuilder::with_capacity(capacity),
100 hashes: PrimitiveBuilder::with_capacity(capacity),
101 begins: PrimitiveBuilder::with_capacity(capacity),
102 ends: PrimitiveBuilder::with_capacity(capacity),
103 durations: PrimitiveBuilder::with_capacity(capacity),
104 names: StringDictionaryBuilder::new(), targets: StringDictionaryBuilder::new(),
106 filenames: StringDictionaryBuilder::new(),
107 lines: PrimitiveBuilder::with_capacity(capacity),
108 property_sets: JsonbDictionary::new(),
109 property_keys: Vec::with_capacity(capacity),
110 }
111 }
112
113 pub fn len(&self) -> i64 {
114 self.ids.len() as i64
115 }
116
117 pub fn is_empty(&self) -> bool {
118 self.ids.len() == 0
119 }
120
121 pub fn append(&mut self, row: SpanRow, properties: &[u8]) -> Result<()> {
124 self.append_columns(row)?;
125 let key = self.property_sets.intern(properties);
126 self.property_keys.push(key);
127 Ok(())
128 }
129
130 fn append_columns(&mut self, row: SpanRow) -> Result<()> {
131 self.ids.append_value(row.id);
132 self.parents.append_value(row.parent);
133 self.depths.append_value(row.depth);
134 self.hashes.append_value(row.hash);
135 self.begins.append_value(row.begin);
136 self.ends.append_value(row.end);
137 self.durations.append_value(row.end - row.begin);
138 self.names.append(&*row.name)?;
139 self.targets.append(&*row.target)?;
140 self.filenames.append(&*row.filename)?;
141 self.lines.append_value(row.line);
142 Ok(())
143 }
144
145 pub fn append_call_tree(&mut self, tree: &CallTree) -> Result<()> {
146 if let Some(root) = &tree.call_tree_root {
147 let remap: Vec<i32> = tree
149 .property_sets
150 .values()
151 .iter()
152 .map(|jsonb| self.property_sets.intern(jsonb))
153 .collect();
154 for_each_node_in_tree(root, 0, 0, &mut |node, parent, depth| {
155 let scope_desc = tree
156 .scopes
157 .get(&node.hash)
158 .with_context(|| "fetching scope_desc from hash")?;
159 self.append_columns(SpanRow {
160 id: node.id.unwrap_or(-1),
161 parent,
162 depth,
163 begin: node.begin,
164 end: node.end,
165 hash: node.hash,
166 name: scope_desc.name.clone(),
167 target: scope_desc.target.clone(),
168 filename: scope_desc.filename.clone(),
169 line: scope_desc.line,
170 })?;
171 let key = *remap
172 .get(node.properties as usize)
173 .with_context(|| "fetching property set from index")?;
174 self.property_keys.push(key);
175 Ok(())
176 })?;
177 }
178 Ok(())
179 }
180
181 pub fn finish(mut self) -> Result<RecordBatch> {
182 let schema = get_spans_schema();
183 RecordBatch::try_new(
184 Arc::new(schema),
185 vec![
186 Arc::new(self.ids.finish()),
187 Arc::new(self.parents.finish()),
188 Arc::new(self.depths.finish()),
189 Arc::new(self.hashes.finish()),
190 Arc::new(self.begins.finish().with_timezone_utc()),
191 Arc::new(self.ends.finish().with_timezone_utc()),
192 Arc::new(self.durations.finish()),
193 Arc::new(self.names.finish()),
194 Arc::new(self.targets.finish()),
195 Arc::new(self.filenames.finish()),
196 Arc::new(self.lines.finish()),
197 Arc::new(self.property_sets.finish(self.property_keys)?),
198 ],
199 )
200 .with_context(|| "building record batch")
201 }
202}
203
204fn for_each_node_in_tree<NodeFun>(
205 node: &CallTreeNode,
206 parent: i64,
207 depth: u32,
208 process_node: &mut NodeFun,
209) -> Result<()>
210where
211 NodeFun: FnMut(&CallTreeNode, i64, u32) -> Result<()>,
212{
213 let mut pending = vec![(node, parent, depth)];
214 while let Some((node, parent, depth)) = pending.pop() {
215 process_node(node, parent, depth)?;
216 let span_id = node.id.unwrap_or(-1);
217 for child in node.children.iter().rev() {
219 pending.push((child, span_id, depth + 1));
220 }
221 }
222 Ok(())
223}