laravel-comments 0.2.0

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Posting, replying, editing, moderating, and removing comments.

use laravel::db::{self, Values, col, values};
use laravel::model::{Column, CreateBuilder, Morph, UpdateBuilder};

use crate::author::{Author, Commenter};
use crate::config::{AutoApprove, CommentsConfig};
use crate::error::CommentError;
use crate::events::{CommentApproved, CommentDeleted, CommentEdited, CommentModerated, CommentPosted};
use crate::mentions::{self, CommentMention};
use crate::model::CommentModel;
use crate::moderation::{ModerationRule, NewComment};
use crate::revisions::CommentRevision;
use crate::status::Status;

/// How many times a write runs when the database aborts it for a deadlock. With the `mysql`
/// feature, writes to different threads don't deadlock on MySQL; the retries cover what's left,
/// as MySQL's documentation advises, and applications that leave the feature off. Inside a
/// transaction of the application's, the write runs once, as only the outermost transaction can
/// retry.
pub(crate) const ATTEMPTS: u32 = 5;

pub(crate) fn config() -> CommentsConfig {
    laravel::config().section::<CommentsConfig>().clone()
}

/// Posts a top-level comment on `on`.
pub(crate) async fn post<C: CommentModel>(
    on: C::Commentable,
    author: Author<'_, C::Author>,
    body: &str,
) -> laravel::Result<C> {
    let config = config();
    check_body(body, &config)?;
    let columns = C::COLUMNS;
    let status = status_for(&config, new_comment(on.morph().name(), *on.key(), None, &author, body)).await?;

    // Every top-level comment starts a tree of its own under a new ULID, so no other writer can
    // be in that tree: its bounds are 1 and 2, and the insert needs no lock. Even nestedset's
    // `create_root_in` would lock more than that on MySQL, where new roots take turns across
    // the table.
    check_author(&author)?;
    let mentioned = mentions::resolve(body, author_id(&author)).await?;
    let comment: C = db::transaction_with_attempts(ATTEMPTS, async |_| {
        let mut create = author_values::<C>(CreateBuilder::new(), &author)
            .set(columns.commentable_type, on.morph())
            .set(columns.commentable_id, *on.key())
            .set(columns.thread, laravel::str::ulid().to_string())
            .set(columns.body, body.to_owned())
            .set(columns.status, status)
            .set(C::lft_column(), 1)
            .set(C::rgt_column(), 2);
        if let Some(depth) = C::depth_column() {
            create = create.set(depth, 0);
        }
        let comment: C = create.await?;
        mentions::record(comment.row().id, &mentioned).await?;
        Ok(comment)
    })
    .await?;

    posted(&comment).await?;
    mentions::announce(&comment).await?;
    Ok(comment)
}

/// Posts a reply to `parent`, and reloads `parent`.
pub(crate) async fn reply<C: CommentModel>(
    parent: &mut C,
    author: Author<'_, C::Author>,
    body: &str,
) -> laravel::Result<C> {
    let config = config();
    check_body(body, &config)?;
    if config.max_depth <= 0 {
        return Err(CommentError::RepliesDisabled.into());
    }
    let row = parent.row();
    let (parent_id, commentable_type, commentable_id) = (row.id, row.commentable_type, row.commentable_id);
    if row.deleted_at.is_some() {
        return Err(CommentError::Deleted { id: parent_id }.into());
    }
    if row.status != Status::Approved {
        return Err(CommentError::NotApproved { id: parent_id }.into());
    }
    let too_deep = row.depth >= config.max_depth;

    let columns = C::COLUMNS;
    check_author(&author)?;
    let status = status_for(
        &config,
        new_comment(commentable_type.name(), commentable_id, Some(parent_id), &author, body),
    )
    .await?;

    let mentioned = mentions::resolve(body, author_id(&author)).await?;
    let start = &*parent;
    let reply = db::transaction_with_attempts(ATTEMPTS, async |_| {
        let create = author_values::<C>(CreateBuilder::new(), &author)
            .set(columns.commentable_type, commentable_type)
            .set(columns.commentable_id, commentable_id)
            .set(columns.body, body.to_owned())
            .set(columns.status, status);
        // Below the deepest level, a reply joins its parent's replies, as on Reddit.
        let mut anchor = if too_deep {
            start
                .ancestors()
                .filter(depth_is::<C>(config.max_depth - 1))
                .first()
                .await?
                .ok_or(CommentError::NotFound { id: parent_id })?
        } else {
            start.clone()
        };
        let reply = anchor.create_child(create).await?;
        if status == Status::Approved {
            adjust_replies::<C>(*anchor.node_key(), 1).await?;
        }
        mentions::record(reply.row().id, &mentioned).await?;
        Ok(reply)
    })
    .await?;

    *parent = find::<C>(parent_id).await?;
    posted(&reply).await?;
    mentions::announce(&reply).await?;
    Ok(reply)
}

/// Replaces the text of `comment` and sets its `edited_at`.
pub(crate) async fn edit<C: CommentModel>(comment: &mut C, body: &str) -> laravel::Result<()> {
    let config = config();
    check_body(body, &config)?;
    let row = comment.row();
    let (id, author_id, old_body) = (row.id, row.author_id, row.body.to_owned());
    if row.deleted_at.is_some() {
        return Err(CommentError::Deleted { id }.into());
    }
    if old_body == body {
        return Ok(());
    }

    let mentioned = mentions::resolve(body, author_id).await?;
    let columns = C::COLUMNS;
    db::transaction_with_attempts(ATTEMPTS, async |_| {
        let now = laravel::now().timestamp();
        if config.revisions {
            db::table("comment_revisions")
                .insert(values! { comment_id: id, body: old_body.as_str(), created_at: now })
                .await?;
        }
        let mut values = Values::new()
            .set(columns.body.name(), body)
            .set(columns.edited_at.name(), now);
        if let Some(stamp) = C::META.updated_at {
            values = values.set(stamp.name, now);
        }
        C::new_query().filter(C::META.key.eq(id)).update_values(values).await?;
        mentions::record(id, &mentioned).await
    })
    .await?;
    *comment = find::<C>(id).await?;

    let row = comment.row();
    CommentEdited {
        comment_id: id,
        commentable_type: row.commentable_type.name().to_owned(),
        commentable_id: row.commentable_id,
        status: row.status,
    }
    .dispatch()
    .await?;
    mentions::announce(&*comment).await
}

/// Gives `comment` the status `to`.
pub(crate) async fn moderate<C: CommentModel>(comment: &mut C, to: Status) -> laravel::Result<()> {
    let row = comment.row();
    let (id, from, parent_id) = (row.id, row.status, row.parent_id);
    if from == to {
        return Ok(());
    }

    let columns = C::COLUMNS;
    db::transaction_with_attempts(ATTEMPTS, async |_| {
        let now = laravel::now().timestamp();
        let mut values = Values::new()
            .set(columns.status.name(), to)
            .set(columns.moderated_at.name(), now);
        if let Some(stamp) = C::META.updated_at {
            values = values.set(stamp.name, now);
        }
        C::new_query().filter(C::META.key.eq(id)).update_values(values).await?;
        if let Some(parent_id) = parent_id {
            if to == Status::Approved {
                adjust_replies::<C>(parent_id, 1).await?;
            } else if from == Status::Approved {
                adjust_replies::<C>(parent_id, -1).await?;
            }
        }
        Ok(())
    })
    .await?;
    *comment = find::<C>(id).await?;

    let row = comment.row();
    let (commentable_type, commentable_id) = (row.commentable_type.name().to_owned(), row.commentable_id);
    CommentModerated {
        comment_id: id,
        commentable_type: commentable_type.clone(),
        commentable_id,
        from,
        to,
    }
    .dispatch()
    .await?;
    if to == Status::Approved {
        CommentApproved {
            comment_id: id,
            commentable_type,
            commentable_id,
        }
        .dispatch()
        .await?;
        mentions::announce(&*comment).await?;
    }
    Ok(())
}

/// Removes `comment`: a comment with replies becomes a placeholder, one without is deleted, and
/// so is every placeholder above it that has no replies left. Returns whether a placeholder stays.
pub(crate) async fn remove<C: CommentModel>(comment: C) -> laravel::Result<bool> {
    let row = comment.row();
    let (id, commentable_type, commentable_id) = (row.id, row.commentable_type.name().to_owned(), row.commentable_id);
    let (placeholder, deleted) = db::transaction_with_attempts(ATTEMPTS, async |_| {
        let mut current = find::<C>(id).await?;
        let status = current.row().status;
        if current.descendant_count() > 0 {
            leave_placeholder(&mut current).await?;
            return Ok((true, vec![(id, status)]));
        }

        // The comment goes, and so does each placeholder above it whose only reply is the branch
        // that goes: one delete of the highest such placeholder's subtree, one write to the tree.
        let mut top = current;
        let mut deleted = vec![(id, status)];
        while let Some(parent_id) = top.row().parent_id {
            let parent = find::<C>(parent_id).await?;
            let left_empty = parent.descendant_count() == top.descendant_count() + 1;
            if parent.row().deleted_at.is_none() || !left_empty {
                break;
            }
            deleted.push((parent_id, parent.row().status));
            top = parent;
        }
        let row = top.row();
        let (parent_id, approved) = (row.parent_id, row.status == Status::Approved);
        top.delete_subtree().await?;
        if let (Some(parent_id), true) = (parent_id, approved) {
            adjust_replies::<C>(parent_id, -1).await?;
        }
        Ok((false, deleted))
    })
    .await?;

    for (comment_id, status) in deleted {
        CommentDeleted {
            comment_id,
            commentable_type: commentable_type.clone(),
            commentable_id,
            placeholder,
            status,
        }
        .dispatch()
        .await?;
    }
    Ok(placeholder)
}

/// Clears the text and the author of `comment`, with its earlier texts and its mentions, keeping
/// its place in the tree for its replies.
async fn leave_placeholder<C: CommentModel>(comment: &mut C) -> laravel::Result<()> {
    let columns = C::COLUMNS;
    let id = comment.row().id;
    CommentRevision::query()
        .filter(CommentRevision::comment_id.eq(id))
        .delete()
        .await?;
    CommentMention::query()
        .filter(CommentMention::comment_id.eq(id))
        .delete()
        .await?;
    UpdateBuilder::new(comment)
        .set(columns.body, String::new())
        .set(columns.author_id, None::<i64>)
        .set(columns.guest_name, None::<String>)
        .set(columns.guest_email, None::<String>)
        .set(columns.deleted_at, laravel::now())
        .await
}

/// Reads the comment with `id` again.
pub(crate) async fn find<C: CommentModel>(id: i64) -> laravel::Result<C> {
    C::new_query()
        .filter(C::META.key.eq(id))
        .first()
        .await?
        .ok_or_else(|| CommentError::NotFound { id }.into())
}

fn depth_is<C: CommentModel>(depth: i64) -> laravel::db::Condition {
    match C::depth_column() {
        Some(column) => column.eq(depth),
        None => laravel::db::raw!("1 = 0").into(),
    }
}

/// Changes the `replies_count` of the comment with `id` by `by`, in SQL.
async fn adjust_replies<C: CommentModel>(id: i64, by: i64) -> laravel::Result<()> {
    bump(id, C::COLUMNS.replies_count, by).await
}

/// Changes a counter of the comment with `id` by `by` in one `UPDATE`, so concurrent changes add
/// up, and leaves `updated_at` as it is: a counter isn't an edit.
pub(crate) async fn bump<C: CommentModel>(id: i64, counter: Column<C, i64>, by: i64) -> laravel::Result<()> {
    let name = counter.name();
    let mut values = Values::new().set(name, col(name) + by);
    if let Some(stamp) = C::META.updated_at {
        values = values.set(stamp.name, col(stamp.name));
    }
    C::new_query().filter(C::META.key.eq(id)).update_values(values).await?;
    Ok(())
}

fn author_id<U: Commenter>(author: &Author<'_, U>) -> Option<i64> {
    match author {
        Author::User(user) => Some(user.commenter_id()),
        Author::Guest { .. } => None,
    }
}

async fn posted<C: CommentModel>(comment: &C) -> laravel::Result<()> {
    let row = comment.row();
    CommentPosted {
        comment_id: row.id,
        commentable_type: row.commentable_type.name().to_owned(),
        commentable_id: row.commentable_id,
        parent_id: row.parent_id,
        author_id: row.author_id,
        status: row.status,
    }
    .dispatch()
    .await
}

fn check_body(body: &str, config: &CommentsConfig) -> Result<(), CommentError> {
    if body.trim().is_empty() {
        return Err(CommentError::EmptyBody);
    }
    if body.chars().count() > config.max_length {
        return Err(CommentError::BodyTooLong { max: config.max_length });
    }
    Ok(())
}

/// A guest needs a name and an email address.
fn check_author<U>(author: &Author<'_, U>) -> Result<(), CommentError> {
    match author {
        Author::Guest { name, email } if name.trim().is_empty() || !email.contains('@') => {
            Err(CommentError::InvalidGuest)
        }
        _ => Ok(()),
    }
}

fn author_values<C: CommentModel>(create: CreateBuilder<C>, author: &Author<'_, C::Author>) -> CreateBuilder<C> {
    let columns = C::COLUMNS;
    match author {
        Author::User(user) => create.set(columns.author_id, Some(user.commenter_id())),
        Author::Guest { name, email } => create
            .set(columns.guest_name, Some(name.trim().to_owned()))
            .set(columns.guest_email, Some(email.trim().to_owned())),
    }
}

fn new_comment<U: Commenter>(
    commentable_type: &'static str,
    commentable_id: i64,
    parent_id: Option<i64>,
    author: &Author<'_, U>,
    body: &str,
) -> NewComment {
    let (author_id, guest_email) = match author {
        Author::User(user) => (Some(user.commenter_id()), None),
        Author::Guest { email, .. } => (None, Some(email.trim().to_owned())),
    };
    NewComment {
        commentable_type,
        commentable_id,
        parent_id,
        author_id,
        guest_email,
        body: body.to_owned(),
    }
}

/// The status a new comment gets: the application's rule decides, or else `auto_approve`.
async fn status_for(config: &CommentsConfig, comment: NewComment) -> laravel::Result<Status> {
    let rule = laravel::resolve::<ModerationRule>().await?;
    if let Some(rule) = &rule.0 {
        return rule(comment).await;
    }
    let approved = match config.auto_approve {
        AutoApprove::Everyone => true,
        AutoApprove::Users => comment.author_id.is_some(),
        AutoApprove::Nobody => false,
    };
    Ok(if approved { Status::Approved } else { Status::Pending })
}