22.0 KiB · text History 95b0c9a
//! `manage seed [--demo]`: baseline data, plus optional demo content.
//!
//! Every step looks its row up by a natural key (category slug, reaction key,
//! tag slug, demo username, demo topic title) and only inserts what is
//! missing, so running it again changes nothing, and it never edits rows an
//! operator has since changed.
//!
//! * `seed` — what a real forum can keep: a category tree three levels deep
//!   with distinct colors, a members-only category (`min_trust_level = 0`: any
//!   signed-in account) and a min-trust one (Regular, 3), the default reaction
//!   types, and a few tags.
//! * `seed --demo` — fake people and conversations for development: `demo-*`
//!   accounts at every trust tier (verified, password [`DEMO_PASSWORD`]),
//!   topics with replies, an edited post, a soft-deleted post, reactions,
//!   bookmarks, tags, a pinned topic, spread over the last few weeks. It is
//!   never run by the image, compose or `AUTO_MIGRATE`; `manage` refuses it
//!   when `PUBLIC_URL` is https unless `--allow-public` is given.

use anyhow::{bail, Context, Result};
use chrono::{DateTime, Duration, FixedOffset, Utc};
use sea_orm::*;
use uuid::Uuid;

use crate::auth;
use crate::entities::{
    bookmarks, categories, post_reactions, post_revisions, posts, reaction_types, tags, topic_tags, topics, users,
};
use crate::markdown;

/// Password of every `demo-*` account (documented in the README). Demo data is
/// for development only.
pub const DEMO_PASSWORD: &str = "recourse-demo";

/// A category to seed: `(slug, name, color, parent slug, min trust, description)`.
pub struct CategorySeed {
    pub slug: &'static str,
    pub name: &'static str,
    pub color: &'static str,
    pub parent: Option<&'static str>,
    pub min_trust: Option<i32>,
    pub description: &'static str,
}

const fn cat(
    slug: &'static str,
    name: &'static str,
    color: &'static str,
    parent: Option<&'static str>,
    min_trust: Option<i32>,
    description: &'static str,
) -> CategorySeed {
    CategorySeed { slug, name, color, parent, min_trust, description }
}

/// Parents come before their children. `announcements` and `general` are
/// also created by the forum migration; listing them keeps `seed` complete on
/// its own.
pub const CATEGORIES: &[CategorySeed] = &[
    cat("announcements", "Announcements", "#E45735", None, None, "Official announcements and news."),
    cat("general", "General", "#0088CC", None, None, "General discussion about anything."),
    cat("development", "Development", "#25AAE2", None, None, "Building things: code, tools and infrastructure."),
    cat("backend", "Backend", "#3AB54A", Some("development"), None, "Servers, APIs and everything behind them."),
    cat("databases", "Databases", "#12A89D", Some("backend"), None, "Schemas, queries, migrations and tuning."),
    cat("frontend", "Frontend", "#F7941D", Some("development"), None, "HTML, CSS, htmx and the browser."),
    cat("hobbies", "Hobbies", "#9EB83B", None, None, "What we do when we're not at a keyboard."),
    cat("games", "Games", "#BF1E2E", Some("hobbies"), None, "Video, board, card and tabletop games."),
    cat("board-games", "Board Games", "#652D90", Some("games"), None, "Cardboard, dice and meeples."),
    cat("feedback", "Site Feedback", "#808281", None, None, "Bugs, ideas and questions about this forum."),
    cat("members", "Members Lounge", "#D4AF37", None, Some(0), "Members only: visible to signed-in accounts."),
    cat("regulars", "Regulars' Corner", "#ED207B", None, Some(3), "For trust level 3 (Regular) and up."),
];

/// The reaction types the reactions migration installs.
pub const REACTIONS: &[(&str, &str)] = &[("heart", "\u{2764}\u{FE0F}"), ("star", "\u{2B50}"), ("thumbsup", "\u{1F44D}")];

/// `(name, slug)`.
pub const TAGS: &[(&str, &str)] = &[
    ("rust", "rust"),
    ("postgres", "postgres"),
    ("htmx", "htmx"),
    ("help", "help"),
    ("meta", "meta"),
    ("show-and-tell", "show-and-tell"),
];

/// What a run created (everything else already existed).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Report {
    pub categories: usize,
    pub reactions: usize,
    pub tags: usize,
    pub users: usize,
    pub topics: usize,
    pub posts: usize,
}

impl Report {
    pub fn is_empty(&self) -> bool {
        *self == Report::default()
    }
}

/// The baseline: categories, reaction types, tags.
pub async fn seed_base<C: ConnectionTrait>(db: &C) -> Result<Report> {
    let mut report = Report::default();
    let now: DateTime<FixedOffset> = Utc::now().into();

    for (position, c) in CATEGORIES.iter().enumerate() {
        if categories::Entity::find()
            .filter(categories::Column::Slug.eq(c.slug))
            .one(db)
            .await?
            .is_some()
        {
            continue;
        }
        let parent_id = match c.parent {
            None => None,
            Some(slug) => Some(
                categories::Entity::find()
                    .filter(categories::Column::Slug.eq(slug))
                    .one(db)
                    .await?
                    .with_context(|| format!("parent category {slug} is missing"))?
                    .id,
            ),
        };
        categories::ActiveModel {
            id: Set(Uuid::now_v7()),
            name: Set(c.name.into()),
            slug: Set(c.slug.into()),
            description: Set(Some(c.description.into())),
            color: Set(c.color.into()),
            position: Set(position as i32),
            parent_id: Set(parent_id),
            min_trust_level: Set(c.min_trust),
            created_at: Set(now),
            updated_at: Set(now),
        }
        .insert(db)
        .await
        .with_context(|| format!("insert category {}", c.slug))?;
        report.categories += 1;
    }

    for (position, (key, emoji)) in REACTIONS.iter().enumerate() {
        if reaction_types::Entity::find()
            .filter(reaction_types::Column::Key.eq(*key))
            .one(db)
            .await?
            .is_none()
        {
            reaction_types::ActiveModel {
                id: Set(Uuid::now_v7()),
                key: Set((*key).into()),
                emoji: Set((*emoji).into()),
                position: Set(position as i32),
                is_active: Set(true),
                created_at: Set(now),
            }
            .insert(db)
            .await?;
            report.reactions += 1;
        }
    }

    for (name, slug) in TAGS {
        if ensure_tag(db, name, slug, now).await?.1 {
            report.tags += 1;
        }
    }
    Ok(report)
}

async fn ensure_tag<C: ConnectionTrait>(
    db: &C,
    name: &str,
    slug: &str,
    now: DateTime<FixedOffset>,
) -> Result<(Uuid, bool)> {
    if let Some(t) = tags::Entity::find().filter(tags::Column::Slug.eq(slug)).one(db).await? {
        return Ok((t.id, false));
    }
    let t = tags::ActiveModel {
        id: Set(Uuid::now_v7()),
        name: Set(name.into()),
        slug: Set(slug.into()),
        created_at: Set(now),
    }
    .insert(db)
    .await?;
    Ok((t.id, true))
}

/// `(username, trust level, staff, joined days ago)`.
pub const DEMO_USERS: &[(&str, i32, bool, i64)] = &[
    ("demo-admin", 4, true, 120),
    ("demo-leader", 4, false, 110),
    ("demo-regular", 3, false, 90),
    ("demo-member", 2, false, 60),
    ("demo-basic", 1, false, 30),
    ("demo-new", 0, false, 2),
];

/// One demo post: author, minutes after the topic started, body.
struct P(&'static str, i64, &'static str);

/// One demo topic: category, author, title, days ago, pinned, tags, posts
/// (the first is the opening post).
struct T {
    category: &'static str,
    title: &'static str,
    days_ago: i64,
    pinned: bool,
    tags: &'static [&'static str],
    posts: &'static [P],
}

const DEMO_TOPICS: &[T] = &[
    T {
        category: "announcements",
        title: "Welcome to the demo forum",
        days_ago: 40,
        pinned: true,
        tags: &["meta"],
        posts: &[
            P("demo-admin", 0, "Welcome! This forum is filled with **demo content** so every screen has something on it.\n\nAll `demo-*` accounts share the password from the README."),
            P("demo-leader", 30, "Thanks for setting this up. Pinned topics stay at the top of their category."),
            P("demo-member", 300, "Glad to be here :)"),
        ],
    },
    T {
        category: "databases",
        title: "Choosing indexes for a topic list",
        days_ago: 21,
        pinned: false,
        tags: &["postgres", "help"],
        posts: &[
            P("demo-regular", 0, "The latest-topics query sorts by `bumped_at`. Is a plain btree enough?\n\n```sql\nCREATE INDEX ON topics (bumped_at DESC);\n```"),
            P("demo-leader", 45, "Yes, and make it partial on `deleted_at IS NULL` if most reads skip deleted topics."),
            P("demo-basic", 90, "What about the category filter?"),
            P("demo-regular", 180, "A composite `(category_id, bumped_at DESC)` covers that."),
        ],
    },
    T {
        category: "frontend",
        title: "htmx boosted links and fragments",
        days_ago: 12,
        pinned: false,
        tags: &["htmx", "show-and-tell"],
        posts: &[
            P("demo-member", 0, "Boosting the body means every partial needs `hx-select=\"unset\"`, or it inherits `#content`."),
            P("demo-regular", 20, "Same trick for `hx-target`. Took me a while to spot."),
            P("demo-new", 60, "This reply was removed by its author."),
        ],
    },
    T {
        category: "backend",
        title: "axum extractors: order matters",
        days_ago: 7,
        pinned: false,
        tags: &["rust"],
        posts: &[
            P("demo-leader", 0, "The body-consuming extractor (`Form`, `Json`) has to be last."),
            P("demo-basic", 15, "Good to know, thanks!"),
        ],
    },
    T {
        category: "board-games",
        title: "What's on your table this month?",
        days_ago: 3,
        pinned: false,
        tags: &[],
        posts: &[
            P("demo-basic", 0, "Lots of Azul here."),
            P("demo-member", 120, "Spirit Island, every week."),
            P("demo-leader", 600, "Cascadia with the kids."),
        ],
    },
    T {
        category: "members",
        title: "Members-only: introduce yourself",
        days_ago: 15,
        pinned: false,
        tags: &[],
        posts: &[
            P("demo-member", 0, "Only signed-in accounts can see this category."),
            P("demo-new", 10, "Hi, I'm new!"),
        ],
    },
    T {
        category: "regulars",
        title: "Regulars: moderation notes",
        days_ago: 5,
        pinned: false,
        tags: &["meta"],
        posts: &[P("demo-regular", 0, "Trust level 3 and up (and staff) can read this.")],
    },
    T {
        category: "general",
        title: "Small talk",
        days_ago: 1,
        pinned: false,
        tags: &[],
        posts: &[P("demo-new", 0, "Is it weekend yet?")],
    },
];

/// The opening post of "Choosing indexes…" is edited once.
const EDITED: (&str, i32, &str) = (
    "Choosing indexes for a topic list",
    1,
    "The latest-topics query sorts by `bumped_at`. Is a plain btree enough?\n\n```sql\nCREATE INDEX ON topics (bumped_at DESC);\n```\n\n**Edit:** we also filter by category.",
);
/// Post 3 of the htmx topic is soft-deleted by its author.
const DELETED: (&str, i32) = ("htmx boosted links and fragments", 3);

/// `(username, reaction key, topic title, post number)`.
const DEMO_REACTIONS: &[(&str, &str, &str, i32)] = &[
    ("demo-member", "heart", "Welcome to the demo forum", 1),
    ("demo-basic", "thumbsup", "Welcome to the demo forum", 1),
    ("demo-regular", "star", "Welcome to the demo forum", 1),
    ("demo-leader", "thumbsup", "Choosing indexes for a topic list", 4),
    ("demo-member", "star", "Choosing indexes for a topic list", 2),
    ("demo-regular", "heart", "htmx boosted links and fragments", 1),
    ("demo-admin", "thumbsup", "axum extractors: order matters", 1),
];

/// `(username, topic title, post number)`.
const DEMO_BOOKMARKS: &[(&str, &str, i32)] = &[
    ("demo-member", "Choosing indexes for a topic list", 2),
    ("demo-member", "axum extractors: order matters", 1),
    ("demo-basic", "htmx boosted links and fragments", 1),
];

/// Demo accounts and content (after [`seed_base`]).
pub async fn seed_demo(db: &DatabaseConnection) -> Result<Report> {
    let mut report = Report::default();
    let now = Utc::now();

    for (name, level, staff, joined) in DEMO_USERS {
        if users::Entity::find().filter(users::Column::Username.eq(*name)).one(db).await?.is_some() {
            continue;
        }
        let email = format!("{name}@demo.invalid");
        let user = auth::create_user_direct(db, name, &email, DEMO_PASSWORD, *staff)
            .await
            .with_context(|| format!("create {name}"))?;
        let joined_at: DateTime<FixedOffset> = (now - Duration::days(*joined)).into();
        let mut am: users::ActiveModel = user.into();
        am.trust_level = Set(*level);
        am.created_at = Set(joined_at);
        am.email_verified_at = Set(Some(joined_at));
        am.update(db).await?;
        report.users += 1;
    }

    for t in DEMO_TOPICS {
        if topics::Entity::find().filter(topics::Column::Title.eq(t.title)).one(db).await?.is_some() {
            continue;
        }
        let txn = db.begin().await?;
        report.posts += demo_topic(&txn, t, now).await.with_context(|| format!("topic {:?}", t.title))?;
        txn.commit().await?;
        report.topics += 1;
    }

    for (name, key, title, number) in DEMO_REACTIONS {
        let user = user_id(db, name).await?;
        let post = post_id(db, title, *number).await?;
        let reaction = reaction_types::Entity::find()
            .filter(reaction_types::Column::Key.eq(*key))
            .one(db)
            .await?
            .with_context(|| format!("reaction {key}"))?;
        let exists = post_reactions::Entity::find()
            .filter(post_reactions::Column::PostId.eq(post))
            .filter(post_reactions::Column::UserId.eq(user))
            .one(db)
            .await?
            .is_some();
        if !exists {
            post_reactions::ActiveModel {
                id: Set(Uuid::now_v7()),
                post_id: Set(post),
                user_id: Set(user),
                reaction_id: Set(reaction.id),
                created_at: Set(now.into()),
            }
            .insert(db)
            .await?;
        }
    }

    for (name, title, number) in DEMO_BOOKMARKS {
        let user = user_id(db, name).await?;
        let post = post_id(db, title, *number).await?;
        let exists = bookmarks::Entity::find()
            .filter(bookmarks::Column::PostId.eq(post))
            .filter(bookmarks::Column::UserId.eq(user))
            .one(db)
            .await?
            .is_some();
        if !exists {
            bookmarks::ActiveModel {
                id: Set(Uuid::now_v7()),
                user_id: Set(user),
                post_id: Set(post),
                created_at: Set(now.into()),
            }
            .insert(db)
            .await?;
        }
    }
    Ok(report)
}

async fn user_id<C: ConnectionTrait>(db: &C, name: &str) -> Result<Uuid> {
    Ok(users::Entity::find()
        .filter(users::Column::Username.eq(name))
        .one(db)
        .await?
        .with_context(|| format!("user {name} is missing"))?
        .id)
}

async fn post_id<C: ConnectionTrait>(db: &C, title: &str, number: i32) -> Result<Uuid> {
    let topic = topics::Entity::find()
        .filter(topics::Column::Title.eq(title))
        .one(db)
        .await?
        .with_context(|| format!("topic {title:?} is missing"))?;
    Ok(posts::Entity::find()
        .filter(posts::Column::TopicId.eq(topic.id))
        .filter(posts::Column::PostNumber.eq(number))
        .one(db)
        .await?
        .with_context(|| format!("post {title:?} #{number} is missing"))?
        .id)
}

/// Insert one topic with its posts (revision 1 for each, as the handlers do),
/// the edit and the deletion. Returns the number of posts.
async fn demo_topic<C: ConnectionTrait>(db: &C, t: &T, now: DateTime<Utc>) -> Result<usize> {
    let Some(category) = categories::Entity::find()
        .filter(categories::Column::Slug.eq(t.category))
        .one(db)
        .await?
    else {
        bail!("category {} is missing (run `manage seed` first)", t.category);
    };
    let start = now - Duration::days(t.days_ago);
    let at = |minutes: i64| -> DateTime<FixedOffset> { (start + Duration::minutes(minutes)).into() };
    let last = t.posts.last().map(|p| p.1).unwrap_or(0);
    let opener = user_id(db, t.posts[0].0).await?;
    let topic_id = Uuid::now_v7();
    topics::ActiveModel {
        id: Set(topic_id),
        category_id: Set(category.id),
        user_id: Set(opener),
        title: Set(t.title.into()),
        is_pinned: Set(t.pinned),
        is_closed: Set(false),
        views: Set(7 * t.posts.len() as i32 + t.days_ago as i32),
        posts_count: Set(t.posts.len() as i32),
        created_at: Set(at(0)),
        updated_at: Set(at(last)),
        bumped_at: Set(at(last)),
        deleted_at: Set(None),
        deleted_by_id: Set(None),
    }
    .insert(db)
    .await?;

    for (i, P(author, minutes, body)) in t.posts.iter().enumerate() {
        let number = i as i32 + 1;
        let author = user_id(db, author).await?;
        let cooked = markdown::render(body);
        let post = posts::ActiveModel {
            id: Set(Uuid::now_v7()),
            topic_id: Set(topic_id),
            user_id: Set(author),
            post_number: Set(number),
            raw: Set((*body).into()),
            cooked: Set(cooked.clone()),
            created_at: Set(at(*minutes)),
            updated_at: Set(at(*minutes)),
            edited_at: Set(None),
            edit_count: Set(0),
            last_editor_id: Set(None),
            deleted_at: Set(None),
            deleted_by_id: Set(None),
        }
        .insert(db)
        .await?;
        revision(db, post.id, 1, author, body, &cooked, at(*minutes)).await?;

        if (t.title, number) == (EDITED.0, EDITED.1) {
            let edited_at = at(*minutes + 25);
            let cooked = markdown::render(EDITED.2);
            revision(db, post.id, 2, author, EDITED.2, &cooked, edited_at).await?;
            let mut am: posts::ActiveModel = post.clone().into();
            am.raw = Set(EDITED.2.into());
            am.cooked = Set(cooked);
            am.edit_count = Set(1);
            am.edited_at = Set(Some(edited_at));
            am.last_editor_id = Set(Some(author));
            am.updated_at = Set(edited_at);
            am.update(db).await?;
        } else if (t.title, number) == DELETED {
            let mut am: posts::ActiveModel = post.into();
            am.deleted_at = Set(Some(at(*minutes + 5)));
            am.deleted_by_id = Set(Some(author));
            am.update(db).await?;
        }
    }

    for slug in t.tags {
        let name = TAGS.iter().find(|(_, s)| s == slug).map(|(n, _)| *n).unwrap_or(slug);
        let (tag_id, _) = ensure_tag(db, name, slug, now.into()).await?;
        topic_tags::ActiveModel {
            id: Set(Uuid::now_v7()),
            topic_id: Set(topic_id),
            tag_id: Set(tag_id),
        }
        .insert(db)
        .await?;
    }
    Ok(t.posts.len())
}

async fn revision<C: ConnectionTrait>(
    db: &C,
    post_id: Uuid,
    number: i32,
    editor: Uuid,
    raw: &str,
    cooked: &str,
    at: DateTime<FixedOffset>,
) -> Result<()> {
    post_revisions::ActiveModel {
        id: Set(Uuid::now_v7()),
        post_id: Set(post_id),
        editor_id: Set(Some(editor)),
        revision_number: Set(number),
        raw: Set(raw.into()),
        cooked: Set(cooked.into()),
        created_at: Set(at),
    }
    .insert(db)
    .await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::{HashMap, HashSet};

    #[test]
    fn category_tree_is_well_formed() {
        let mut depth: HashMap<&str, i32> = HashMap::new();
        let mut colors = HashSet::new();
        for c in CATEGORIES {
            assert!(colors.insert(c.color.to_ascii_lowercase()), "color {} reused", c.color);
            let d = match c.parent {
                None => 1,
                Some(p) => depth.get(p).copied().expect("parent listed before child") + 1,
            };
            assert!(d <= 3, "{} is deeper than three levels", c.slug);
            assert!(depth.insert(c.slug, d).is_none(), "slug {} repeated", c.slug);
        }
        assert_eq!(depth.values().max(), Some(&3), "some branch reaches three levels");
        assert!(CATEGORIES.iter().any(|c| c.min_trust == Some(0)), "a members-only category");
        assert!(CATEGORIES.iter().any(|c| c.min_trust.is_some_and(|m| m > 0)), "a min-trust category");
    }

    #[test]
    fn demo_content_refers_to_seeded_things() {
        let users: HashSet<_> = DEMO_USERS.iter().map(|u| u.0).collect();
        let tiers: HashSet<_> = DEMO_USERS.iter().map(|u| u.1).collect();
        assert_eq!(tiers.len(), 5, "every trust tier");
        let titles: HashSet<_> = DEMO_TOPICS.iter().map(|t| t.title).collect();
        assert_eq!(titles.len(), DEMO_TOPICS.len(), "titles are the idempotency key");
        for t in DEMO_TOPICS {
            assert!(CATEGORIES.iter().any(|c| c.slug == t.category));
            assert!(t.tags.iter().all(|s| TAGS.iter().any(|(_, slug)| slug == s)));
            assert!(t.posts.iter().all(|p| users.contains(p.0)));
            assert!(t.posts.windows(2).all(|w| w[0].1 < w[1].1), "posts in time order");
        }
        let post_exists = |title: &str, n: i32| {
            DEMO_TOPICS.iter().any(|t| t.title == title && n >= 1 && n as usize <= t.posts.len())
        };
        assert!(post_exists(EDITED.0, EDITED.1));
        assert!(post_exists(DELETED.0, DELETED.1));
        assert!(DEMO_TOPICS.iter().any(|t| t.pinned));
        for (u, key, title, n) in DEMO_REACTIONS {
            assert!(users.contains(u) && REACTIONS.iter().any(|r| r.0 == *key) && post_exists(title, *n));
        }
        let pairs: HashSet<_> = DEMO_REACTIONS.iter().map(|r| (r.0, r.2, r.3)).collect();
        assert_eq!(pairs.len(), DEMO_REACTIONS.len(), "one reaction per user per post");
        for (u, title, n) in DEMO_BOOKMARKS {
            assert!(users.contains(u) && post_exists(title, *n));
        }
    }
}