diff --git a/crates/forge-core/src/audit.rs b/crates/forge-core/src/audit.rs index 66b2a03..a372a29 100644 --- a/crates/forge-core/src/audit.rs +++ b/crates/forge-core/src/audit.rs @@ -73,17 +73,6 @@ audit_actions! { CiRunnerConfigChanged => "ci_runner_config_changed", CiRegistrationTokenCreated => "ci_registration_token_created", UiPrefsChanged => "ui_prefs_changed", - DiscussionsEnabled => "discussions_enabled", - DiscussionsDisabled => "discussions_disabled", - DiscussionCreated => "discussion_created", - DiscussionEdited => "discussion_edited", - DiscussionDeleted => "discussion_deleted", - DiscussionLocked => "discussion_locked", - DiscussionUnlocked => "discussion_unlocked", - DiscussionAnswered => "discussion_answered", - DiscussionCommentCreated => "discussion_comment_created", - DiscussionCommentEdited => "discussion_comment_edited", - DiscussionCommentDeleted => "discussion_comment_deleted", MailSettingsUpdated => "mail_settings_updated", MailTestQueued => "mail_test_queued", ServerSettingsUpdated => "server_settings_updated", diff --git a/crates/forge-core/src/discussions.rs b/crates/forge-core/src/discussions.rs deleted file mode 100644 index a2e5133..0000000 --- a/crates/forge-core/src/discussions.rs +++ /dev/null @@ -1,114 +0,0 @@ -use crate::error::{Error, Result}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DiscussionCategory { - General, - Ideas, - Qa, - Announcements, -} - -pub const DISCUSSION_CATEGORIES: &[DiscussionCategory] = &[ - DiscussionCategory::General, - DiscussionCategory::Ideas, - DiscussionCategory::Qa, - DiscussionCategory::Announcements, -]; - -string_enum!(DiscussionCategory { - General = "general", - Ideas = "ideas", - Qa = "qa", - Announcements = "announcements", -}); - -impl DiscussionCategory { - pub fn label(self) -> &'static str { - match self { - DiscussionCategory::General => "General", - DiscussionCategory::Ideas => "Ideas", - DiscussionCategory::Qa => "Q&A", - DiscussionCategory::Announcements => "Announcements", - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Discussion { - pub id: String, - pub repo_id: String, - pub number: i64, - pub category: DiscussionCategory, - pub title: String, - pub body: String, - pub author_id: String, - pub answer_comment_id: Option, - pub locked: bool, - pub comment_count: i64, - pub created_at: String, - pub updated_at: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DiscussionListItem { - pub discussion: Discussion, - pub author: String, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum DiscussionReason { - Mention, - Reply, -} - -string_enum!(DiscussionReason { - Mention = "mention", - Reply = "reply", -}); - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DiscussionNotification { - pub discussion_id: String, - pub repo_id: String, - pub repo_owner: String, - pub repo_name: String, - pub number: i64, - pub title: String, - pub reason: DiscussionReason, - pub last_actor_name: Option, - pub unread: bool, - pub updated_at: String, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DiscussionComment { - pub id: String, - pub discussion_id: String, - pub parent_id: Option, - pub author_id: String, - pub body: String, - pub created_at: String, - pub updated_at: String, - pub deleted: bool, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DiscussionFilter { - pub category: Option, - pub page: u32, - pub per_page: u32, -} - -pub fn validate_discussion(title: &str, body: &str) -> Result { - let title = crate::issues::validate_title(title)?; - crate::issues::validate_body(body)?; - Ok(title) -} - -pub fn validate_comment(body: &str) -> Result<()> { - crate::issues::validate_body(body)?; - if body.trim().is_empty() { - return Err(Error::Invalid("comment is empty".into())); - } - Ok(()) -} diff --git a/crates/forge-core/src/lib.rs b/crates/forge-core/src/lib.rs index a9ebdb8..797bb7d 100644 --- a/crates/forge-core/src/lib.rs +++ b/crates/forge-core/src/lib.rs @@ -30,7 +30,6 @@ pub mod authz; pub mod avatar; pub mod ci; pub mod config; -pub mod discussions; pub mod error; pub mod issue_refs; pub mod issues; diff --git a/crates/forge-core/src/reactions.rs b/crates/forge-core/src/reactions.rs index d54ca3b..b6112a9 100644 --- a/crates/forge-core/src/reactions.rs +++ b/crates/forge-core/src/reactions.rs @@ -53,15 +53,11 @@ string_enum!(Reaction { pub enum ReactionTarget { Issue, Comment, - Discussion, - DiscussionComment, } string_enum!(ReactionTarget { Issue = "issue", Comment = "comment", - Discussion = "discussion", - DiscussionComment = "discussion_comment", }); #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/forge-core/src/store/discussions.rs b/crates/forge-core/src/store/discussions.rs deleted file mode 100644 index 6ed14d5..0000000 --- a/crates/forge-core/src/store/discussions.rs +++ /dev/null @@ -1,1240 +0,0 @@ -use turso::transaction::Transaction; -use turso::{Connection, Row, Value}; - -use super::finish; -use super::issues::parse_db; -use super::{ - Store, col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, insert_err, new_id, -}; -use crate::discussions::{ - Discussion, DiscussionCategory, DiscussionComment, DiscussionFilter, DiscussionListItem, - DiscussionNotification, validate_comment, validate_discussion, -}; -use crate::error::{Error, Result}; -use crate::time::now_stamp; - -const DISCUSSION_COLS: &str = "d.id, d.repo_id, d.number, d.category, d.title, d.body, \ - d.author_id, d.answer_comment_id, d.locked, d.comment_count, d.created_at, d.updated_at"; -const COMMENT_COLS: &str = "c.id, c.discussion_id, c.parent_id, c.author_id, c.body, \ - c.created_at, c.updated_at, c.deleted_at"; - -fn map_discussion(row: &Row) -> Result { - let category = col_text(row, 3)?; - Ok(Discussion { - id: col_text(row, 0)?, - repo_id: col_text(row, 1)?, - number: col_int(row, 2)?, - category: parse_db(&category)?, - title: col_text(row, 4)?, - body: col_text(row, 5)?, - author_id: col_text(row, 6)?, - answer_comment_id: col_opt_text(row, 7)?, - locked: col_int(row, 8)? != 0, - comment_count: col_int(row, 9)?, - created_at: col_text(row, 10)?, - updated_at: col_text(row, 11)?, - }) -} - -const DISCUSSION_NOTE_SELECT: &str = "SELECT n.discussion_id, n.repo_id, o.username, r.name, \ - d.number, d.title, n.reason, a.username, n.unread, n.updated_at FROM discussion_notifications n \ - JOIN discussions d ON d.id = n.discussion_id \ - JOIN repos r ON r.id = n.repo_id \ - JOIN users o ON o.id = r.owner_id \ - LEFT JOIN users a ON a.id = n.last_actor_id"; - -fn map_discussion_note(row: &Row) -> Result { - let reason = col_text(row, 6)?; - Ok(DiscussionNotification { - discussion_id: col_text(row, 0)?, - repo_id: col_text(row, 1)?, - repo_owner: col_text(row, 2)?, - repo_name: col_text(row, 3)?, - number: col_int(row, 4)?, - title: col_text(row, 5)?, - reason: parse_db(&reason)?, - last_actor_name: col_opt_text(row, 7)?, - unread: col_int(row, 8)? != 0, - updated_at: col_text(row, 9)?, - }) -} - -fn map_comment(row: &Row) -> Result { - Ok(DiscussionComment { - id: col_text(row, 0)?, - discussion_id: col_text(row, 1)?, - parent_id: col_opt_text(row, 2)?, - author_id: col_text(row, 3)?, - body: col_text(row, 4)?, - created_at: col_text(row, 5)?, - updated_at: col_text(row, 6)?, - deleted: col_opt_text(row, 7)?.is_some(), - }) -} - -async fn discussion_row(conn: &Connection, discussion_id: &str) -> Result { - fetch_opt( - conn, - &format!("SELECT {DISCUSSION_COLS} FROM discussions d WHERE d.id = ?1 LIMIT 1"), - (discussion_id.to_string(),), - map_discussion, - ) - .await? - .ok_or(Error::NotFound) -} - -pub(super) async fn delete_repo_discussion_rows(tx: &Transaction<'_>, repo_id: &str) -> Result<()> { - let id = repo_id.to_string(); - for sql in [ - "DELETE FROM reactions WHERE target_kind = 'discussion_comment' AND target_id IN \ - (SELECT c.id FROM discussion_comments c JOIN discussions d ON d.id = c.discussion_id \ - WHERE d.repo_id = ?1)", - "DELETE FROM reactions WHERE target_kind = 'discussion' AND target_id IN \ - (SELECT id FROM discussions WHERE repo_id = ?1)", - "DELETE FROM discussion_notifications WHERE repo_id = ?1", - "DELETE FROM discussion_comments WHERE discussion_id IN \ - (SELECT id FROM discussions WHERE repo_id = ?1)", - "DELETE FROM discussions WHERE repo_id = ?1", - ] { - tx.execute(sql, (id.clone(),)).await.map_err(db_err)?; - } - Ok(()) -} - -impl Store { - pub async fn discussions_enabled(&self, repo_id: &str) -> Result { - let conn = self.read_conn().await; - let flag = fetch_opt( - &conn, - "SELECT discussions_enabled FROM repos WHERE id = ?1 LIMIT 1", - (repo_id.to_string(),), - |row| col_int(row, 0), - ) - .await? - .ok_or(Error::NotFound)?; - Ok(flag != 0) - } - - pub async fn set_discussions_enabled(&self, repo_id: &str, enabled: bool) -> Result<()> { - let conn = self.inner.conn.lock().await; - let changed = conn - .execute( - "UPDATE repos SET discussions_enabled = ?2 WHERE id = ?1", - (repo_id.to_string(), i64::from(enabled)), - ) - .await - .map_err(db_err)?; - if changed == 0 { - return Err(Error::NotFound); - } - Ok(()) - } - - pub async fn create_discussion( - &self, - repo_id: &str, - author_id: &str, - category: DiscussionCategory, - title: &str, - body: &str, - ) -> Result { - let title = validate_discussion(title, body)?; - let conn = self.inner.conn.lock().await; - let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let outcome: Result = async { - let number = fetch_opt( - &tx, - "SELECT next_issue_number FROM repos WHERE id = ?1 LIMIT 1", - (repo_id.to_string(),), - |row| col_int(row, 0), - ) - .await? - .ok_or(Error::NotFound)?; - let now = now_stamp(); - let id = new_id(); - tx.execute( - "INSERT INTO discussions (id, repo_id, number, category, title, body, author_id, \ - locked, comment_count, created_at, updated_at) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 0, 0, ?8, ?8)", - ( - id.clone(), - repo_id.to_string(), - number, - category.as_str().to_string(), - title.clone(), - body.to_string(), - author_id.to_string(), - now.clone(), - ), - ) - .await - .map_err(|e| insert_err(e, "discussion number already taken"))?; - tx.execute( - "UPDATE repos SET next_issue_number = next_issue_number + 1 WHERE id = ?1", - (repo_id.to_string(),), - ) - .await - .map_err(db_err)?; - Ok(Discussion { - id, - repo_id: repo_id.to_string(), - number, - category, - title, - body: body.to_string(), - author_id: author_id.to_string(), - answer_comment_id: None, - locked: false, - comment_count: 0, - created_at: now.clone(), - updated_at: now, - }) - } - .await; - finish(tx, outcome).await - } - - pub async fn discussion_by_number( - &self, - repo_id: &str, - number: i64, - ) -> Result> { - let conn = self.read_conn().await; - fetch_opt( - &conn, - &format!( - "SELECT {DISCUSSION_COLS} FROM discussions d WHERE d.repo_id = ?1 AND d.number = ?2 \ - LIMIT 1" - ), - (repo_id.to_string(), number), - map_discussion, - ) - .await - } - - pub async fn list_discussions( - &self, - repo_id: &str, - f: &DiscussionFilter, - ) -> Result<(Vec, u64)> { - let mut clauses: Vec<&str> = vec!["d.repo_id = ?"]; - let mut params: Vec = vec![Value::Text(repo_id.to_string())]; - if let Some(category) = f.category { - clauses.push("d.category = ?"); - params.push(Value::Text(category.as_str().to_string())); - } - let where_sql = clauses.join(" AND "); - let per_page = f.per_page.clamp(1, 100); - let page = f.page.clamp(1, 1000); - let offset = i64::from(page - 1) * i64::from(per_page); - - let conn = self.read_conn().await; - let total = fetch_opt( - &conn, - &format!("SELECT COUNT(*) FROM discussions d WHERE {where_sql}"), - params.clone(), - |row| col_int(row, 0), - ) - .await? - .unwrap_or(0); - - let mut page_params = params; - page_params.push(Value::Integer(i64::from(per_page))); - page_params.push(Value::Integer(offset)); - let items = fetch_all( - &conn, - &format!( - "SELECT {DISCUSSION_COLS}, u.username FROM discussions d \ - JOIN users u ON u.id = d.author_id WHERE {where_sql} \ - ORDER BY d.updated_at DESC, d.number DESC LIMIT ? OFFSET ?" - ), - page_params, - |row| { - Ok(DiscussionListItem { - discussion: map_discussion(row)?, - author: col_text(row, 12)?, - }) - }, - ) - .await?; - Ok((items, u64::try_from(total).unwrap_or(0))) - } - - pub async fn edit_discussion( - &self, - discussion_id: &str, - title: &str, - body: &str, - ) -> Result<()> { - let title = validate_discussion(title, body)?; - let conn = self.inner.conn.lock().await; - let changed = conn - .execute( - "UPDATE discussions SET title = ?2, body = ?3, updated_at = ?4 WHERE id = ?1", - ( - discussion_id.to_string(), - title, - body.to_string(), - now_stamp(), - ), - ) - .await - .map_err(db_err)?; - if changed == 0 { - return Err(Error::NotFound); - } - Ok(()) - } - - pub async fn set_discussion_locked(&self, discussion_id: &str, locked: bool) -> Result { - let conn = self.inner.conn.lock().await; - let changed = conn - .execute( - "UPDATE discussions SET locked = ?2 WHERE id = ?1 AND locked != ?2", - (discussion_id.to_string(), i64::from(locked)), - ) - .await - .map_err(db_err)?; - if changed > 0 { - return Ok(true); - } - discussion_row(&conn, discussion_id).await?; - Ok(false) - } - - pub async fn set_discussion_answer( - &self, - discussion_id: &str, - comment_id: Option<&str>, - ) -> Result<()> { - let conn = self.inner.conn.lock().await; - let discussion = discussion_row(&conn, discussion_id).await?; - if discussion.category != DiscussionCategory::Qa { - return Err(Error::Invalid("only Q&A discussions have an answer".into())); - } - if let Some(comment_id) = comment_id { - let live = fetch_opt( - &conn, - "SELECT 1 FROM discussion_comments WHERE id = ?1 AND discussion_id = ?2 \ - AND deleted_at IS NULL LIMIT 1", - (comment_id.to_string(), discussion_id.to_string()), - |row| col_int(row, 0), - ) - .await?; - if live.is_none() { - return Err(Error::Invalid( - "the answer must be a comment on this discussion".into(), - )); - } - } - conn.execute( - "UPDATE discussions SET answer_comment_id = ?2 WHERE id = ?1", - (discussion_id.to_string(), comment_id.map(str::to_string)), - ) - .await - .map_err(db_err)?; - Ok(()) - } - - pub async fn delete_discussion(&self, discussion_id: &str) -> Result<()> { - let conn = self.inner.conn.lock().await; - let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let outcome: Result<()> = async { - discussion_row(&tx, discussion_id).await?; - let id = discussion_id.to_string(); - for sql in [ - "DELETE FROM reactions WHERE target_kind = 'discussion_comment' AND target_id IN \ - (SELECT id FROM discussion_comments WHERE discussion_id = ?1)", - "DELETE FROM reactions WHERE target_kind = 'discussion' AND target_id = ?1", - "DELETE FROM discussion_notifications WHERE discussion_id = ?1", - "DELETE FROM discussion_comments WHERE discussion_id = ?1", - "DELETE FROM discussions WHERE id = ?1", - ] { - tx.execute(sql, (id.clone(),)).await.map_err(db_err)?; - } - Ok(()) - } - .await; - finish(tx, outcome).await - } - - pub async fn add_discussion_comment( - &self, - discussion_id: &str, - author_id: &str, - parent_id: Option<&str>, - body: &str, - triage: bool, - ) -> Result { - validate_comment(body)?; - let conn = self.inner.conn.lock().await; - let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let outcome: Result = async { - let discussion = discussion_row(&tx, discussion_id).await?; - if discussion.locked && !triage { - return Err(Error::Forbidden("this discussion is locked".into())); - } - if let Some(parent) = parent_id { - let row = fetch_opt( - &tx, - &format!( - "SELECT {COMMENT_COLS} FROM discussion_comments c WHERE c.id = ?1 LIMIT 1" - ), - (parent.to_string(),), - map_comment, - ) - .await? - .ok_or(Error::NotFound)?; - if row.discussion_id != discussion_id { - return Err(Error::NotFound); - } - if row.parent_id.is_some() { - return Err(Error::Invalid("replies nest one level only".into())); - } - if row.deleted { - return Err(Error::Invalid("this comment was deleted".into())); - } - } - let now = now_stamp(); - let comment = DiscussionComment { - id: new_id(), - discussion_id: discussion_id.to_string(), - parent_id: parent_id.map(str::to_string), - author_id: author_id.to_string(), - body: body.to_string(), - created_at: now.clone(), - updated_at: now.clone(), - deleted: false, - }; - tx.execute( - "INSERT INTO discussion_comments (id, discussion_id, parent_id, author_id, body, \ - created_at, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)", - ( - comment.id.clone(), - comment.discussion_id.clone(), - comment.parent_id.clone(), - comment.author_id.clone(), - comment.body.clone(), - now.clone(), - ), - ) - .await - .map_err(db_err)?; - tx.execute( - "UPDATE discussions SET comment_count = comment_count + 1, updated_at = ?2 \ - WHERE id = ?1", - (discussion_id.to_string(), now.clone()), - ) - .await - .map_err(db_err)?; - if discussion.author_id != author_id { - upsert_discussion_notification( - &tx, - &discussion.author_id, - &discussion.repo_id, - discussion_id, - "reply", - author_id, - &now, - ) - .await?; - } - Ok(comment) - } - .await; - finish(tx, outcome).await - } - - pub async fn discussion_comment( - &self, - discussion_id: &str, - comment_id: &str, - ) -> Result> { - let conn = self.read_conn().await; - fetch_opt( - &conn, - &format!( - "SELECT {COMMENT_COLS} FROM discussion_comments c WHERE c.id = ?1 \ - AND c.discussion_id = ?2 LIMIT 1" - ), - (comment_id.to_string(), discussion_id.to_string()), - map_comment, - ) - .await - } - - pub async fn edit_discussion_comment(&self, comment_id: &str, body: &str) -> Result<()> { - validate_comment(body)?; - let conn = self.inner.conn.lock().await; - let changed = conn - .execute( - "UPDATE discussion_comments SET body = ?2, updated_at = ?3 \ - WHERE id = ?1 AND deleted_at IS NULL", - (comment_id.to_string(), body.to_string(), now_stamp()), - ) - .await - .map_err(db_err)?; - if changed == 0 { - return Err(Error::NotFound); - } - Ok(()) - } - - pub async fn delete_discussion_comment(&self, comment_id: &str) -> Result<()> { - let conn = self.inner.conn.lock().await; - let tx = conn.unchecked_transaction().await.map_err(db_err)?; - let outcome: Result<()> = async { - let comment = fetch_opt( - &tx, - &format!("SELECT {COMMENT_COLS} FROM discussion_comments c WHERE c.id = ?1 LIMIT 1"), - (comment_id.to_string(),), - map_comment, - ) - .await? - .ok_or(Error::NotFound)?; - if comment.deleted { - return Ok(()); - } - let now = now_stamp(); - tx.execute( - "UPDATE discussion_comments SET body = '', deleted_at = ?2, updated_at = ?2 \ - WHERE id = ?1", - (comment_id.to_string(), now.clone()), - ) - .await - .map_err(db_err)?; - tx.execute( - "DELETE FROM reactions WHERE target_kind = 'discussion_comment' AND target_id = ?1", - (comment_id.to_string(),), - ) - .await - .map_err(db_err)?; - tx.execute( - "UPDATE discussions SET comment_count = CASE WHEN comment_count > 0 \ - THEN comment_count - 1 ELSE 0 END, updated_at = ?2 WHERE id = ?1", - (comment.discussion_id.clone(), now), - ) - .await - .map_err(db_err)?; - tx.execute( - "UPDATE discussions SET answer_comment_id = NULL WHERE id = ?1 AND answer_comment_id = ?2", - (comment.discussion_id, comment_id.to_string()), - ) - .await - .map_err(db_err)?; - Ok(()) - } - .await; - finish(tx, outcome).await - } - - pub async fn list_discussion_comments( - &self, - discussion_id: &str, - ) -> Result> { - let conn = self.read_conn().await; - fetch_all( - &conn, - &format!( - "SELECT {COMMENT_COLS} FROM discussion_comments c WHERE c.discussion_id = ?1 \ - ORDER BY c.created_at, c.id" - ), - (discussion_id.to_string(),), - map_comment, - ) - .await - } - - pub async fn record_discussion_mentions( - &self, - repo_id: &str, - discussion_id: &str, - actor_id: &str, - user_ids: &[String], - ) -> Result<()> { - if user_ids.is_empty() { - return Ok(()); - } - let conn = self.inner.conn.lock().await; - let now = now_stamp(); - for user_id in user_ids { - upsert_discussion_notification( - &conn, - user_id, - repo_id, - discussion_id, - "mention", - actor_id, - &now, - ) - .await?; - } - Ok(()) - } - - pub async fn unread_discussion_mentions(&self, user_id: &str) -> Result> { - let conn = self.read_conn().await; - fetch_all( - &conn, - "SELECT discussion_id, repo_id FROM discussion_notifications \ - WHERE user_id = ?1 AND unread = 1 ORDER BY updated_at DESC", - (user_id.to_string(),), - |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), - ) - .await - } - - pub async fn list_discussion_notifications( - &self, - user_id: &str, - unread_only: bool, - before: Option<&str>, - limit: u32, - ) -> Result> { - let mut sql = format!("{DISCUSSION_NOTE_SELECT} WHERE n.user_id = ?"); - let mut params = vec![Value::Text(user_id.to_string())]; - if unread_only { - sql.push_str(" AND n.unread = 1"); - } - if let Some(stamp) = before { - sql.push_str(" AND n.updated_at < ?"); - params.push(Value::Text(stamp.to_string())); - } - sql.push_str(" ORDER BY n.updated_at DESC, n.discussion_id DESC LIMIT ?"); - params.push(Value::Integer(i64::from(limit.clamp(1, 200)))); - let conn = self.read_conn().await; - fetch_all(&conn, &sql, params, map_discussion_note).await - } - - pub async fn discussion_notification( - &self, - user_id: &str, - discussion_id: &str, - ) -> Result> { - let conn = self.read_conn().await; - fetch_opt( - &conn, - &format!( - "{DISCUSSION_NOTE_SELECT} WHERE n.user_id = ?1 AND n.discussion_id = ?2 LIMIT 1" - ), - (user_id.to_string(), discussion_id.to_string()), - map_discussion_note, - ) - .await - } - - pub async fn mark_discussion_notification_read( - &self, - user_id: &str, - discussion_id: &str, - ) -> Result<()> { - let conn = self.inner.conn.lock().await; - conn.execute( - "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND discussion_id = ?2", - (user_id.to_string(), discussion_id.to_string()), - ) - .await - .map_err(db_err)?; - Ok(()) - } - - pub async fn mark_all_discussion_notifications_read( - &self, - user_id: &str, - repo_id: Option<&str>, - ) -> Result<()> { - let conn = self.inner.conn.lock().await; - conn.execute( - "UPDATE discussion_notifications SET unread = 0 WHERE user_id = ?1 AND unread = 1 \ - AND (?2 IS NULL OR repo_id = ?2)", - (user_id.to_string(), repo_id.map(str::to_string)), - ) - .await - .map_err(db_err)?; - Ok(()) - } -} - -async fn upsert_discussion_notification( - conn: &Connection, - user_id: &str, - repo_id: &str, - discussion_id: &str, - reason: &str, - actor_id: &str, - now: &str, -) -> Result<()> { - conn.execute( - "INSERT INTO discussion_notifications (user_id, discussion_id, repo_id, reason, \ - last_actor_id, unread, updated_at) VALUES (?1, ?2, ?3, ?4, ?5, 1, ?6) \ - ON CONFLICT (user_id, discussion_id) DO UPDATE SET \ - reason = CASE WHEN excluded.reason = 'mention' OR discussion_notifications.reason = 'mention' \ - THEN 'mention' ELSE 'reply' END, last_actor_id = excluded.last_actor_id, unread = 1, \ - updated_at = excluded.updated_at", - ( - user_id.to_string(), - discussion_id.to_string(), - repo_id.to_string(), - reason.to_string(), - actor_id.to_string(), - now.to_string(), - ), - ) - .await - .map_err(db_err)?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::discussions::DiscussionReason; - use crate::model::{User, Visibility}; - - struct Fixture { - store: Store, - tahinli: User, - bob: User, - repo_id: String, - _dir: tempfile::TempDir, - } - - async fn fixture() -> Fixture { - let dir = tempfile::tempdir().unwrap(); - let store = Store::open(&dir.path().join("forge.db")).await.unwrap(); - let tahinli = store - .create_user("Tahinli", None, "hash", false) - .await - .unwrap(); - let bob = store.create_user("Bob", None, "hash", false).await.unwrap(); - let repo = store - .create_repo(&tahinli.id, "proj", "", Visibility::Public, "main") - .await - .unwrap(); - Fixture { - store, - tahinli, - bob, - repo_id: repo.id, - _dir: dir, - } - } - - fn filter(category: Option) -> DiscussionFilter { - DiscussionFilter { - category, - page: 1, - per_page: 25, - } - } - - async fn fresh_repo(store: &Store, owner: &str, name: &str) -> String { - store - .create_repo(owner, name, "", Visibility::Public, "main") - .await - .unwrap() - .id - } - - #[tokio::test] - async fn repo_level_rules_hold_in_each_scenario() { - let fx = fixture().await; - - let repo = fresh_repo(&fx.store, &fx.tahinli.id, "toggle").await; - assert!( - !fx.store.discussions_enabled(&repo).await.unwrap(), - "toggle: off by default" - ); - fx.store.set_discussions_enabled(&repo, true).await.unwrap(); - assert!( - fx.store.discussions_enabled(&repo).await.unwrap(), - "toggle: on after enabling" - ); - assert!( - matches!( - fx.store.set_discussions_enabled("missing", true).await, - Err(Error::NotFound) - ), - "toggle: unknown repo" - ); - - let repo = fresh_repo(&fx.store, &fx.tahinli.id, "numbers").await; - let issue = fx - .store - .create_issue(&repo, &fx.tahinli.id, "first", "") - .await - .unwrap(); - let d1 = fx - .store - .create_discussion(&repo, &fx.tahinli.id, DiscussionCategory::General, "a", "") - .await - .unwrap(); - let issue2 = fx - .store - .create_issue(&repo, &fx.tahinli.id, "second", "") - .await - .unwrap(); - assert_eq!(issue.number, 1, "numbers: first issue"); - assert_eq!(d1.number, 2, "numbers: discussion takes the next slot"); - assert_eq!(issue2.number, 3, "numbers: second issue"); - let found = fx.store.discussion_by_number(&repo, 2).await.unwrap(); - assert_eq!( - found.map(|d| d.title), - Some("a".to_string()), - "numbers: lookup by number" - ); - - let repo = fresh_repo(&fx.store, &fx.tahinli.id, "categories").await; - assert!( - matches!( - fx.store - .create_discussion(&repo, &fx.tahinli.id, DiscussionCategory::Ideas, " ", "") - .await, - Err(Error::Invalid(_)) - ), - "categories: blank title refused" - ); - fx.store - .create_discussion(&repo, &fx.tahinli.id, DiscussionCategory::Ideas, "idea", "") - .await - .unwrap(); - fx.store - .create_discussion(&repo, &fx.bob.id, DiscussionCategory::Qa, "question", "") - .await - .unwrap(); - let (all, total) = fx - .store - .list_discussions(&repo, &filter(None)) - .await - .unwrap(); - assert_eq!((all.len(), total), (2, 2), "categories: unfiltered list"); - let (qa, total) = fx - .store - .list_discussions(&repo, &filter(Some(DiscussionCategory::Qa))) - .await - .unwrap(); - assert_eq!(total, 1, "categories: qa total"); - assert_eq!(qa[0].discussion.title, "question", "categories: qa title"); - assert_eq!(qa[0].author, "Bob", "categories: qa author"); - } - - #[tokio::test] - async fn thread_rules_hold_in_each_scenario() { - let fx = fixture().await; - - let d = fx - .store - .create_discussion( - &fx.repo_id, - &fx.tahinli.id, - DiscussionCategory::General, - "t", - "", - ) - .await - .unwrap(); - let top = fx - .store - .add_discussion_comment(&d.id, &fx.bob.id, None, "hello", false) - .await - .unwrap(); - let reply = fx - .store - .add_discussion_comment(&d.id, &fx.tahinli.id, Some(&top.id), "hi back", false) - .await - .unwrap(); - assert_eq!( - reply.parent_id.as_deref(), - Some(top.id.as_str()), - "nesting: reply points at its parent" - ); - let nested = fx - .store - .add_discussion_comment(&d.id, &fx.bob.id, Some(&reply.id), "too deep", false) - .await; - assert!( - matches!(nested, Err(Error::Invalid(_))), - "nesting: too deep" - ); - assert!( - matches!( - fx.store - .add_discussion_comment(&d.id, &fx.bob.id, None, " ", false) - .await, - Err(Error::Invalid(_)) - ), - "nesting: blank body" - ); - let stored = fx - .store - .discussion_by_number(&fx.repo_id, d.number) - .await - .unwrap(); - assert_eq!( - stored.map(|d| d.comment_count), - Some(2), - "nesting: comment count" - ); - let all = fx.store.list_discussion_comments(&d.id).await.unwrap(); - assert_eq!(all.len(), 2, "nesting: listed comments"); - - let qa = fx - .store - .create_discussion(&fx.repo_id, &fx.tahinli.id, DiscussionCategory::Qa, "q", "") - .await - .unwrap(); - let general = fx - .store - .create_discussion( - &fx.repo_id, - &fx.tahinli.id, - DiscussionCategory::General, - "g", - "", - ) - .await - .unwrap(); - let c = fx - .store - .add_discussion_comment(&qa.id, &fx.bob.id, None, "answer", false) - .await - .unwrap(); - let g = fx - .store - .add_discussion_comment(&general.id, &fx.bob.id, None, "x", false) - .await - .unwrap(); - assert!( - matches!( - fx.store - .set_discussion_answer(&general.id, Some(&g.id)) - .await, - Err(Error::Invalid(_)) - ), - "answer: refused outside Q&A" - ); - assert!( - matches!( - fx.store.set_discussion_answer(&qa.id, Some(&g.id)).await, - Err(Error::Invalid(_)) - ), - "answer: refused for a comment of another discussion" - ); - fx.store - .set_discussion_answer(&qa.id, Some(&c.id)) - .await - .unwrap(); - let stored = fx - .store - .discussion_by_number(&fx.repo_id, qa.number) - .await - .unwrap(); - assert_eq!( - stored.and_then(|d| d.answer_comment_id), - Some(c.id.clone()), - "answer: accepted" - ); - fx.store.delete_discussion_comment(&c.id).await.unwrap(); - let stored = fx - .store - .discussion_by_number(&fx.repo_id, qa.number) - .await - .unwrap(); - assert_eq!( - stored.and_then(|d| d.answer_comment_id), - None, - "answer: cleared when the comment is deleted" - ); - - let d = fx - .store - .create_discussion( - &fx.repo_id, - &fx.tahinli.id, - DiscussionCategory::General, - "t", - "", - ) - .await - .unwrap(); - let top = fx - .store - .add_discussion_comment(&d.id, &fx.bob.id, None, "gone soon", false) - .await - .unwrap(); - fx.store - .add_discussion_comment(&d.id, &fx.tahinli.id, Some(&top.id), "reply stays", false) - .await - .unwrap(); - assert!( - fx.store.set_discussion_locked(&d.id, true).await.unwrap(), - "lock: first change reported" - ); - assert!( - !fx.store.set_discussion_locked(&d.id, true).await.unwrap(), - "lock: repeat is no change" - ); - assert!( - matches!( - fx.store.set_discussion_locked("missing", true).await, - Err(Error::NotFound) - ), - "lock: unknown discussion" - ); - fx.store.delete_discussion_comment(&top.id).await.unwrap(); - let gone = fx - .store - .discussion_comment(&d.id, &top.id) - .await - .unwrap() - .unwrap(); - assert!(gone.deleted, "lock: parent tombstoned"); - assert!(gone.body.is_empty(), "lock: parent body cleared"); - let all = fx.store.list_discussion_comments(&d.id).await.unwrap(); - assert_eq!(all.len(), 2, "lock: tombstone and reply both listed"); - assert!( - all.iter().any(|c| c.body == "reply stays" && !c.deleted), - "lock: reply survives" - ); - - let d = fx - .store - .create_discussion( - &fx.repo_id, - &fx.tahinli.id, - DiscussionCategory::Ideas, - "old", - "body", - ) - .await - .unwrap(); - fx.store - .edit_discussion(&d.id, "new", "changed") - .await - .unwrap(); - let edited = fx - .store - .discussion_by_number(&fx.repo_id, d.number) - .await - .unwrap(); - assert_eq!( - edited.map(|d| d.title), - Some("new".to_string()), - "edit: title updated" - ); - fx.store - .add_discussion_comment(&d.id, &fx.bob.id, None, "c", false) - .await - .unwrap(); - fx.store.delete_discussion(&d.id).await.unwrap(); - assert!( - fx.store - .discussion_by_number(&fx.repo_id, d.number) - .await - .unwrap() - .is_none(), - "delete: discussion gone" - ); - assert!( - fx.store - .list_discussion_comments(&d.id) - .await - .unwrap() - .is_empty(), - "delete: comments gone" - ); - assert!( - matches!( - fx.store.delete_discussion(&d.id).await, - Err(Error::NotFound) - ), - "delete: second delete is not found" - ); - - let d = fx - .store - .create_discussion( - &fx.repo_id, - &fx.tahinli.id, - DiscussionCategory::General, - "t", - "", - ) - .await - .unwrap(); - fx.store.set_discussion_locked(&d.id, true).await.unwrap(); - let refused = fx - .store - .add_discussion_comment(&d.id, &fx.bob.id, None, "hi", false) - .await; - assert!( - matches!(refused, Err(Error::Forbidden(_))), - "locked: plain comment refused" - ); - let stored = fx - .store - .discussion_by_number(&fx.repo_id, d.number) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.comment_count, 0, "locked: nothing was stored"); - fx.store - .add_discussion_comment(&d.id, &fx.bob.id, None, "maintainer note", true) - .await - .unwrap(); - fx.store.set_discussion_locked(&d.id, false).await.unwrap(); - fx.store - .add_discussion_comment(&d.id, &fx.bob.id, None, "open again", false) - .await - .unwrap(); - } - - #[tokio::test] - async fn inbox_rules_hold_in_each_scenario() { - let fx = fixture().await; - - let ana = fx - .store - .create_user("Ana", None, "hash", false) - .await - .unwrap(); - let ben = fx - .store - .create_user("Ben", None, "hash", false) - .await - .unwrap(); - let repo = fresh_repo(&fx.store, &ana.id, "mentions").await; - let d = fx - .store - .create_discussion(&repo, &ana.id, DiscussionCategory::General, "t", "") - .await - .unwrap(); - for _ in 0..2 { - fx.store - .record_discussion_mentions(&repo, &d.id, &ana.id, std::slice::from_ref(&ben.id)) - .await - .unwrap(); - } - let rows = fx.store.unread_discussion_mentions(&ben.id).await.unwrap(); - assert_eq!( - rows, - vec![(d.id.clone(), repo.clone())], - "mentions: one row after repeats" - ); - assert!( - fx.store - .unread_discussion_mentions(&ana.id) - .await - .unwrap() - .is_empty(), - "mentions: author is not mentioned" - ); - - let cora = fx - .store - .create_user("Cora", None, "hash", false) - .await - .unwrap(); - let dev = fx - .store - .create_user("Dev", None, "hash", false) - .await - .unwrap(); - let repo = fresh_repo(&fx.store, &cora.id, "replies").await; - let d = fx - .store - .create_discussion(&repo, &cora.id, DiscussionCategory::Qa, "Q", "") - .await - .unwrap(); - fx.store - .add_discussion_comment(&d.id, &dev.id, None, "answer", false) - .await - .unwrap(); - fx.store - .add_discussion_comment(&d.id, &cora.id, None, "thanks", false) - .await - .unwrap(); - let rows = fx - .store - .list_discussion_notifications(&cora.id, true, None, 50) - .await - .unwrap(); - assert_eq!(rows.len(), 1, "replies: one row"); - assert_eq!(rows[0].reason, DiscussionReason::Reply, "replies: reason"); - assert_eq!(rows[0].title, "Q", "replies: title"); - assert_eq!(rows[0].number, d.number, "replies: number"); - assert_eq!(rows[0].repo_owner, "Cora", "replies: owner"); - assert_eq!( - rows[0].last_actor_name.as_deref(), - Some("Dev"), - "replies: last actor" - ); - - fx.store - .record_discussion_mentions(&repo, &d.id, &dev.id, std::slice::from_ref(&cora.id)) - .await - .unwrap(); - fx.store - .add_discussion_comment(&d.id, &dev.id, None, "again", false) - .await - .unwrap(); - let rows = fx - .store - .list_discussion_notifications(&cora.id, true, None, 50) - .await - .unwrap(); - assert_eq!(rows.len(), 1, "upgrade: still one row"); - assert_eq!( - rows[0].reason, - DiscussionReason::Mention, - "upgrade: mention wins" - ); - assert_eq!( - fx.store.unread_count(&cora.id).await.unwrap(), - 1, - "upgrade: unread count" - ); - - fx.store - .mark_discussion_notification_read(&dev.id, &d.id) - .await - .unwrap(); - assert_eq!( - fx.store.unread_count(&cora.id).await.unwrap(), - 1, - "mark-read: other user is ignored" - ); - fx.store - .mark_all_discussion_notifications_read(&cora.id, Some(&repo)) - .await - .unwrap(); - assert_eq!( - fx.store.unread_count(&cora.id).await.unwrap(), - 0, - "mark-read: cleared" - ); - assert!( - fx.store - .list_discussion_notifications(&cora.id, true, None, 50) - .await - .unwrap() - .is_empty(), - "mark-read: no unread rows" - ); - let all = fx - .store - .list_discussion_notifications(&cora.id, false, None, 50) - .await - .unwrap(); - assert_eq!(all.len(), 1, "mark-read: read rows still listed"); - assert!(!all[0].unread, "mark-read: row is read"); - assert!( - fx.store - .discussion_notification(&dev.id, &d.id) - .await - .unwrap() - .is_none(), - "mark-read: no row for the commenter" - ); - } -} diff --git a/crates/forge-core/src/store/mod.rs b/crates/forge-core/src/store/mod.rs index 8fc543a..0ad6c18 100644 --- a/crates/forge-core/src/store/mod.rs +++ b/crates/forge-core/src/store/mod.rs @@ -6,7 +6,6 @@ pub mod backup_runs; pub mod ci; pub mod commit_status; pub mod contributions; -pub mod discussions; pub mod edit_history_read; pub mod exports; pub mod health; @@ -1174,7 +1173,6 @@ impl Store { reviews::delete_repo_review_rows(&tx, &id).await?; pulls::delete_repo_pull_rows(&tx, &id).await?; issues::delete_repo_issue_rows(&tx, &id).await?; - discussions::delete_repo_discussion_rows(&tx, &id).await?; releases::delete_repo_release_rows(&tx, &id).await?; for sql in [ "DELETE FROM webhook_deliveries WHERE hook_id IN (SELECT id FROM webhooks WHERE repo_id = ?1)", diff --git a/crates/forge-core/src/store/notifications.rs b/crates/forge-core/src/store/notifications.rs index 94f1938..7b5bc93 100644 --- a/crates/forge-core/src/store/notifications.rs +++ b/crates/forge-core/src/store/notifications.rs @@ -347,16 +347,11 @@ impl Store { let readable = readable_repo(); let sql = format!( "SELECT (SELECT COUNT(*) FROM notifications n JOIN repos r ON r.id = n.repo_id \ - WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ - (SELECT COUNT(*) FROM discussion_notifications n JOIN repos r ON r.id = n.repo_id \ WHERE n.user_id = ? AND n.unread = 1 AND {readable}) + \ (SELECT COUNT(*) FROM admin_notifications WHERE user_id = ? AND unread = 1)" ); - let mut params = Vec::new(); - for _ in 0..2 { - params.push(Value::Text(user_id.to_string())); - params.extend(readable_params(user_id)); - } + let mut params = vec![Value::Text(user_id.to_string())]; + params.extend(readable_params(user_id)); params.push(Value::Text(user_id.to_string())); let conn = self.read_conn().await; let n = fetch_opt(&conn, &sql, params, |row| col_int(row, 0)) diff --git a/crates/forge-core/src/store/reactions.rs b/crates/forge-core/src/store/reactions.rs index 1045821..75fb5bd 100644 --- a/crates/forge-core/src/store/reactions.rs +++ b/crates/forge-core/src/store/reactions.rs @@ -21,10 +21,6 @@ impl Store { let exists_sql = match kind { ReactionTarget::Issue => "SELECT 1 FROM issues WHERE id = ?1 LIMIT 1", ReactionTarget::Comment => "SELECT 1 FROM comments WHERE id = ?1 LIMIT 1", - ReactionTarget::Discussion => "SELECT 1 FROM discussions WHERE id = ?1 LIMIT 1", - ReactionTarget::DiscussionComment => { - "SELECT 1 FROM discussion_comments WHERE id = ?1 AND deleted_at IS NULL LIMIT 1" - } }; if fetch_opt(&tx, exists_sql, (target_id.to_string(),), |row| { col_int(row, 0) diff --git a/crates/forge-core/src/store/user_delete.rs b/crates/forge-core/src/store/user_delete.rs index adc9553..56970ad 100644 --- a/crates/forge-core/src/store/user_delete.rs +++ b/crates/forge-core/src/store/user_delete.rs @@ -76,19 +76,6 @@ const REASSIGNED: &[(&str, &str, &str, &str)] = &[ "last_actor_id", " AND user_id <> ?1", ), - ("discussions", "discussions", "author_id", ""), - ( - "discussion comments", - "discussion_comments", - "author_id", - "", - ), - ( - "discussion notification actors", - "discussion_notifications", - "last_actor_id", - " AND user_id <> ?1", - ), ]; const REMOVED: &[(&str, &str, &str)] = &[ @@ -107,11 +94,6 @@ const REMOVED: &[(&str, &str, &str)] = &[ ("repo watches", "repo_watches", "user_id"), ("issue subscriptions", "issue_subscriptions", "user_id"), ("notifications", "notifications", "user_id"), - ( - "discussion notifications", - "discussion_notifications", - "user_id", - ), ("admin notifications", "admin_notifications", "user_id"), ("reactions", "reactions", "user_id"), ("preferences", "user_prefs", "user_id"), @@ -323,7 +305,6 @@ fn missing() -> Error { #[cfg(test)] mod tests { use super::*; - use crate::discussions::DiscussionCategory; use crate::model::Visibility; struct Fixture { @@ -567,86 +548,4 @@ mod tests { 0 ); } - - #[tokio::test] - async fn discussions_and_comments_move_to_ghost() { - let fx = fixture().await; - let mine = fx - .store - .create_discussion( - &fx.repo_id, - &fx.tahinli.id, - DiscussionCategory::General, - "Mine", - "", - ) - .await - .unwrap(); - let comment = fx - .store - .add_discussion_comment(&mine.id, &fx.tahinli.id, None, "a comment", false) - .await - .unwrap(); - fx.store - .add_discussion_comment(&mine.id, &fx.bob.id, None, "a reply", false) - .await - .unwrap(); - let theirs = fx - .store - .create_discussion( - &fx.repo_id, - &fx.bob.id, - DiscussionCategory::General, - "Theirs", - "", - ) - .await - .unwrap(); - fx.store - .add_discussion_comment(&theirs.id, &fx.tahinli.id, None, "a reply", false) - .await - .unwrap(); - - let report = fx - .store - .delete_user(&fx.tahinli.id, &fx.ghost.id) - .await - .unwrap(); - assert_eq!(reassigned(&report, "discussions"), Some(1)); - assert_eq!(reassigned(&report, "discussion comments"), Some(2)); - assert_eq!( - reassigned(&report, "discussion notification actors"), - Some(1) - ); - let removed = report - .removed - .iter() - .find(|(l, _)| *l == "discussion notifications") - .map(|(_, n)| *n); - assert_eq!(removed, Some(1)); - - assert_eq!( - scalar( - &fx.store, - "SELECT COUNT(*) FROM discussions WHERE author_id = ?1", - &fx.ghost.id - ) - .await, - 1 - ); - let kept = fx.store.list_discussion_comments(&mine.id).await.unwrap(); - assert_eq!(kept.len(), 2); - assert_eq!(kept[0].id, comment.id); - assert_eq!(kept[0].author_id, fx.ghost.id); - assert_eq!( - scalar( - &fx.store, - "SELECT COUNT(*) FROM discussion_notifications WHERE last_actor_id = ?1", - &fx.ghost.id - ) - .await, - 1 - ); - assert!(fx.store.user_by_id(&fx.tahinli.id).await.unwrap().is_none()); - } } diff --git a/crates/forge-e2e/tests/e2e/discussions_e2e.rs b/crates/forge-e2e/tests/e2e/discussions_e2e.rs deleted file mode 100644 index 5df150a..0000000 --- a/crates/forge-e2e/tests/e2e/discussions_e2e.rs +++ /dev/null @@ -1,183 +0,0 @@ -use crate::common::{ - BOB_CMD, Http, PW, TAHINLI_CMD, boot_forge, create_repo, csrf_for, login, tool_on_path, -}; - -fn anchored_id(location: Option<&str>) -> String { - location - .and_then(|l| l.rsplit_once("#comment-")) - .map(|(_, id)| id.to_owned()) - .expect("redirect anchored on a comment") -} - -#[tokio::test] -async fn discussions_create_reply_answer_lock_and_toggle() { - if !tool_on_path("git") { - eprintln!("SKIP discussions_e2e: `git` was not found on PATH"); - return; - } - - let root = tempfile::tempdir().expect("temp dir"); - let dir = root.path().to_path_buf(); - let (_server, ports) = boot_forge(&dir, "", &[TAHINLI_CMD, BOB_CMD]).await; - let http = Http::new(ports.http); - let tahinli = login(&http, "tahinli", PW).await; - let bob = login(&http, "bob", PW).await; - create_repo(&http, &tahinli, "pub", "public").await; - - let repo_page = http.get("/tahinli/pub", Some(tahinli.as_str())).await; - assert_eq!(repo_page.status, 200); - assert!( - !repo_page.body.contains("href=\"/tahinli/pub/discussions\""), - "the Discussions tab shows while discussions are off" - ); - assert_eq!( - http.get("/tahinli/pub/discussions", Some(tahinli.as_str())) - .await - .status, - 404, - "list while off" - ); - - let csrf = csrf_for(&http, "/tahinli/pub/settings", &tahinli).await; - let res = http - .post_form( - "/tahinli/pub/settings/discussions", - &[("csrf", &csrf), ("enabled", "1")], - Some(tahinli.as_str()), - ) - .await; - assert_eq!(res.status, 303, "enable: {}", res.body); - let repo_page = http.get("/tahinli/pub", Some(tahinli.as_str())).await; - assert!( - repo_page.body.contains("href=\"/tahinli/pub/discussions\""), - "the Discussions tab is missing after turning it on" - ); - - let csrf = csrf_for(&http, "/tahinli/pub/discussions/new", &tahinli).await; - let res = http - .post_form( - "/tahinli/pub/discussions/new", - &[ - ("csrf", &csrf), - ("category", "qa"), - ("title", "How do I rebase?"), - ("body", "Any tips?"), - ], - Some(tahinli.as_str()), - ) - .await; - assert_eq!(res.status, 303, "create: {}", res.body); - assert_eq!( - res.location().as_deref(), - Some("/tahinli/pub/discussions/1") - ); - let discussion = "/tahinli/pub/discussions/1"; - - let csrf_bob = csrf_for(&http, discussion, &bob).await; - let res = http - .post_form( - &format!("{discussion}/comments"), - &[("csrf", &csrf_bob), ("body", "Try git rebase -i.")], - Some(bob.as_str()), - ) - .await; - assert_eq!(res.status, 303, "top comment: {}", res.body); - let top = anchored_id(res.location().as_deref()); - - let res = http - .post_form( - &format!("{discussion}/comments"), - &[ - ("csrf", &csrf_bob), - ("parent", &top), - ("body", "Thanks, that worked."), - ], - Some(bob.as_str()), - ) - .await; - assert_eq!(res.status, 303, "reply: {}", res.body); - let reply = anchored_id(res.location().as_deref()); - - let res = http - .post_form( - &format!("{discussion}/comments"), - &[ - ("csrf", &csrf_bob), - ("parent", &reply), - ("body", "Too deep"), - ], - Some(bob.as_str()), - ) - .await; - assert_eq!(res.status, 200, "nested reply shows the refusal page"); - assert!( - res.body.contains("Could not save") && res.body.contains("one level"), - "nested reply was not refused: {}", - res.body - ); - - let csrf_tahinli = csrf_for(&http, discussion, &tahinli).await; - let res = http - .post_form( - &format!("{discussion}/answer"), - &[ - ("csrf", &csrf_tahinli), - ("comment_id", &top), - ("answer", "1"), - ], - Some(tahinli.as_str()), - ) - .await; - assert_eq!(res.status, 303, "answer: {}", res.body); - let page = http.get(discussion, Some(bob.as_str())).await; - assert!( - page.body.contains("Answered"), - "the answered badge is missing after marking an answer" - ); - - let csrf_tahinli = csrf_for(&http, discussion, &tahinli).await; - let res = http - .post_form( - &format!("{discussion}/lock"), - &[("csrf", &csrf_tahinli), ("locked", "1")], - Some(tahinli.as_str()), - ) - .await; - assert_eq!(res.status, 303, "lock: {}", res.body); - let res = http - .post_form( - &format!("{discussion}/comments"), - &[("csrf", &csrf_bob), ("body", "Still here")], - Some(bob.as_str()), - ) - .await; - assert_eq!(res.status, 403, "bob comments on a locked discussion"); - let res = http - .post_form( - &format!("{discussion}/lock"), - &[("csrf", &csrf_bob), ("locked", "0")], - Some(bob.as_str()), - ) - .await; - assert_eq!(res.status, 403, "bob locks a discussion"); - - let csrf = csrf_for(&http, "/tahinli/pub/settings", &tahinli).await; - let res = http - .post_form( - "/tahinli/pub/settings/discussions", - &[("csrf", &csrf), ("enabled", "0")], - Some(tahinli.as_str()), - ) - .await; - assert_eq!(res.status, 303, "disable: {}", res.body); - let repo_page = http.get("/tahinli/pub", Some(tahinli.as_str())).await; - assert!( - !repo_page.body.contains("href=\"/tahinli/pub/discussions\""), - "the tab stays after turning discussions off" - ); - assert_eq!( - http.get(discussion, Some(tahinli.as_str())).await.status, - 404, - "discussion page while off" - ); -} diff --git a/crates/forge-e2e/tests/e2e/main.rs b/crates/forge-e2e/tests/e2e/main.rs index 48f7840..e895cbe 100644 --- a/crates/forge-e2e/tests/e2e/main.rs +++ b/crates/forge-e2e/tests/e2e/main.rs @@ -5,7 +5,6 @@ mod branch_protection_e2e; mod browse_e2e; mod ci_e2e; mod community_i18n_e2e; -mod discussions_e2e; mod git_e2e; mod i18n_e2e; mod issue_close_e2e; diff --git a/crates/forge-web-account/src/pages/palette.rs b/crates/forge-web-account/src/pages/palette.rs index 258f2e8..02bb129 100644 --- a/crates/forge-web-account/src/pages/palette.rs +++ b/crates/forge-web-account/src/pages/palette.rs @@ -286,15 +286,7 @@ fn repo_pages(lang: Lang) -> Vec { &settings, "settings", true, - &[ - "Description", - "Açıklama", - "Features", - "Özellikler", - "Wiki", - "Discussions", - "Tartışmalar", - ], + &["Description", "Açıklama", "Features", "Özellikler", "Wiki"], ), repo_page( admin(RK::BranchProtection), diff --git a/crates/forge-web-app/src/layers.rs b/crates/forge-web-app/src/layers.rs index 84564a4..7e81bb1 100644 --- a/crates/forge-web-app/src/layers.rs +++ b/crates/forge-web-app/src/layers.rs @@ -7,7 +7,6 @@ use topcoat::router::request::{method, uri}; use crate::live::Topic; use crate::state::AppState; -pub use discussion_write::DiscussionWriteLayer; pub use not_found_layer::NotFoundLayer; pub use org_write::OrgWriteLayer; pub use pull_write::PullWriteLayer; @@ -287,100 +286,6 @@ mod pull_write { } } -mod discussion_write { - use topcoat::context::{Cx, context}; - use topcoat::router::response::Response; - use topcoat::router::{Body, Layer, LayerFuture, Next, Path}; - - use super::post_segments; - use crate::live::Topic; - use crate::state::AppState; - - enum Written { - List { - owner: String, - repo: String, - }, - Discussion { - owner: String, - repo: String, - number: String, - }, - } - - fn written(cx: &Cx) -> Option { - let parts = post_segments(cx)?; - let [owner, repo, kind, rest @ ..] = parts.as_slice() else { - return None; - }; - let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned()); - match (*kind, rest) { - ("discussions", ["new"]) => Some(Written::List { owner, repo }), - ("discussions", [number, ..]) => Some(Written::Discussion { - owner, - repo, - number: (*number).to_owned(), - }), - ("settings", ["discussions"]) => Some(Written::List { owner, repo }), - _ => None, - } - } - - async fn topics_of(state: &AppState, target: Written) -> Vec { - let (owner, name) = match &target { - Written::List { owner, repo } | Written::Discussion { owner, repo, .. } => { - (owner.as_str(), repo.as_str()) - } - }; - let repo = match state.store.repo_by_owner_and_name(owner, name).await { - Ok(Some(repo)) => repo, - Ok(None) => return Vec::new(), - Err(e) => { - tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); - return Vec::new(); - } - }; - let mut topics = vec![Topic::Discussions(repo.id.clone())]; - if let Written::Discussion { number, .. } = target - && let Ok(number) = number.parse::() - { - match state.store.discussion_by_number(&repo.id, number).await { - Ok(Some(discussion)) => topics.push(Topic::Discussion(discussion.id)), - Ok(None) => {} - Err(e) => { - tracing::error!(error = %e, number, "live: loading the discussion to bump failed") - } - } - } - topics - } - - pub struct DiscussionWriteLayer; - - impl Layer for DiscussionWriteLayer { - fn path(&self) -> Option<&Path> { - None - } - - fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { - Box::pin(bump_after_write(cx, body, next)) - } - } - - async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result { - let state = context::(cx); - let topics = match written(cx) { - Some(target) => topics_of(state, target).await, - None => Vec::new(), - }; - let result = next.run(cx, body).await; - for topic in &topics { - state.live.bump(topic); - } - result - } -} - mod org_write { use topcoat::context::{Cx, context}; use topcoat::router::response::Response; diff --git a/crates/forge-web-app/src/live.rs b/crates/forge-web-app/src/live.rs index a40ff54..5ffdef7 100644 --- a/crates/forge-web-app/src/live.rs +++ b/crates/forge-web-app/src/live.rs @@ -27,8 +27,6 @@ pub enum Topic { ReviewRequests(String), Imports(String), Explore, - Discussions(String), - Discussion(String), Wiki(String), Snippets, Snippet(String), diff --git a/crates/forge-web-app/src/test_support/mod.rs b/crates/forge-web-app/src/test_support/mod.rs index 1927885..8c626e3 100644 --- a/crates/forge-web-app/src/test_support/mod.rs +++ b/crates/forge-web-app/src/test_support/mod.rs @@ -101,7 +101,6 @@ pub fn app_router(state: AppState) -> Router { .layer(RepoMovedLayer) .layer(crate::layers::RepoSettingsWriteLayer) .layer(crate::layers::PullWriteLayer) - .layer(crate::layers::DiscussionWriteLayer) .layer(crate::layers::OrgWriteLayer) .layer(TowerLayer::new(crate::compression::ResponseCompression)) .with(Compression::disable()) diff --git a/crates/forge-web-app/src/views/mod.rs b/crates/forge-web-app/src/views/mod.rs index 5b77683..de9492d 100644 --- a/crates/forge-web-app/src/views/mod.rs +++ b/crates/forge-web-app/src/views/mod.rs @@ -154,8 +154,8 @@ fn step_label(lang: Lang, word: &str) -> String { fn repo_section_label(lang: Lang, kind: &str) -> Option { match kind { - "issues" | "pulls" | "ci" | "commits" | "branches" | "tags" | "releases" - | "discussions" | "wiki" | "settings" => Some(tab_title(lang, kind, "")), + "issues" | "pulls" | "ci" | "commits" | "branches" | "tags" | "releases" | "wiki" + | "settings" => Some(tab_title(lang, kind, "")), "milestones" => Some(s(lang, "Milestones", "Kilometre taşları").to_owned()), "labels" => Some(s(lang, "Labels", "Etiketler").to_owned()), _ => None, @@ -273,7 +273,7 @@ fn path_segments(lang: Lang, path: &str, title: &str) -> Vec<(String, Option { segments.push((label, Some(repo_href(owner, repo, section, "")))); let item = rest[0].as_str(); - let numbered = matches!(section, "issues" | "pulls" | "discussions") + let numbered = matches!(section, "issues" | "pulls") && item.bytes().all(|b| b.is_ascii_digit()); match (section, rest) { ("ci", [runs, number]) if runs == "runs" => { @@ -1286,7 +1286,6 @@ pub async fn repo_tabs( lang: Lang, #[default] open_issues: Option, #[default] open_pulls: Option, - #[default] discussions: bool, #[default] wiki: bool, ) -> Result { let home = repo_href(&owner, &repo, "", ""); @@ -1305,7 +1304,6 @@ pub async fn repo_tabs( ); let code_on = active == "code" || more_on; let settings = repo_href(&owner, &repo, "settings", ""); - let discussions_tab = repo_href(&owner, &repo, "discussions", ""); let wiki_tab = repo_href(&owner, &repo, "wiki", ""); Ok(view! {