1use std::sync::Arc;
16
17use arrow::array::{Array, Float64Array, UInt32Array};
18use snafu::OptionExt;
19
20use crate::error::{InvalidSeriesSnafu, Result};
21use crate::series::SeriesLabels;
22use crate::series::histogram::{HistogramBatch, HistogramView};
23use crate::series::time::{EvalGrid, TimeAxis};
24
25#[cfg(test)]
26mod tests;
27
28fn invalid<T>(reason: impl Into<String>) -> Result<T> {
29 Err(InvalidSeriesSnafu {
30 reason: reason.into(),
31 }
32 .build())
33}
34
35#[derive(Clone, Debug)]
37pub struct HistogramSamples {
38 indices: UInt32Array,
39 batch: Arc<HistogramBatch>,
40}
41impl HistogramSamples {
42 pub fn try_new(indices: UInt32Array, batch: Arc<HistogramBatch>) -> Result<Self> {
44 if indices.iter().flatten().any(|i| i as usize >= batch.len()) {
45 return invalid("histogram sample index is out of bounds");
46 }
47 Ok(Self { indices, batch })
48 }
49 pub fn indices(&self) -> &UInt32Array {
51 &self.indices
52 }
53 pub fn batch(&self) -> &Arc<HistogramBatch> {
55 &self.batch
56 }
57 pub fn len(&self) -> usize {
59 self.indices.len()
60 }
61 pub fn is_empty(&self) -> bool {
63 self.indices.is_empty()
64 }
65 pub fn view_at(&self, index: usize) -> Option<HistogramView<'_>> {
67 if index >= self.indices.len() {
68 return None;
69 }
70 if self.indices.is_valid(index) {
71 self.batch.view(self.indices.value(index) as usize)
72 } else {
73 None
74 }
75 }
76 fn slice(&self, offset: usize, len: usize) -> Self {
77 Self {
78 indices: self.indices.slice(offset, len),
79 batch: self.batch.clone(),
80 }
81 }
82}
83
84#[derive(Clone, Debug)]
86pub struct MixedSamples {
87 floats: Float64Array,
88 histograms: HistogramSamples,
89}
90impl MixedSamples {
91 pub fn floats(&self) -> &Float64Array {
93 &self.floats
94 }
95 pub fn histograms(&self) -> &HistogramSamples {
97 &self.histograms
98 }
99 pub fn len(&self) -> usize {
101 self.floats.len()
102 }
103 pub fn is_empty(&self) -> bool {
105 self.floats.is_empty()
106 }
107}
108
109#[derive(Clone, Debug)]
110enum SampleStorage {
111 Float(Float64Array),
112 Histogram(HistogramSamples),
113 Mixed(MixedSamples),
114 Chunks(Arc<[Samples]>, usize),
115}
116
117#[derive(Clone, Debug)]
119pub struct Samples {
120 storage: SampleStorage,
121}
122
123pub enum DenseSamplesRef<'a> {
125 Float(&'a Float64Array),
126 Histogram(&'a HistogramSamples),
127 Mixed(&'a MixedSamples),
128}
129
130pub enum SampleRef<'a> {
132 Missing,
133 Float(f64),
134 Histogram(HistogramView<'a>),
135}
136
137impl Samples {
138 pub fn from_float(values: Float64Array) -> Self {
140 Self {
141 storage: SampleStorage::Float(values),
142 }
143 }
144 pub fn try_from_histogram(indices: UInt32Array, batch: Arc<HistogramBatch>) -> Result<Self> {
146 Ok(Self {
147 storage: SampleStorage::Histogram(HistogramSamples::try_new(indices, batch)?),
148 })
149 }
150 pub fn try_from_mixed(floats: Float64Array, histograms: HistogramSamples) -> Result<Self> {
152 if floats.len() != histograms.len() {
153 return invalid("mixed sample arrays have unequal lengths");
154 }
155 if (0..floats.len()).any(|i| floats.is_valid(i) && histograms.indices.is_valid(i)) {
156 return invalid("mixed sample position has both float and histogram values");
157 }
158 Ok(Self {
159 storage: SampleStorage::Mixed(MixedSamples { floats, histograms }),
160 })
161 }
162 pub fn try_from_chunks(chunks: Vec<Samples>) -> Result<Self> {
164 let mut flat = Vec::new();
165 for chunk in chunks {
166 match chunk.storage {
167 SampleStorage::Chunks(parts, _) => flat.extend(parts.iter().cloned()),
168 _ => flat.push(chunk),
169 }
170 }
171 let total = flat
172 .iter()
173 .try_fold(0usize, |n, s| n.checked_add(s.len()))
174 .context(InvalidSeriesSnafu {
175 reason: "sample chunk length overflow",
176 })?;
177 flat.retain(|s| !s.is_empty());
178 if flat.is_empty() {
179 return Ok(Self::from_float(Float64Array::new_null(0)));
180 }
181 if flat.len() == 1 {
182 return flat.pop().ok_or_else(|| {
183 InvalidSeriesSnafu {
184 reason: "single sample chunk disappeared".to_string(),
185 }
186 .build()
187 });
188 }
189 Ok(Self {
190 storage: SampleStorage::Chunks(flat.into(), total),
191 })
192 }
193 pub fn segments(&self) -> &[Samples] {
228 match &self.storage {
229 SampleStorage::Chunks(chunks, _) => chunks,
230 _ => std::slice::from_ref(self),
231 }
232 }
233 pub fn len(&self) -> usize {
235 match &self.storage {
236 SampleStorage::Float(a) => a.len(),
237 SampleStorage::Histogram(a) => a.len(),
238 SampleStorage::Mixed(a) => a.len(),
239 SampleStorage::Chunks(_, len) => *len,
240 }
241 }
242 pub fn is_empty(&self) -> bool {
244 self.len() == 0
245 }
246 pub fn dense(&self) -> Option<DenseSamplesRef<'_>> {
248 match &self.storage {
249 SampleStorage::Float(a) => Some(DenseSamplesRef::Float(a)),
250 SampleStorage::Histogram(a) => Some(DenseSamplesRef::Histogram(a)),
251 SampleStorage::Mixed(a) => Some(DenseSamplesRef::Mixed(a)),
252 SampleStorage::Chunks(_, _) => None,
253 }
254 }
255 pub fn sample(&self, index: usize) -> SampleRef<'_> {
260 if index >= self.len() {
261 return SampleRef::Missing;
262 }
263 match &self.storage {
264 SampleStorage::Float(a) => {
265 if a.is_valid(index) {
266 SampleRef::Float(a.value(index))
267 } else {
268 SampleRef::Missing
269 }
270 }
271 SampleStorage::Histogram(a) => a
272 .view_at(index)
273 .map_or(SampleRef::Missing, SampleRef::Histogram),
274 SampleStorage::Mixed(a) => {
275 if a.floats.is_valid(index) {
276 SampleRef::Float(a.floats.value(index))
277 } else {
278 a.histograms
279 .view_at(index)
280 .map_or(SampleRef::Missing, SampleRef::Histogram)
281 }
282 }
283 SampleStorage::Chunks(chunks, _) => {
284 let mut i = index;
285 for part in chunks.iter() {
286 if i < part.len() {
287 return part.sample(i);
288 }
289 i -= part.len();
290 }
291 SampleRef::Missing
292 }
293 }
294 }
295 pub fn iter(&self) -> impl ExactSizeIterator<Item = SampleRef<'_>> + '_ {
297 let (chunks, remaining) = match &self.storage {
298 SampleStorage::Chunks(chunks, len) => (Some(chunks.as_ref()), *len),
299 _ => (None, self.len()),
300 };
301 SamplesIter {
302 samples: self,
303 chunks,
304 chunk_index: 0,
305 local_index: 0,
306 remaining,
307 }
308 }
309 pub fn cursor(&self) -> RowCursor<'_> {
311 let (chunks, remaining) = match &self.storage {
312 SampleStorage::Chunks(chunks, len) => (Some(chunks.as_ref()), *len),
313 _ => (None, self.len()),
314 };
315 RowCursor {
316 iter: SamplesIter {
317 samples: self,
318 chunks,
319 chunk_index: 0,
320 local_index: 0,
321 remaining,
322 },
323 row: 0,
324 }
325 }
326 pub fn slice(&self, offset: usize, len: usize) -> Result<Self> {
328 let end = offset.checked_add(len).context(InvalidSeriesSnafu {
329 reason: "sample slice bounds overflow",
330 })?;
331 if end > self.len() {
332 return invalid("sample slice is out of bounds");
333 }
334 match &self.storage {
335 SampleStorage::Float(a) => Ok(Self::from_float(a.slice(offset, len))),
336 SampleStorage::Histogram(a) => Ok(Self {
337 storage: SampleStorage::Histogram(a.slice(offset, len)),
338 }),
339 SampleStorage::Mixed(a) => Ok(Self {
340 storage: SampleStorage::Mixed(MixedSamples {
341 floats: a.floats.slice(offset, len),
342 histograms: a.histograms.slice(offset, len),
343 }),
344 }),
345 SampleStorage::Chunks(chunks, _) => {
346 let mut skip = offset;
347 let mut remain = len;
348 let mut out = Vec::new();
349 for chunk in chunks.iter() {
350 if skip >= chunk.len() {
351 skip -= chunk.len();
352 continue;
353 }
354 let take = remain.min(chunk.len() - skip);
355 if take != 0 {
356 out.push(chunk.slice(skip, take)?);
357 remain -= take;
358 }
359 skip = 0;
360 if remain == 0 {
361 break;
362 }
363 }
364 Self::try_from_chunks(out)
365 }
366 }
367 }
368}
369
370struct SamplesIter<'a> {
372 samples: &'a Samples,
373 chunks: Option<&'a [Samples]>,
374 chunk_index: usize,
375 local_index: usize,
376 remaining: usize,
377}
378impl<'a> Iterator for SamplesIter<'a> {
379 type Item = SampleRef<'a>;
380
381 fn next(&mut self) -> Option<Self::Item> {
382 if self.remaining == 0 {
383 return None;
384 }
385 self.remaining -= 1;
386 if let Some(chunks) = self.chunks {
387 while self.chunk_index < chunks.len()
388 && self.local_index == chunks[self.chunk_index].len()
389 {
390 self.chunk_index += 1;
391 self.local_index = 0;
392 }
393 let chunk = &chunks[self.chunk_index];
394 let value = chunk.sample(self.local_index);
395 self.local_index += 1;
396 Some(value)
397 } else {
398 let index = self.samples.len() - self.remaining - 1;
399 Some(self.samples.sample(index))
400 }
401 }
402
403 fn size_hint(&self) -> (usize, Option<usize>) {
404 (self.remaining, Some(self.remaining))
405 }
406}
407impl ExactSizeIterator for SamplesIter<'_> {
408 fn len(&self) -> usize {
409 self.remaining
410 }
411}
412
413pub struct RowCursor<'a> {
435 iter: SamplesIter<'a>,
436 row: usize,
438}
439impl<'a> RowCursor<'a> {
440 pub fn at(&mut self, row: usize) -> Option<SampleRef<'a>> {
446 if row < self.row {
447 return None;
448 }
449 if row - self.row >= self.iter.len() {
452 return None;
453 }
454 let sample = self.iter.nth(row - self.row)?;
455 self.row = row + 1;
456 Some(sample)
457 }
458}
459
460#[derive(Clone, Debug)]
461enum Fields {
462 One(Samples),
463 Many(Box<[Samples]>),
464}
465#[derive(Clone, Debug)]
467pub struct SeriesFields {
468 storage: Fields,
469}
470impl SeriesFields {
471 pub fn one(field: Samples) -> Self {
473 Self {
474 storage: Fields::One(field),
475 }
476 }
477 pub fn try_from_vec(fields: Vec<Samples>) -> Result<Self> {
479 if fields.is_empty() {
480 return invalid("series fields must not be empty");
481 }
482 if fields.iter().any(|f| f.len() != fields[0].len()) {
483 return invalid("series fields have unequal lengths");
484 }
485 Ok(if fields.len() == 1 {
486 let mut fields = fields.into_iter();
487 let field = fields.next().ok_or_else(|| {
488 InvalidSeriesSnafu {
489 reason: "single series field disappeared".to_string(),
490 }
491 .build()
492 })?;
493 Self::one(field)
494 } else {
495 Self {
496 storage: Fields::Many(fields.into_boxed_slice()),
497 }
498 })
499 }
500 pub fn as_slice(&self) -> &[Samples] {
502 match &self.storage {
503 Fields::One(f) => std::slice::from_ref(f),
504 Fields::Many(f) => f,
505 }
506 }
507 pub fn len(&self) -> usize {
509 self.as_slice().len()
510 }
511 pub fn is_empty(&self) -> bool {
513 false
514 }
515 pub fn get(&self, index: usize) -> Option<&Samples> {
517 self.as_slice().get(index)
518 }
519 pub fn iter(&self) -> std::slice::Iter<'_, Samples> {
521 self.as_slice().iter()
522 }
523}
524
525#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
527pub struct FieldSpec {
528 pub name: Arc<str>,
529}
530#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Hash, Eq)]
532pub struct SeriesSchema {
533 pub fields: Arc<[FieldSpec]>,
534 pub eval_grid: Option<Arc<EvalGrid>>,
536}
537#[derive(Clone, Debug)]
539pub struct Series {
540 pub metric: SeriesLabels,
541 pub time: TimeAxis,
542 pub fields: SeriesFields,
543}
544impl Series {
545 pub fn try_new(
547 schema: &SeriesSchema,
548 metric: SeriesLabels,
549 time: TimeAxis,
550 fields: SeriesFields,
551 ) -> Result<Self> {
552 if fields.len() != schema.fields.len() {
553 return invalid("series field count does not match schema");
554 }
555 let time_len = time.try_len()?;
556 if fields.iter().any(|f| f.len() != time_len) {
557 return invalid("series field length does not match time axis");
558 }
559 match (&schema.eval_grid, time.grid()) {
560 (Some(expected), Some(grid)) if expected.spec() == grid.spec() => {}
561 (Some(_), Some(_)) => {
562 return invalid("series grid does not match schema evaluation grid");
563 }
564 (Some(_), None) => {
565 return invalid("explicit series time axis cannot use an evaluation grid");
566 }
567 (None, Some(_)) => {
568 return invalid("grid series requires a schema evaluation grid");
569 }
570 (None, None) => {}
571 }
572 Ok(Self {
573 metric,
574 time,
575 fields,
576 })
577 }
578}