diff --git a/crates/izlek-core/src/detail.rs b/crates/izlek-core/src/detail.rs index 49d37e1..2bdb5e6 100644 --- a/crates/izlek-core/src/detail.rs +++ b/crates/izlek-core/src/detail.rs @@ -132,6 +132,7 @@ pub enum ActivityKind { Moved, Unblocked, Deleted, + Commented, /// A kind written by a newer version than the one reading it. The stored /// detail is shown as-is rather than dropping the row. Other(String), @@ -152,6 +153,7 @@ impl ActivityKind { ActivityKind::Moved => "moved", ActivityKind::Unblocked => "unblocked", ActivityKind::Deleted => "deleted", + ActivityKind::Commented => "commented", ActivityKind::Other(raw) => raw, } } @@ -170,6 +172,7 @@ impl ActivityKind { "moved" => ActivityKind::Moved, "unblocked" => ActivityKind::Unblocked, "deleted" => ActivityKind::Deleted, + "commented" => ActivityKind::Commented, other => ActivityKind::Other(other.to_string()), } } @@ -205,6 +208,7 @@ impl ActivityEntry { ActivityKind::Moved => format!("moved {detail}"), ActivityKind::Unblocked => format!("unblocked this task — {detail}"), ActivityKind::Deleted => "deleted this task".to_string(), + ActivityKind::Commented => "commented".to_string(), ActivityKind::Other(_) => detail.to_string(), } } diff --git a/crates/izlek-core/src/mail.rs b/crates/izlek-core/src/mail.rs index 8819e39..84d401e 100644 --- a/crates/izlek-core/src/mail.rs +++ b/crates/izlek-core/src/mail.rs @@ -611,6 +611,9 @@ impl Engine { "{} deleted {} — {}, the last task it was waiting on.", actor, freeing.cause_key, freeing.cause_title ), + // Not a wired path yet — S4's work — so this only needs to be + // exhaustive, not right. + (Event::Happened(_), _) => format!("{} touched it.", actor), }; let body = format!( "{key} — {title}\n\n{happened}\n\n{when}\n\n{base}/?task={id}\n", diff --git a/crates/izlek-core/src/store/mod.rs b/crates/izlek-core/src/store/mod.rs index 0564b5d..41b2aec 100644 --- a/crates/izlek-core/src/store/mod.rs +++ b/crates/izlek-core/src/store/mod.rs @@ -206,6 +206,23 @@ pub struct NewTask<'a> { pub created_by: &'a str, } +/// What `create_task` wrote: the task, and the id of the Created activity row +/// it filed alongside it, so a caller that needs to name the event — a mail +/// retry, one day — does not have to go read the trail back. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct TaskCreated { + pub row: TaskRow, + pub activity_id: String, +} + +/// What `add_comment` wrote: the comment's id, and the id of the Commented +/// activity row it filed alongside it in the same transaction. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CommentWritten { + pub comment_id: String, + pub activity_id: String, +} + /// What makes a rule fire. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum Trigger { @@ -406,7 +423,21 @@ pub struct Deletion { pub event: Option, } -/// The two things that can owe a mail. Both are committed facts with an id, an +/// One row of a task's activity trail, as an event a rule can fire on. Covers +/// everything `record_activity` writes that is not already its own event +/// shape — a comment today, whatever else `ActivityKind` grows later. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ActivityEvent { + pub id: String, + pub task_id: String, + pub board_id: String, + pub kind: ActivityKind, + pub actor_id: String, + pub detail: String, + pub at: OffsetDateTime, +} + +/// The things that can owe a mail. Each is a committed fact with an id, an /// actor and a moment, and a retry rebuilds its mail from whichever one the /// ledger row points at. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -415,6 +446,8 @@ pub enum Event { Moved(crate::board::Transition), /// A blocker was deleted and let something go. Freed(Freeing), + /// An activity row that is neither of the above — a comment, today. + Happened(ActivityEvent), } impl Event { @@ -422,6 +455,7 @@ impl Event { match self { Event::Moved(transition) => &transition.id, Event::Freed(freeing) => &freeing.id, + Event::Happened(activity) => &activity.id, } } @@ -431,6 +465,7 @@ impl Event { match self { Event::Moved(transition) => &transition.actor_id, Event::Freed(freeing) => &freeing.actor_id, + Event::Happened(activity) => &activity.actor_id, } } @@ -439,6 +474,7 @@ impl Event { match self { Event::Moved(transition) => transition.at, Event::Freed(freeing) => freeing.at, + Event::Happened(activity) => activity.at, } } } @@ -603,7 +639,7 @@ pub trait Store: BoardReads + DetailReads + 'static { /// Writes a task and hands it the next key on its board, in one /// transaction, so two writers cannot both take `DZ-14`. - async fn create_task(&self, new: NewTask<'_>) -> Result; + async fn create_task(&self, new: NewTask<'_>) -> Result; /// Idempotent: assigning someone twice is not an error. async fn assign_task(&self, task_id: &str, user_id: &str) -> Result<()>; @@ -631,14 +667,16 @@ pub trait Store: BoardReads + DetailReads + 'static { ) -> Result<()>; /// The author is the session's user, decided by the handler. There is no - /// author field on the form. + /// author field on the form. Writes the comment and its Commented + /// activity row in the same transaction, so one never exists without the + /// other. async fn add_comment( &self, task_id: &str, author_id: &str, body: &str, at: OffsetDateTime, - ) -> Result; + ) -> Result; /// Hangs a file off a task. The bytes go into the database file with the /// row: there is no second place for a Izlek deployment to keep, and no @@ -717,8 +755,8 @@ pub trait Store: BoardReads + DetailReads + 'static { /// only; nothing here writes. async fn deletion_cost(&self, task_id: &str) -> Result>; - /// Appends one line to a task's activity trail. `actor_id` is `None` when - /// the system did it rather than a person. + /// Appends one line to a task's activity trail and returns its row id. + /// `actor_id` is `None` when the system did it rather than a person. async fn record_activity( &self, task_id: &str, @@ -726,7 +764,7 @@ pub trait Store: BoardReads + DetailReads + 'static { kind: &ActivityKind, detail: &str, at: OffsetDateTime, - ) -> Result<()>; + ) -> Result; // -- mail rules -------------------------------------------------------- diff --git a/crates/izlek-core/src/store/turso_store.rs b/crates/izlek-core/src/store/turso_store.rs index 7a23638..265827b 100644 --- a/crates/izlek-core/src/store/turso_store.rs +++ b/crates/izlek-core/src/store/turso_store.rs @@ -15,9 +15,10 @@ use uuid::Uuid; use super::secret; use super::{ - ActivityLine, Attachment, Audience, Deletion, Event, Freeing, MailDecision, MailOutcome, - MailRule, MailSend, NewAttachment, NewSender, NewTask, NewUser, Recipient, Result, SendKind, - SendState, SenderTest, Session, SigninLink, Store, StoreError, Trigger, User, Workspace, + ActivityEvent, ActivityLine, Attachment, Audience, CommentWritten, Deletion, Event, Freeing, + MailDecision, MailOutcome, MailRule, MailSend, NewAttachment, NewSender, NewTask, NewUser, + Recipient, Result, SendKind, SendState, SenderTest, Session, SigninLink, Store, StoreError, + TaskCreated, Trigger, User, Workspace, }; use crate::Role; use crate::board::{BoardMeta, BoardReads, Column, Moved, Person, TaskRow, Transition}; @@ -1178,8 +1179,9 @@ impl Store for TursoStore { }) } - async fn create_task(&self, new: NewTask<'_>) -> Result { + async fn create_task(&self, new: NewTask<'_>) -> Result { let id = Uuid::new_v4().to_string(); + let activity_id = Uuid::new_v4().to_string(); let now = now_text()?; let deadline = new.deadline.map(day_text).transpose()?; @@ -1248,7 +1250,7 @@ impl Store for TursoStore { "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ VALUES (?1, ?2, ?3, ?4, '', ?5)", params![ - Uuid::new_v4().to_string(), + activity_id.clone(), id.clone(), new.created_by, ActivityKind::Created.as_str(), @@ -1274,14 +1276,17 @@ impl Store for TursoStore { tx.commit().await.map_err(backend)?; let (task_key, position) = written; - Ok(TaskRow { - id, - task_key, - title: new.title.to_string(), - column_id: new.column_id.to_string(), - deadline: new.deadline, - position, - done_at: None, + Ok(TaskCreated { + row: TaskRow { + id, + task_key, + title: new.title.to_string(), + column_id: new.column_id.to_string(), + deadline: new.deadline, + position, + done_at: None, + }, + activity_id, }) } @@ -1422,17 +1427,50 @@ impl Store for TursoStore { author_id: &str, body: &str, at: OffsetDateTime, - ) -> Result { - let id = Uuid::new_v4().to_string(); - self.conn - .execute( + ) -> Result { + let comment_id = Uuid::new_v4().to_string(); + let activity_id = Uuid::new_v4().to_string(); + let when = stamp(at)?; + + let mut conn = self.tx_conn().await?; + let tx = conn + .transaction_with_behavior(TransactionBehavior::Immediate) + .await + .map_err(backend)?; + + let written = async { + tx.execute( "INSERT INTO comment (id, task_id, author_id, body, created_at) \ VALUES (?1, ?2, ?3, ?4, ?5)", - params![id.clone(), task_id, author_id, body, stamp(at)?], + params![comment_id.clone(), task_id, author_id, body, when.clone()], ) - .await - .map_err(backend)?; - Ok(id) + .await?; + tx.execute( + "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ + VALUES (?1, ?2, ?3, ?4, '', ?5)", + params![ + activity_id.clone(), + task_id, + author_id, + ActivityKind::Commented.as_str(), + when.clone() + ], + ) + .await?; + Ok::<_, turso::Error>(()) + } + .await; + + if let Err(e) = written { + let _ = tx.rollback().await; + return Err(backend(e)); + } + tx.commit().await.map_err(backend)?; + + Ok(CommentWritten { + comment_id, + activity_id, + }) } async fn add_attachment(&self, new: NewAttachment<'_>) -> Result { @@ -2009,13 +2047,14 @@ impl Store for TursoStore { kind: &ActivityKind, detail: &str, at: OffsetDateTime, - ) -> Result<()> { + ) -> Result { + let id = Uuid::new_v4().to_string(); self.conn .execute( "INSERT INTO activity (id, task_id, actor_id, kind, detail, created_at) \ VALUES (?1, ?2, ?3, ?4, ?5, ?6)", params![ - Uuid::new_v4().to_string(), + id.clone(), task_id, actor_id, kind.as_str(), @@ -2025,7 +2064,7 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - Ok(()) + Ok(id) } // -- mail rules -------------------------------------------------------- @@ -2148,13 +2187,36 @@ impl Store for TursoStore { ) .await? { - Some(row) => Ok(Some(Event::Freed(Freeing { + Some(row) => { + return Ok(Some(Event::Freed(Freeing { + id: text(&row, 0)?, + board_id: text(&row, 1)?, + cause_key: text(&row, 2)?, + cause_title: text(&row, 3)?, + actor_id: text(&row, 4)?, + at: parse_stamp(&text(&row, 5)?)?, + }))); + } + None => {} + } + match self + .one_row( + "SELECT activity.id, activity.task_id, task.board_id, activity.kind, \ + activity.actor_id, activity.detail, activity.created_at \ + FROM activity JOIN task ON task.id = activity.task_id \ + WHERE activity.id = ?1", + params![event_id], + ) + .await? + { + Some(row) => Ok(Some(Event::Happened(ActivityEvent { id: text(&row, 0)?, - board_id: text(&row, 1)?, - cause_key: text(&row, 2)?, - cause_title: text(&row, 3)?, - actor_id: text(&row, 4)?, - at: parse_stamp(&text(&row, 5)?)?, + task_id: text(&row, 1)?, + board_id: text(&row, 2)?, + kind: ActivityKind::parse(&text(&row, 3)?), + actor_id: opt_text(&row, 4)?.unwrap_or_default(), + detail: text(&row, 5)?, + at: parse_stamp(&text(&row, 6)?)?, }))), None => Ok(None), } diff --git a/crates/izlek-core/tests/store.rs b/crates/izlek-core/tests/store.rs index 9d5aa3a..ab8abca 100644 --- a/crates/izlek-core/tests/store.rs +++ b/crates/izlek-core/tests/store.rs @@ -9,8 +9,8 @@ use std::path::PathBuf; use izlek_core::Role; use izlek_core::auth::{Token, hash_password}; use izlek_core::store::{ - Audience, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind, SendState, Store, - StoreError, Trigger, TursoStore, User, + Audience, Event, MailOutcome, MailRule, NewAttachment, NewSender, NewUser, SendKind, + SendState, Store, StoreError, Trigger, TursoStore, User, }; use time::{Duration, OffsetDateTime}; use uuid::Uuid; @@ -1869,6 +1869,7 @@ async fn add_task( }) .await .unwrap() + .row .id } @@ -2538,8 +2539,9 @@ async fn a_task_detail_costs_eight_queries_whatever_it_carries() { assert_eq!(detail.comments.len(), 20); assert_eq!(detail.assignees.len(), 20); assert_eq!(detail.blocks.len(), 20); - // Twenty moves plus the line create_task wrote. - assert_eq!(detail.activity.len(), 21); + // Twenty comments (each its own Commented line), twenty moves, plus the + // line create_task wrote. + assert_eq!(detail.activity.len(), 41); assert_eq!( counted.count(), 8, @@ -4381,3 +4383,61 @@ async fn the_activity_feed_is_the_whole_workspace_newest_first() { assert_eq!(feed[1].task_id, task_a); assert_eq!(feed[1].actor_name.as_deref(), Some("Ada")); } + +#[tokio::test] +async fn a_comment_leaves_one_activity_row_that_resolves_as_an_event() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let task = add_task(store, &workspace, "Backlog", "note me", None, &admin).await; + + let written = store + .add_comment(&task, &admin, "hello", OffsetDateTime::now_utc()) + .await + .unwrap(); + + let activity = store.activity_for_task(&task).await.unwrap(); + let commented: Vec<_> = activity + .iter() + .filter(|line| line.kind == ActivityKind::Commented) + .collect(); + assert_eq!(commented.len(), 1); + assert_eq!(commented[0].id, written.activity_id); + + match store.event(&written.activity_id).await.unwrap() { + Some(Event::Happened(event)) => { + assert_eq!(event.task_id, task); + assert_eq!(event.actor_id, admin); + assert_eq!(event.kind, ActivityKind::Commented); + } + other => panic!("expected Event::Happened, got {other:?}"), + } +} + +#[tokio::test] +async fn a_created_task_s_activity_id_resolves_as_an_event() { + let (scratch, workspace, admin) = workspace_with_admin().await; + let store = &scratch.store; + let board = store.board(&workspace).await.unwrap().unwrap(); + let column_id = column_named(store, &workspace, "Backlog").await; + + let created = store + .create_task(NewTask { + board_id: &board.id, + column_id: &column_id, + title: "brand new", + description: "", + deadline: None, + created_by: &admin, + }) + .await + .unwrap(); + + match store.event(&created.activity_id).await.unwrap() { + Some(Event::Happened(event)) => { + assert_eq!(event.task_id, created.row.id); + assert_eq!(event.actor_id, admin); + assert_eq!(event.kind, ActivityKind::Created); + } + other => panic!("expected Event::Happened, got {other:?}"), + } +} diff --git a/crates/izlek-web/src/logs.rs b/crates/izlek-web/src/logs.rs index 044d395..19dcb6f 100644 --- a/crates/izlek-web/src/logs.rs +++ b/crates/izlek-web/src/logs.rs @@ -100,6 +100,7 @@ fn activity_sentence(kind: &izlek_core::detail::ActivityKind, detail: &str) -> S ActivityKind::Moved => format!("moved {detail}"), ActivityKind::Unblocked => format!("unblocked this task — {detail}"), ActivityKind::Deleted => "deleted this task".to_string(), + ActivityKind::Commented => "commented".to_string(), ActivityKind::Other(_) => detail.to_string(), } } @@ -129,6 +130,9 @@ async fn event_happened( .map(|column| format!("moved to {}", column.name))) } Event::Freed(_) => Ok(Some("unblocked".to_string())), + // Not a wired path yet — S4's work — so this only needs to be + // exhaustive, not right. + Event::Happened(activity) => Ok(Some(activity.kind.as_str().to_string())), } }