use core::{future::Future, hash::Hash};
use smol_bytes::Utf8Bytes;
use super::journal::Ledger;
#[derive(Debug, Clone, PartialEq, Eq, Hash, derive_more::Display)]
#[display("{node}/{source}")]
pub struct Track {
node: Utf8Bytes,
source: Utf8Bytes,
}
impl Track {
#[inline]
pub fn new(node: impl Into<Utf8Bytes>, source: impl Into<Utf8Bytes>) -> Self {
Self {
node: node.into(),
source: source.into(),
}
}
#[inline]
#[must_use]
pub fn node(&self) -> &str {
&self.node
}
#[inline]
#[must_use]
pub fn source(&self) -> &str {
&self.source
}
}
pub trait Positions<K>: Ledger {
fn position(&mut self, track: &Track) -> Result<Option<K>, Self::Error>;
fn position_async(
&mut self,
track: &Track,
) -> impl Future<Output = Result<Option<K>, Self::Error>> + Send;
fn advance(&mut self, track: &Track, to: K, journal: &[Self::Row]) -> Result<(), Self::Error>;
fn advance_async(
&mut self,
track: &Track,
to: K,
journal: &[Self::Row],
) -> impl Future<Output = Result<(), Self::Error>> + Send;
}
#[derive(Debug)]
pub struct RecordedPositions<K> {
rows: std::collections::HashMap<Track, K>,
}
impl<K> RecordedPositions<K> {
#[inline]
#[must_use]
pub fn new() -> Self {
Self {
rows: std::collections::HashMap::new(),
}
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.rows.len()
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.rows.is_empty()
}
}
impl<K> Default for RecordedPositions<K> {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<K> Ledger for RecordedPositions<K>
where
K: Send,
{
type Error = core::convert::Infallible;
type Row = ();
#[inline]
fn record(&mut self, _rows: &[()]) -> Result<(), Self::Error> {
Ok(())
}
#[inline]
async fn record_async(&mut self, _rows: &[()]) -> Result<(), Self::Error> {
Ok(())
}
}
impl<K> Positions<K> for RecordedPositions<K>
where
K: Clone + Send + Sync,
{
#[inline]
fn position(&mut self, track: &Track) -> Result<Option<K>, Self::Error> {
Ok(self.rows.get(track).cloned())
}
#[inline]
async fn position_async(&mut self, track: &Track) -> Result<Option<K>, Self::Error> {
self.position(track)
}
#[inline]
fn advance(&mut self, track: &Track, to: K, _journal: &[()]) -> Result<(), Self::Error> {
self.rows.insert(track.clone(), to);
Ok(())
}
#[inline]
async fn advance_async(
&mut self,
track: &Track,
to: K,
journal: &[()],
) -> Result<(), Self::Error> {
self.advance(track, to, journal)
}
}
#[cfg(feature = "sqlite")]
#[derive(Debug)]
pub struct SqlitePositions {
conn: sqlx::SqliteConnection,
}
#[cfg(feature = "sqlite")]
impl SqlitePositions {
pub const TABLE: &'static str = "ingraph_position";
pub async fn open(mut conn: sqlx::SqliteConnection) -> Result<Self, SqlitePositionsError> {
use sqlx::Executor as _;
conn
.execute(
"CREATE TABLE IF NOT EXISTS ingraph_position (\
unit TEXT NOT NULL, \
source TEXT NOT NULL, \
position INTEGER NOT NULL, \
PRIMARY KEY (unit, source)\
) WITHOUT ROWID",
)
.await
.map_err(SqlitePositionsError)?;
Ok(Self { conn })
}
#[inline]
#[must_use]
pub fn into_connection(self) -> sqlx::SqliteConnection {
self.conn
}
}
#[cfg(feature = "sqlite")]
#[derive(Debug, derive_more::Display)]
#[display("the positions table refused a statement: {_0}")]
pub struct SqlitePositionsError(sqlx::Error);
#[cfg(feature = "sqlite")]
impl core::error::Error for SqlitePositionsError {
#[inline]
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
Some(&self.0)
}
}
#[cfg(feature = "sqlite")]
impl Ledger for SqlitePositions {
type Error = SqlitePositionsError;
type Row = ();
#[inline]
fn record(&mut self, _rows: &[()]) -> Result<(), Self::Error> {
Ok(())
}
#[inline]
async fn record_async(&mut self, _rows: &[()]) -> Result<(), Self::Error> {
Ok(())
}
}
#[cfg(feature = "sqlite")]
impl Positions<i64> for SqlitePositions {
#[inline]
fn position(&mut self, track: &Track) -> Result<Option<i64>, Self::Error> {
super::lane::block_on(self.position_async(track))
}
async fn position_async(&mut self, track: &Track) -> Result<Option<i64>, Self::Error> {
use sqlx::Row as _;
let row = sqlx::query("SELECT position FROM ingraph_position WHERE unit = ? AND source = ?")
.bind(track.node())
.bind(track.source())
.fetch_optional(&mut self.conn)
.await
.map_err(SqlitePositionsError)?;
row
.map(|row| row.try_get::<i64, _>(0))
.transpose()
.map_err(SqlitePositionsError)
}
#[inline]
fn advance(&mut self, track: &Track, to: i64, journal: &[()]) -> Result<(), Self::Error> {
super::lane::block_on(self.advance_async(track, to, journal))
}
async fn advance_async(
&mut self,
track: &Track,
to: i64,
_journal: &[()],
) -> Result<(), Self::Error> {
sqlx::query(
"INSERT INTO ingraph_position (unit, source, position) VALUES (?, ?, ?) \
ON CONFLICT (unit, source) DO UPDATE SET position = excluded.position",
)
.bind(track.node())
.bind(track.source())
.bind(to)
.execute(&mut self.conn)
.await
.map_err(SqlitePositionsError)?;
Ok(())
}
}
pub trait PositionKey: Clone + Eq + Hash + Send + Sync {}
impl<K> PositionKey for K where K: Clone + Eq + Hash + Send + Sync {}
#[cfg(test)]
mod tests;