metrique_writer_core/stream.rs
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Contains the [EntryIoStream] trait, which writes entries to a destination
5//! synchronously.
6
7use std::{fmt, io};
8
9use crate::{Entry, ValidationError};
10
11/// The error cases for a [`EntryIoStream::next`] call.
12#[derive(Debug)]
13pub enum IoStreamError {
14 /// Validation error with the metric
15 Validation(ValidationError),
16 /// I/O error
17 Io(io::Error),
18}
19
20impl fmt::Display for IoStreamError {
21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 match self {
23 Self::Validation(err) => fmt::Display::fmt(err, f),
24 Self::Io(err) => fmt::Display::fmt(err, f),
25 }
26 }
27}
28
29impl std::error::Error for IoStreamError {}
30
31impl From<io::Error> for IoStreamError {
32 fn from(value: io::Error) -> Self {
33 Self::Io(value)
34 }
35}
36
37impl From<ValidationError> for IoStreamError {
38 fn from(value: ValidationError) -> Self {
39 Self::Validation(value)
40 }
41}
42
43/// Writes a stream of [entries](`Entry`) to an output IO sink.
44///
45/// The `EntryIoStream` is normally used to create an [`EntrySink`] - the [`EntrySink`]
46/// takes the `entry` by value, which allows managing a queueing policy.
47///
48/// An `EntryIoStream` is generally generated by coupling a [`Format`] with some output,
49/// generally by calling the `output_to` or `output_to_makewriter` method
50/// on `FormatExt`, and possibly afterwards merging globals
51/// (via `EntryIoStreamExt::merge_globals`), merging dimensions
52/// (via `EntryIoStreamExt::merge_global_dimensions`), or
53/// using `FormatExt::tee` to emit output to several places.
54///
55/// Of course, if you have custom needs, it might be worth implementing this trait yourself.
56///
57/// Flushing may occur at any time, but is required to happen when [`EntryIoStream::flush`] is called.
58///
59/// [`EntrySink`]: crate::EntrySink
60/// [`Format`]: crate::format::Format
61pub trait EntryIoStream {
62 /// Write the next [`Entry`] to the stream.
63 ///
64 /// If an [`IoStreamError::Io`] occurs, the result of the following call is undefined.
65 fn next(&mut self, entry: &impl Entry) -> Result<(), IoStreamError>;
66
67 /// Flush any pending entries that have been written to a buffer before the final IO sink.
68 ///
69 /// Note that some writers rely on regular flush
70 /// calls to interleave IO operations that won't tear across entries.
71 fn flush(&mut self) -> io::Result<()>;
72}