diff options
Diffstat (limited to 'src/message')
| -rw-r--r-- | src/message/app.rs | 16 | ||||
| -rw-r--r-- | src/message/repo.rs | 7 |
2 files changed, 14 insertions, 9 deletions
diff --git a/src/message/app.rs b/src/message/app.rs index 3c74628..9792c8f 100644 --- a/src/message/app.rs +++ b/src/message/app.rs @@ -29,13 +29,17 @@ impl<'a> Messages<'a> { sent_at: &DateTime, body: &Body, ) -> Result<Message, SendError> { + let to_not_found = || SendError::ChannelNotFound(channel.clone()); + let to_deleted = || SendError::ChannelDeleted(channel.clone()); + let mut tx = self.db.begin().await?; - let channel = tx - .channels() - .by_id(channel) - .await - .not_found(|| SendError::ChannelNotFound(channel.clone()))?; + let channel = tx.channels().by_id(channel).await.not_found(to_not_found)?; + + // Ordering: don't bother allocating a sequence number before we know the channel might + // exist. let sent = tx.sequence().next(sent_at).await?; + let channel = channel.as_of(sent).ok_or_else(to_deleted)?; + let message = tx.messages().create(&channel, sender, &sent, body).await?; tx.commit().await?; @@ -126,6 +130,8 @@ impl<'a> Messages<'a> { pub enum SendError { #[error("channel {0} not found")] ChannelNotFound(channel::Id), + #[error("channel {0} deleted")] + ChannelDeleted(channel::Id), #[error(transparent)] Database(#[from] sqlx::Error), #[error(transparent)] diff --git a/src/message/repo.rs b/src/message/repo.rs index 9a4f72f..e753134 100644 --- a/src/message/repo.rs +++ b/src/message/repo.rs @@ -2,7 +2,7 @@ use sqlx::{SqliteConnection, Transaction, sqlite::Sqlite}; use super::{Body, History, Id, snapshot::Message}; use crate::{ - channel, + channel::{self, Channel}, clock::DateTime, event::{Instant, Sequence}, user::{self, User}, @@ -23,13 +23,12 @@ pub struct Messages<'t>(&'t mut SqliteConnection); impl Messages<'_> { pub async fn create( &mut self, - channel: &channel::History, + channel: &Channel, sender: &User, sent: &Instant, body: &Body, ) -> Result<History, sqlx::Error> { let id = Id::generate(); - let channel_id = channel.id(); let message = sqlx::query!( r#" @@ -45,7 +44,7 @@ impl Messages<'_> { body as "body: Body" "#, id, - channel_id, + channel.id, sender.id, sent.at, sent.sequence, |
