engula_journal/
stream.rs

1// Copyright 2021 The Engula Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::convert::TryInto;
16
17use crate::{async_trait, Error, Result, ResultStream};
18
19/// A generic timestamp to order events.
20#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
21pub struct Timestamp(u64);
22
23impl Timestamp {
24    pub fn serialize(&self) -> Vec<u8> {
25        self.0.to_be_bytes().to_vec()
26    }
27
28    pub fn deserialize(bytes: Vec<u8>) -> Result<Self> {
29        let bytes: [u8; 8] = bytes
30            .try_into()
31            .map_err(|v| Error::Unknown(format!("malformed bytes: {:?}", v)))?;
32        Ok(Self(u64::from_be_bytes(bytes)))
33    }
34}
35
36impl From<u64> for Timestamp {
37    fn from(v: u64) -> Self {
38        Self(v)
39    }
40}
41
42#[derive(Clone, Debug, PartialEq)]
43pub struct Event {
44    pub ts: Timestamp,
45    pub data: Vec<u8>,
46}
47
48/// An interface to manipulate a stream.
49#[async_trait]
50pub trait Stream: Clone + Send + Sync + 'static {
51    /// Reads events since a timestamp (inclusive).
52    async fn read_events(&self, ts: Timestamp) -> ResultStream<Vec<Event>>;
53
54    /// Appends an event.
55    async fn append_event(&self, event: Event) -> Result<()>;
56
57    /// Releases events up to a timestamp (exclusive).
58    async fn release_events(&self, ts: Timestamp) -> Result<()>;
59}