neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions success · Badges · Packages
⭐
Log in to mark this repository.
manage seed [--demo]: idempotent baseline categories/reactions/tags and dev demo content
95b0c9a · gmorell · 2026-12-02 16:19
Message
{commit_body(@commit)}
Files changed
modified
Justfile
+24
−1
@@ -86,9 +86,32 @@ check:
| 86 | 86 | cargo check --bins --lib |
| 87 | 87 | cargo test --lib |
| 88 | 88 | |
| 89 | −# Bring up just Postgres for local dev | |
| 89 | +# A fresh database (no users yet) is also migrated and given demo content | |
| 90 | +# (`seed --demo`); an existing one is left alone. | |
| 91 | +# Bring up just Postgres for local dev (fresh DB: migrate + seed --demo) | |
| 90 | 92 | db-up: |
| 93 | + #!/usr/bin/env bash | |
| 94 | + set -euo pipefail | |
| 91 | 95 | podman compose up -d postgres |
| 96 | + for _ in $(seq 1 30); do | |
| 97 | + podman exec recourse_postgres pg_isready -U recourse_user -d recourse >/dev/null 2>&1 && break | |
| 98 | + sleep 1 | |
| 99 | + done | |
| 100 | + users=$(podman exec recourse_postgres psql -U recourse_user -d recourse -tAc \ | |
| 101 | + "SELECT CASE WHEN to_regclass('public.users') IS NULL THEN 0 ELSE (SELECT count(*) FROM users) END") | |
| 102 | + if [ "$users" = "0" ]; then | |
| 103 | + echo "▶ fresh database: migrating and seeding demo content" | |
| 104 | + cargo run -p migration -- up | |
| 105 | + cargo run --bin manage -- seed --demo | |
| 106 | + fi | |
| 107 | + | |
| 108 | +# Baseline categories (3 levels), reaction types and tags. Idempotent; fine in production. | |
| 109 | +seed: | |
| 110 | + cargo run --bin manage -- seed | |
| 111 | + | |
| 112 | +# Baseline + demo accounts and conversations. Development only. | |
| 113 | +seed-demo: | |
| 114 | + cargo run --bin manage -- seed --demo | |
| 92 | 115 | |
| 93 | 116 | # Build the runtime image |
| 94 | 117 | build-image: |
modified
README.md
+29
−2
@@ -14,7 +14,7 @@ A small axum web application scaffold with:
| 14 | 14 | ```bash |
| 15 | 15 | just deps # npm install (frontend deps) |
| 16 | 16 | just assets # build CSS + JS + webfonts |
| 17 | −just db-up # start Postgres via podman compose | |
| 17 | +just db-up # start Postgres via podman compose; a fresh DB is migrated and gets demo content | |
| 18 | 18 | just migrate # apply migrations |
| 19 | 19 | just admin alice alice@example.com # first (staff) account; prints its password |
| 20 | 20 | just serve # run the web service on :3000 |
@@ -23,6 +23,32 @@ just serve # run the web service on :3000
| 23 | 23 | Sign in with the printed password. Further members join through invites |
| 24 | 24 | (`just invite`, or the Invites page), or are created the same way. |
| 25 | 25 | |
| 26 | +### Seed and demo data | |
| 27 | + | |
| 28 | +- `just seed` (`manage seed`) creates what any forum can keep: a category tree | |
| 29 | + up to three levels deep (Development › Backend › Databases, Hobbies › Games | |
| 30 | + › Board Games, …) with distinct colors, a members-only category ("Members | |
| 31 | + Lounge", any signed-in account) and a min-trust one ("Regulars' Corner", | |
| 32 | + trust level 3+), the default reaction types if missing, and a few tags. | |
| 33 | +- `just seed-demo` (`manage seed --demo`) adds development data: verified | |
| 34 | + accounts `demo-admin` (staff, Leader), `demo-leader`, `demo-regular`, | |
| 35 | + `demo-member`, `demo-basic` and `demo-new` (one per trust level), **all with | |
| 36 | + the password `recourse-demo`**, and topics spread over the last six weeks | |
| 37 | + with replies, an edited post, a soft-deleted post, reactions, bookmarks, | |
| 38 | + tags and a pinned announcement. | |
| 39 | + | |
| 40 | +Both are idempotent: rows are matched by slug / key / username / topic title | |
| 41 | +and only missing ones are created, so re-running changes nothing and never | |
| 42 | +overwrites edits. `just db-up` runs `seed --demo` only when the database has | |
| 43 | +no users yet. | |
| 44 | + | |
| 45 | +**Production never gets demo content.** Demo accounts share a published | |
| 46 | +password, so nothing automatic runs `--demo`: not the image, not compose, not | |
| 47 | +`AUTO_MIGRATE`. `manage seed --demo` also refuses to run when `PUBLIC_URL` is | |
| 48 | +https unless given `--allow-public`. Plain `manage seed` is safe in production | |
| 49 | +(it only adds missing categories/reactions/tags); run it by hand if you want | |
| 50 | +the starter categories. | |
| 51 | + | |
| 26 | 52 | ### Staff |
| 27 | 53 | |
| 28 | 54 | Staff (category/reaction admin, moderation) is only ever granted on purpose: |
@@ -119,4 +145,5 @@ never taken over, and accounts created this way are never staff. In
| 119 | 145 | - `manage user verify-email <name> | resend-verification <name>` |
| 120 | 146 | - `manage invite create [--email E] [--days N] | list | show <token>` |
| 121 | 147 | - `manage email test <to>` — send a test message through mail-prism (or report it isn't configured) |
| 122 | − - Justfile shortcuts: `just manage …`, `just admin <name> <email>`, `just invite [days]`, `just staff <name>`, `just trust <name> <level>` | |
| 148 | + - `manage seed [--demo [--allow-public]]` — baseline categories/reactions/tags; `--demo` adds demo users and content | |
| 149 | + - Justfile shortcuts: `just manage …`, `just admin <name> <email>`, `just invite [days]`, `just staff <name>`, `just trust <name> <level>`, `just seed`, `just seed-demo` |
modified
src/bin/manage.rs
+51
−0
@@ -14,6 +14,7 @@
| 14 | 14 | //! manage invite list |
| 15 | 15 | //! manage invite show <token> |
| 16 | 16 | //! manage email test <to> |
| 17 | +//! manage seed [--demo [--allow-public]] | |
| 17 | 18 | |
| 18 | 19 | use clap::{Parser, Subcommand}; |
| 19 | 20 | use recourse::config::{create_db_connection, Config}; |
@@ -44,6 +45,16 @@ enum Command {
| 44 | 45 | #[command(subcommand)] |
| 45 | 46 | cmd: InviteCmd, |
| 46 | 47 | }, |
| 48 | + /// Idempotently create the baseline categories, reaction types and tags; | |
| 49 | + /// with --demo also demo accounts and conversations (development only) | |
| 50 | + Seed { | |
| 51 | + /// Also create demo-* accounts (password in the README) and demo topics | |
| 52 | + #[arg(long)] | |
| 53 | + demo: bool, | |
| 54 | + /// Allow --demo even though PUBLIC_URL is https (looks like production) | |
| 55 | + #[arg(long, requires = "demo")] | |
| 56 | + allow_public: bool, | |
| 57 | + }, | |
| 47 | 58 | /// Outbound mail (mail-prism) |
| 48 | 59 | Email { |
| 49 | 60 | #[command(subcommand)] |
@@ -135,6 +146,7 @@ async fn main() -> Result<(), DynErr> {
| 135 | 146 | match cli.command { |
| 136 | 147 | Command::User { cmd } => run_user(&db, &config, cmd).await, |
| 137 | 148 | Command::Email { cmd } => run_email(&config, cmd).await, |
| 149 | + Command::Seed { demo, allow_public } => run_seed(&db, &config, demo, allow_public).await, | |
| 138 | 150 | Command::Invite { cmd } => run_invite(&db, &config, cmd).await, |
| 139 | 151 | } |
| 140 | 152 | } |
@@ -383,3 +395,42 @@ async fn run_email(config: &Config, cmd: EmailCmd) -> Result<(), DynErr> {
| 383 | 395 | } |
| 384 | 396 | Ok(()) |
| 385 | 397 | } |
| 398 | + | |
| 399 | +// ---------------------------------------------------------------------------- | |
| 400 | +// seed | |
| 401 | +// ---------------------------------------------------------------------------- | |
| 402 | + | |
| 403 | +async fn run_seed(db: &DatabaseConnection, config: &Config, demo: bool, allow_public: bool) -> Result<(), DynErr> { | |
| 404 | + use recourse::seed; | |
| 405 | + // Demo accounts share a published password: never on a public instance | |
| 406 | + // by accident. | |
| 407 | + if demo && config.secure_cookies() && !allow_public { | |
| 408 | + return Err(format!( | |
| 409 | + "refusing --demo: PUBLIC_URL ({}) is https, which looks like production. \ | |
| 410 | + Demo accounts share a published password; pass --allow-public if you really mean it.", | |
| 411 | + config.public_url | |
| 412 | + ) | |
| 413 | + .into()); | |
| 414 | + } | |
| 415 | + let base = seed::seed_base(db).await.map_err(|e| format!("{e:#}"))?; | |
| 416 | + println!( | |
| 417 | + "Baseline: {} categories, {} reaction types, {} tags created{}.", | |
| 418 | + base.categories, | |
| 419 | + base.reactions, | |
| 420 | + base.tags, | |
| 421 | + if base.is_empty() { " (already seeded)" } else { "" } | |
| 422 | + ); | |
| 423 | + if demo { | |
| 424 | + let d = seed::seed_demo(db).await.map_err(|e| format!("{e:#}"))?; | |
| 425 | + println!( | |
| 426 | + "Demo: {} users, {} topics, {} posts created{}.", | |
| 427 | + d.users, | |
| 428 | + d.topics, | |
| 429 | + d.posts, | |
| 430 | + if d.is_empty() { " (already seeded)" } else { "" } | |
| 431 | + ); | |
| 432 | + let names: Vec<&str> = seed::DEMO_USERS.iter().map(|u| u.0).collect(); | |
| 433 | + println!("Demo accounts ({}) all use the password: {}", names.join(", "), seed::DEMO_PASSWORD); | |
| 434 | + } | |
| 435 | + Ok(()) | |
| 436 | +} |
modified
src/lib.rs
+1
−0
@@ -6,6 +6,7 @@ pub mod entities;
| 6 | 6 | pub mod handlers; |
| 7 | 7 | pub mod mailer; |
| 8 | 8 | pub mod markdown; |
| 9 | +pub mod seed; | |
| 9 | 10 | pub mod middleware; |
| 10 | 11 | pub mod timeutil; |
| 11 | 12 | pub mod trust; |
added
src/seed.rs
+606
−0
@@ -0,0 +1,606 @@
| 1 | +//! `manage seed [--demo]`: baseline data, plus optional demo content. | |
| 2 | +//! | |
| 3 | +//! Every step looks its row up by a natural key (category slug, reaction key, | |
| 4 | +//! tag slug, demo username, demo topic title) and only inserts what is | |
| 5 | +//! missing, so running it again changes nothing, and it never edits rows an | |
| 6 | +//! operator has since changed. | |
| 7 | +//! | |
| 8 | +//! * `seed` — what a real forum can keep: a category tree three levels deep | |
| 9 | +//! with distinct colors, a members-only category (`min_trust_level = 0`: any | |
| 10 | +//! signed-in account) and a min-trust one (Regular, 3), the default reaction | |
| 11 | +//! types, and a few tags. | |
| 12 | +//! * `seed --demo` — fake people and conversations for development: `demo-*` | |
| 13 | +//! accounts at every trust tier (verified, password [`DEMO_PASSWORD`]), | |
| 14 | +//! topics with replies, an edited post, a soft-deleted post, reactions, | |
| 15 | +//! bookmarks, tags, a pinned topic, spread over the last few weeks. It is | |
| 16 | +//! never run by the image, compose or `AUTO_MIGRATE`; `manage` refuses it | |
| 17 | +//! when `PUBLIC_URL` is https unless `--allow-public` is given. | |
| 18 | + | |
| 19 | +use anyhow::{bail, Context, Result}; | |
| 20 | +use chrono::{DateTime, Duration, FixedOffset, Utc}; | |
| 21 | +use sea_orm::*; | |
| 22 | +use uuid::Uuid; | |
| 23 | + | |
| 24 | +use crate::auth; | |
| 25 | +use crate::entities::{ | |
| 26 | + bookmarks, categories, post_reactions, post_revisions, posts, reaction_types, tags, topic_tags, topics, users, | |
| 27 | +}; | |
| 28 | +use crate::markdown; | |
| 29 | + | |
| 30 | +/// Password of every `demo-*` account (documented in the README). Demo data is | |
| 31 | +/// for development only. | |
| 32 | +pub const DEMO_PASSWORD: &str = "recourse-demo"; | |
| 33 | + | |
| 34 | +/// A category to seed: `(slug, name, color, parent slug, min trust, description)`. | |
| 35 | +pub struct CategorySeed { | |
| 36 | + pub slug: &'static str, | |
| 37 | + pub name: &'static str, | |
| 38 | + pub color: &'static str, | |
| 39 | + pub parent: Option<&'static str>, | |
| 40 | + pub min_trust: Option<i32>, | |
| 41 | + pub description: &'static str, | |
| 42 | +} | |
| 43 | + | |
| 44 | +const fn cat( | |
| 45 | + slug: &'static str, | |
| 46 | + name: &'static str, | |
| 47 | + color: &'static str, | |
| 48 | + parent: Option<&'static str>, | |
| 49 | + min_trust: Option<i32>, | |
| 50 | + description: &'static str, | |
| 51 | +) -> CategorySeed { | |
| 52 | + CategorySeed { slug, name, color, parent, min_trust, description } | |
| 53 | +} | |
| 54 | + | |
| 55 | +/// Parents come before their children. `announcements` and `general` are | |
| 56 | +/// also created by the forum migration; listing them keeps `seed` complete on | |
| 57 | +/// its own. | |
| 58 | +pub const CATEGORIES: &[CategorySeed] = &[ | |
| 59 | + cat("announcements", "Announcements", "#E45735", None, None, "Official announcements and news."), | |
| 60 | + cat("general", "General", "#0088CC", None, None, "General discussion about anything."), | |
| 61 | + cat("development", "Development", "#25AAE2", None, None, "Building things: code, tools and infrastructure."), | |
| 62 | + cat("backend", "Backend", "#3AB54A", Some("development"), None, "Servers, APIs and everything behind them."), | |
| 63 | + cat("databases", "Databases", "#12A89D", Some("backend"), None, "Schemas, queries, migrations and tuning."), | |
| 64 | + cat("frontend", "Frontend", "#F7941D", Some("development"), None, "HTML, CSS, htmx and the browser."), | |
| 65 | + cat("hobbies", "Hobbies", "#9EB83B", None, None, "What we do when we're not at a keyboard."), | |
| 66 | + cat("games", "Games", "#BF1E2E", Some("hobbies"), None, "Video, board, card and tabletop games."), | |
| 67 | + cat("board-games", "Board Games", "#652D90", Some("games"), None, "Cardboard, dice and meeples."), | |
| 68 | + cat("feedback", "Site Feedback", "#808281", None, None, "Bugs, ideas and questions about this forum."), | |
| 69 | + cat("members", "Members Lounge", "#D4AF37", None, Some(0), "Members only: visible to signed-in accounts."), | |
| 70 | + cat("regulars", "Regulars' Corner", "#ED207B", None, Some(3), "For trust level 3 (Regular) and up."), | |
| 71 | +]; | |
| 72 | + | |
| 73 | +/// The reaction types the reactions migration installs. | |
| 74 | +pub const REACTIONS: &[(&str, &str)] = &[("heart", "\u{2764}\u{FE0F}"), ("star", "\u{2B50}"), ("thumbsup", "\u{1F44D}")]; | |
| 75 | + | |
| 76 | +/// `(name, slug)`. | |
| 77 | +pub const TAGS: &[(&str, &str)] = &[ | |
| 78 | + ("rust", "rust"), | |
| 79 | + ("postgres", "postgres"), | |
| 80 | + ("htmx", "htmx"), | |
| 81 | + ("help", "help"), | |
| 82 | + ("meta", "meta"), | |
| 83 | + ("show-and-tell", "show-and-tell"), | |
| 84 | +]; | |
| 85 | + | |
| 86 | +/// What a run created (everything else already existed). | |
| 87 | +#[derive(Debug, Default, PartialEq, Eq)] | |
| 88 | +pub struct Report { | |
| 89 | + pub categories: usize, | |
| 90 | + pub reactions: usize, | |
| 91 | + pub tags: usize, | |
| 92 | + pub users: usize, | |
| 93 | + pub topics: usize, | |
| 94 | + pub posts: usize, | |
| 95 | +} | |
| 96 | + | |
| 97 | +impl Report { | |
| 98 | + pub fn is_empty(&self) -> bool { | |
| 99 | + *self == Report::default() | |
| 100 | + } | |
| 101 | +} | |
| 102 | + | |
| 103 | +/// The baseline: categories, reaction types, tags. | |
| 104 | +pub async fn seed_base<C: ConnectionTrait>(db: &C) -> Result<Report> { | |
| 105 | + let mut report = Report::default(); | |
| 106 | + let now: DateTime<FixedOffset> = Utc::now().into(); | |
| 107 | + | |
| 108 | + for (position, c) in CATEGORIES.iter().enumerate() { | |
| 109 | + if categories::Entity::find() | |
| 110 | + .filter(categories::Column::Slug.eq(c.slug)) | |
| 111 | + .one(db) | |
| 112 | + .await? | |
| 113 | + .is_some() | |
| 114 | + { | |
| 115 | + continue; | |
| 116 | + } | |
| 117 | + let parent_id = match c.parent { | |
| 118 | + None => None, | |
| 119 | + Some(slug) => Some( | |
| 120 | + categories::Entity::find() | |
| 121 | + .filter(categories::Column::Slug.eq(slug)) | |
| 122 | + .one(db) | |
| 123 | + .await? | |
| 124 | + .with_context(|| format!("parent category {slug} is missing"))? | |
| 125 | + .id, | |
| 126 | + ), | |
| 127 | + }; | |
| 128 | + categories::ActiveModel { | |
| 129 | + id: Set(Uuid::now_v7()), | |
| 130 | + name: Set(c.name.into()), | |
| 131 | + slug: Set(c.slug.into()), | |
| 132 | + description: Set(Some(c.description.into())), | |
| 133 | + color: Set(c.color.into()), | |
| 134 | + position: Set(position as i32), | |
| 135 | + parent_id: Set(parent_id), | |
| 136 | + min_trust_level: Set(c.min_trust), | |
| 137 | + created_at: Set(now), | |
| 138 | + updated_at: Set(now), | |
| 139 | + } | |
| 140 | + .insert(db) | |
| 141 | + .await | |
| 142 | + .with_context(|| format!("insert category {}", c.slug))?; | |
| 143 | + report.categories += 1; | |
| 144 | + } | |
| 145 | + | |
| 146 | + for (position, (key, emoji)) in REACTIONS.iter().enumerate() { | |
| 147 | + if reaction_types::Entity::find() | |
| 148 | + .filter(reaction_types::Column::Key.eq(*key)) | |
| 149 | + .one(db) | |
| 150 | + .await? | |
| 151 | + .is_none() | |
| 152 | + { | |
| 153 | + reaction_types::ActiveModel { | |
| 154 | + id: Set(Uuid::now_v7()), | |
| 155 | + key: Set((*key).into()), | |
| 156 | + emoji: Set((*emoji).into()), | |
| 157 | + position: Set(position as i32), | |
| 158 | + is_active: Set(true), | |
| 159 | + created_at: Set(now), | |
| 160 | + } | |
| 161 | + .insert(db) | |
| 162 | + .await?; | |
| 163 | + report.reactions += 1; | |
| 164 | + } | |
| 165 | + } | |
| 166 | + | |
| 167 | + for (name, slug) in TAGS { | |
| 168 | + if ensure_tag(db, name, slug, now).await?.1 { | |
| 169 | + report.tags += 1; | |
| 170 | + } | |
| 171 | + } | |
| 172 | + Ok(report) | |
| 173 | +} | |
| 174 | + | |
| 175 | +async fn ensure_tag<C: ConnectionTrait>( | |
| 176 | + db: &C, | |
| 177 | + name: &str, | |
| 178 | + slug: &str, | |
| 179 | + now: DateTime<FixedOffset>, | |
| 180 | +) -> Result<(Uuid, bool)> { | |
| 181 | + if let Some(t) = tags::Entity::find().filter(tags::Column::Slug.eq(slug)).one(db).await? { | |
| 182 | + return Ok((t.id, false)); | |
| 183 | + } | |
| 184 | + let t = tags::ActiveModel { | |
| 185 | + id: Set(Uuid::now_v7()), | |
| 186 | + name: Set(name.into()), | |
| 187 | + slug: Set(slug.into()), | |
| 188 | + created_at: Set(now), | |
| 189 | + } | |
| 190 | + .insert(db) | |
| 191 | + .await?; | |
| 192 | + Ok((t.id, true)) | |
| 193 | +} | |
| 194 | + | |
| 195 | +/// `(username, trust level, staff, joined days ago)`. | |
| 196 | +pub const DEMO_USERS: &[(&str, i32, bool, i64)] = &[ | |
| 197 | + ("demo-admin", 4, true, 120), | |
| 198 | + ("demo-leader", 4, false, 110), | |
| 199 | + ("demo-regular", 3, false, 90), | |
| 200 | + ("demo-member", 2, false, 60), | |
| 201 | + ("demo-basic", 1, false, 30), | |
| 202 | + ("demo-new", 0, false, 2), | |
| 203 | +]; | |
| 204 | + | |
| 205 | +/// One demo post: author, minutes after the topic started, body. | |
| 206 | +struct P(&'static str, i64, &'static str); | |
| 207 | + | |
| 208 | +/// One demo topic: category, author, title, days ago, pinned, tags, posts | |
| 209 | +/// (the first is the opening post). | |
| 210 | +struct T { | |
| 211 | + category: &'static str, | |
| 212 | + title: &'static str, | |
| 213 | + days_ago: i64, | |
| 214 | + pinned: bool, | |
| 215 | + tags: &'static [&'static str], | |
| 216 | + posts: &'static [P], | |
| 217 | +} | |
| 218 | + | |
| 219 | +const DEMO_TOPICS: &[T] = &[ | |
| 220 | + T { | |
| 221 | + category: "announcements", | |
| 222 | + title: "Welcome to the demo forum", | |
| 223 | + days_ago: 40, | |
| 224 | + pinned: true, | |
| 225 | + tags: &["meta"], | |
| 226 | + posts: &[ | |
| 227 | + 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."), | |
| 228 | + P("demo-leader", 30, "Thanks for setting this up. Pinned topics stay at the top of their category."), | |
| 229 | + P("demo-member", 300, "Glad to be here :)"), | |
| 230 | + ], | |
| 231 | + }, | |
| 232 | + T { | |
| 233 | + category: "databases", | |
| 234 | + title: "Choosing indexes for a topic list", | |
| 235 | + days_ago: 21, | |
| 236 | + pinned: false, | |
| 237 | + tags: &["postgres", "help"], | |
| 238 | + posts: &[ | |
| 239 | + 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```"), | |
| 240 | + P("demo-leader", 45, "Yes, and make it partial on `deleted_at IS NULL` if most reads skip deleted topics."), | |
| 241 | + P("demo-basic", 90, "What about the category filter?"), | |
| 242 | + P("demo-regular", 180, "A composite `(category_id, bumped_at DESC)` covers that."), | |
| 243 | + ], | |
| 244 | + }, | |
| 245 | + T { | |
| 246 | + category: "frontend", | |
| 247 | + title: "htmx boosted links and fragments", | |
| 248 | + days_ago: 12, | |
| 249 | + pinned: false, | |
| 250 | + tags: &["htmx", "show-and-tell"], | |
| 251 | + posts: &[ | |
| 252 | + P("demo-member", 0, "Boosting the body means every partial needs `hx-select=\"unset\"`, or it inherits `#content`."), | |
| 253 | + P("demo-regular", 20, "Same trick for `hx-target`. Took me a while to spot."), | |
| 254 | + P("demo-new", 60, "This reply was removed by its author."), | |
| 255 | + ], | |
| 256 | + }, | |
| 257 | + T { | |
| 258 | + category: "backend", | |
| 259 | + title: "axum extractors: order matters", | |
| 260 | + days_ago: 7, | |
| 261 | + pinned: false, | |
| 262 | + tags: &["rust"], | |
| 263 | + posts: &[ | |
| 264 | + P("demo-leader", 0, "The body-consuming extractor (`Form`, `Json`) has to be last."), | |
| 265 | + P("demo-basic", 15, "Good to know, thanks!"), | |
| 266 | + ], | |
| 267 | + }, | |
| 268 | + T { | |
| 269 | + category: "board-games", | |
| 270 | + title: "What's on your table this month?", | |
| 271 | + days_ago: 3, | |
| 272 | + pinned: false, | |
| 273 | + tags: &[], | |
| 274 | + posts: &[ | |
| 275 | + P("demo-basic", 0, "Lots of Azul here."), | |
| 276 | + P("demo-member", 120, "Spirit Island, every week."), | |
| 277 | + P("demo-leader", 600, "Cascadia with the kids."), | |
| 278 | + ], | |
| 279 | + }, | |
| 280 | + T { | |
| 281 | + category: "members", | |
| 282 | + title: "Members-only: introduce yourself", | |
| 283 | + days_ago: 15, | |
| 284 | + pinned: false, | |
| 285 | + tags: &[], | |
| 286 | + posts: &[ | |
| 287 | + P("demo-member", 0, "Only signed-in accounts can see this category."), | |
| 288 | + P("demo-new", 10, "Hi, I'm new!"), | |
| 289 | + ], | |
| 290 | + }, | |
| 291 | + T { | |
| 292 | + category: "regulars", | |
| 293 | + title: "Regulars: moderation notes", | |
| 294 | + days_ago: 5, | |
| 295 | + pinned: false, | |
| 296 | + tags: &["meta"], | |
| 297 | + posts: &[P("demo-regular", 0, "Trust level 3 and up (and staff) can read this.")], | |
| 298 | + }, | |
| 299 | + T { | |
| 300 | + category: "general", | |
| 301 | + title: "Small talk", | |
| 302 | + days_ago: 1, | |
| 303 | + pinned: false, | |
| 304 | + tags: &[], | |
| 305 | + posts: &[P("demo-new", 0, "Is it weekend yet?")], | |
| 306 | + }, | |
| 307 | +]; | |
| 308 | + | |
| 309 | +/// The opening post of "Choosing indexes…" is edited once. | |
| 310 | +const EDITED: (&str, i32, &str) = ( | |
| 311 | + "Choosing indexes for a topic list", | |
| 312 | + 1, | |
| 313 | + "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.", | |
| 314 | +); | |
| 315 | +/// Post 3 of the htmx topic is soft-deleted by its author. | |
| 316 | +const DELETED: (&str, i32) = ("htmx boosted links and fragments", 3); | |
| 317 | + | |
| 318 | +/// `(username, reaction key, topic title, post number)`. | |
| 319 | +const DEMO_REACTIONS: &[(&str, &str, &str, i32)] = &[ | |
| 320 | + ("demo-member", "heart", "Welcome to the demo forum", 1), | |
| 321 | + ("demo-basic", "thumbsup", "Welcome to the demo forum", 1), | |
| 322 | + ("demo-regular", "star", "Welcome to the demo forum", 1), | |
| 323 | + ("demo-leader", "thumbsup", "Choosing indexes for a topic list", 4), | |
| 324 | + ("demo-member", "star", "Choosing indexes for a topic list", 2), | |
| 325 | + ("demo-regular", "heart", "htmx boosted links and fragments", 1), | |
| 326 | + ("demo-admin", "thumbsup", "axum extractors: order matters", 1), | |
| 327 | +]; | |
| 328 | + | |
| 329 | +/// `(username, topic title, post number)`. | |
| 330 | +const DEMO_BOOKMARKS: &[(&str, &str, i32)] = &[ | |
| 331 | + ("demo-member", "Choosing indexes for a topic list", 2), | |
| 332 | + ("demo-member", "axum extractors: order matters", 1), | |
| 333 | + ("demo-basic", "htmx boosted links and fragments", 1), | |
| 334 | +]; | |
| 335 | + | |
| 336 | +/// Demo accounts and content (after [`seed_base`]). | |
| 337 | +pub async fn seed_demo(db: &DatabaseConnection) -> Result<Report> { | |
| 338 | + let mut report = Report::default(); | |
| 339 | + let now = Utc::now(); | |
| 340 | + | |
| 341 | + for (name, level, staff, joined) in DEMO_USERS { | |
| 342 | + if users::Entity::find().filter(users::Column::Username.eq(*name)).one(db).await?.is_some() { | |
| 343 | + continue; | |
| 344 | + } | |
| 345 | + let email = format!("{name}@demo.invalid"); | |
| 346 | + let user = auth::create_user_direct(db, name, &email, DEMO_PASSWORD, *staff) | |
| 347 | + .await | |
| 348 | + .with_context(|| format!("create {name}"))?; | |
| 349 | + let joined_at: DateTime<FixedOffset> = (now - Duration::days(*joined)).into(); | |
| 350 | + let mut am: users::ActiveModel = user.into(); | |
| 351 | + am.trust_level = Set(*level); | |
| 352 | + am.created_at = Set(joined_at); | |
| 353 | + am.email_verified_at = Set(Some(joined_at)); | |
| 354 | + am.update(db).await?; | |
| 355 | + report.users += 1; | |
| 356 | + } | |
| 357 | + | |
| 358 | + for t in DEMO_TOPICS { | |
| 359 | + if topics::Entity::find().filter(topics::Column::Title.eq(t.title)).one(db).await?.is_some() { | |
| 360 | + continue; | |
| 361 | + } | |
| 362 | + let txn = db.begin().await?; | |
| 363 | + report.posts += demo_topic(&txn, t, now).await.with_context(|| format!("topic {:?}", t.title))?; | |
| 364 | + txn.commit().await?; | |
| 365 | + report.topics += 1; | |
| 366 | + } | |
| 367 | + | |
| 368 | + for (name, key, title, number) in DEMO_REACTIONS { | |
| 369 | + let user = user_id(db, name).await?; | |
| 370 | + let post = post_id(db, title, *number).await?; | |
| 371 | + let reaction = reaction_types::Entity::find() | |
| 372 | + .filter(reaction_types::Column::Key.eq(*key)) | |
| 373 | + .one(db) | |
| 374 | + .await? | |
| 375 | + .with_context(|| format!("reaction {key}"))?; | |
| 376 | + let exists = post_reactions::Entity::find() | |
| 377 | + .filter(post_reactions::Column::PostId.eq(post)) | |
| 378 | + .filter(post_reactions::Column::UserId.eq(user)) | |
| 379 | + .one(db) | |
| 380 | + .await? | |
| 381 | + .is_some(); | |
| 382 | + if !exists { | |
| 383 | + post_reactions::ActiveModel { | |
| 384 | + id: Set(Uuid::now_v7()), | |
| 385 | + post_id: Set(post), | |
| 386 | + user_id: Set(user), | |
| 387 | + reaction_id: Set(reaction.id), | |
| 388 | + created_at: Set(now.into()), | |
| 389 | + } | |
| 390 | + .insert(db) | |
| 391 | + .await?; | |
| 392 | + } | |
| 393 | + } | |
| 394 | + | |
| 395 | + for (name, title, number) in DEMO_BOOKMARKS { | |
| 396 | + let user = user_id(db, name).await?; | |
| 397 | + let post = post_id(db, title, *number).await?; | |
| 398 | + let exists = bookmarks::Entity::find() | |
| 399 | + .filter(bookmarks::Column::PostId.eq(post)) | |
| 400 | + .filter(bookmarks::Column::UserId.eq(user)) | |
| 401 | + .one(db) | |
| 402 | + .await? | |
| 403 | + .is_some(); | |
| 404 | + if !exists { | |
| 405 | + bookmarks::ActiveModel { | |
| 406 | + id: Set(Uuid::now_v7()), | |
| 407 | + user_id: Set(user), | |
| 408 | + post_id: Set(post), | |
| 409 | + created_at: Set(now.into()), | |
| 410 | + } | |
| 411 | + .insert(db) | |
| 412 | + .await?; | |
| 413 | + } | |
| 414 | + } | |
| 415 | + Ok(report) | |
| 416 | +} | |
| 417 | + | |
| 418 | +async fn user_id<C: ConnectionTrait>(db: &C, name: &str) -> Result<Uuid> { | |
| 419 | + Ok(users::Entity::find() | |
| 420 | + .filter(users::Column::Username.eq(name)) | |
| 421 | + .one(db) | |
| 422 | + .await? | |
| 423 | + .with_context(|| format!("user {name} is missing"))? | |
| 424 | + .id) | |
| 425 | +} | |
| 426 | + | |
| 427 | +async fn post_id<C: ConnectionTrait>(db: &C, title: &str, number: i32) -> Result<Uuid> { | |
| 428 | + let topic = topics::Entity::find() | |
| 429 | + .filter(topics::Column::Title.eq(title)) | |
| 430 | + .one(db) | |
| 431 | + .await? | |
| 432 | + .with_context(|| format!("topic {title:?} is missing"))?; | |
| 433 | + Ok(posts::Entity::find() | |
| 434 | + .filter(posts::Column::TopicId.eq(topic.id)) | |
| 435 | + .filter(posts::Column::PostNumber.eq(number)) | |
| 436 | + .one(db) | |
| 437 | + .await? | |
| 438 | + .with_context(|| format!("post {title:?} #{number} is missing"))? | |
| 439 | + .id) | |
| 440 | +} | |
| 441 | + | |
| 442 | +/// Insert one topic with its posts (revision 1 for each, as the handlers do), | |
| 443 | +/// the edit and the deletion. Returns the number of posts. | |
| 444 | +async fn demo_topic<C: ConnectionTrait>(db: &C, t: &T, now: DateTime<Utc>) -> Result<usize> { | |
| 445 | + let Some(category) = categories::Entity::find() | |
| 446 | + .filter(categories::Column::Slug.eq(t.category)) | |
| 447 | + .one(db) | |
| 448 | + .await? | |
| 449 | + else { | |
| 450 | + bail!("category {} is missing (run `manage seed` first)", t.category); | |
| 451 | + }; | |
| 452 | + let start = now - Duration::days(t.days_ago); | |
| 453 | + let at = |minutes: i64| -> DateTime<FixedOffset> { (start + Duration::minutes(minutes)).into() }; | |
| 454 | + let last = t.posts.last().map(|p| p.1).unwrap_or(0); | |
| 455 | + let opener = user_id(db, t.posts[0].0).await?; | |
| 456 | + let topic_id = Uuid::now_v7(); | |
| 457 | + topics::ActiveModel { | |
| 458 | + id: Set(topic_id), | |
| 459 | + category_id: Set(category.id), | |
| 460 | + user_id: Set(opener), | |
| 461 | + title: Set(t.title.into()), | |
| 462 | + is_pinned: Set(t.pinned), | |
| 463 | + is_closed: Set(false), | |
| 464 | + views: Set(7 * t.posts.len() as i32 + t.days_ago as i32), | |
| 465 | + posts_count: Set(t.posts.len() as i32), | |
| 466 | + created_at: Set(at(0)), | |
| 467 | + updated_at: Set(at(last)), | |
| 468 | + bumped_at: Set(at(last)), | |
| 469 | + deleted_at: Set(None), | |
| 470 | + deleted_by_id: Set(None), | |
| 471 | + } | |
| 472 | + .insert(db) | |
| 473 | + .await?; | |
| 474 | + | |
| 475 | + for (i, P(author, minutes, body)) in t.posts.iter().enumerate() { | |
| 476 | + let number = i as i32 + 1; | |
| 477 | + let author = user_id(db, author).await?; | |
| 478 | + let cooked = markdown::render(body); | |
| 479 | + let post = posts::ActiveModel { | |
| 480 | + id: Set(Uuid::now_v7()), | |
| 481 | + topic_id: Set(topic_id), | |
| 482 | + user_id: Set(author), | |
| 483 | + post_number: Set(number), | |
| 484 | + raw: Set((*body).into()), | |
| 485 | + cooked: Set(cooked.clone()), | |
| 486 | + created_at: Set(at(*minutes)), | |
| 487 | + updated_at: Set(at(*minutes)), | |
| 488 | + edited_at: Set(None), | |
| 489 | + edit_count: Set(0), | |
| 490 | + last_editor_id: Set(None), | |
| 491 | + deleted_at: Set(None), | |
| 492 | + deleted_by_id: Set(None), | |
| 493 | + } | |
| 494 | + .insert(db) | |
| 495 | + .await?; | |
| 496 | + revision(db, post.id, 1, author, body, &cooked, at(*minutes)).await?; | |
| 497 | + | |
| 498 | + if (t.title, number) == (EDITED.0, EDITED.1) { | |
| 499 | + let edited_at = at(*minutes + 25); | |
| 500 | + let cooked = markdown::render(EDITED.2); | |
| 501 | + revision(db, post.id, 2, author, EDITED.2, &cooked, edited_at).await?; | |
| 502 | + let mut am: posts::ActiveModel = post.clone().into(); | |
| 503 | + am.raw = Set(EDITED.2.into()); | |
| 504 | + am.cooked = Set(cooked); | |
| 505 | + am.edit_count = Set(1); | |
| 506 | + am.edited_at = Set(Some(edited_at)); | |
| 507 | + am.last_editor_id = Set(Some(author)); | |
| 508 | + am.updated_at = Set(edited_at); | |
| 509 | + am.update(db).await?; | |
| 510 | + } else if (t.title, number) == DELETED { | |
| 511 | + let mut am: posts::ActiveModel = post.into(); | |
| 512 | + am.deleted_at = Set(Some(at(*minutes + 5))); | |
| 513 | + am.deleted_by_id = Set(Some(author)); | |
| 514 | + am.update(db).await?; | |
| 515 | + } | |
| 516 | + } | |
| 517 | + | |
| 518 | + for slug in t.tags { | |
| 519 | + let name = TAGS.iter().find(|(_, s)| s == slug).map(|(n, _)| *n).unwrap_or(slug); | |
| 520 | + let (tag_id, _) = ensure_tag(db, name, slug, now.into()).await?; | |
| 521 | + topic_tags::ActiveModel { | |
| 522 | + id: Set(Uuid::now_v7()), | |
| 523 | + topic_id: Set(topic_id), | |
| 524 | + tag_id: Set(tag_id), | |
| 525 | + } | |
| 526 | + .insert(db) | |
| 527 | + .await?; | |
| 528 | + } | |
| 529 | + Ok(t.posts.len()) | |
| 530 | +} | |
| 531 | + | |
| 532 | +async fn revision<C: ConnectionTrait>( | |
| 533 | + db: &C, | |
| 534 | + post_id: Uuid, | |
| 535 | + number: i32, | |
| 536 | + editor: Uuid, | |
| 537 | + raw: &str, | |
| 538 | + cooked: &str, | |
| 539 | + at: DateTime<FixedOffset>, | |
| 540 | +) -> Result<()> { | |
| 541 | + post_revisions::ActiveModel { | |
| 542 | + id: Set(Uuid::now_v7()), | |
| 543 | + post_id: Set(post_id), | |
| 544 | + editor_id: Set(Some(editor)), | |
| 545 | + revision_number: Set(number), | |
| 546 | + raw: Set(raw.into()), | |
| 547 | + cooked: Set(cooked.into()), | |
| 548 | + created_at: Set(at), | |
| 549 | + } | |
| 550 | + .insert(db) | |
| 551 | + .await?; | |
| 552 | + Ok(()) | |
| 553 | +} | |
| 554 | + | |
| 555 | +#[cfg(test)] | |
| 556 | +mod tests { | |
| 557 | + use super::*; | |
| 558 | + use std::collections::{HashMap, HashSet}; | |
| 559 | + | |
| 560 | + #[test] | |
| 561 | + fn category_tree_is_well_formed() { | |
| 562 | + let mut depth: HashMap<&str, i32> = HashMap::new(); | |
| 563 | + let mut colors = HashSet::new(); | |
| 564 | + for c in CATEGORIES { | |
| 565 | + assert!(colors.insert(c.color.to_ascii_lowercase()), "color {} reused", c.color); | |
| 566 | + let d = match c.parent { | |
| 567 | + None => 1, | |
| 568 | + Some(p) => depth.get(p).copied().expect("parent listed before child") + 1, | |
| 569 | + }; | |
| 570 | + assert!(d <= 3, "{} is deeper than three levels", c.slug); | |
| 571 | + assert!(depth.insert(c.slug, d).is_none(), "slug {} repeated", c.slug); | |
| 572 | + } | |
| 573 | + assert_eq!(depth.values().max(), Some(&3), "some branch reaches three levels"); | |
| 574 | + assert!(CATEGORIES.iter().any(|c| c.min_trust == Some(0)), "a members-only category"); | |
| 575 | + assert!(CATEGORIES.iter().any(|c| c.min_trust.is_some_and(|m| m > 0)), "a min-trust category"); | |
| 576 | + } | |
| 577 | + | |
| 578 | + #[test] | |
| 579 | + fn demo_content_refers_to_seeded_things() { | |
| 580 | + let users: HashSet<_> = DEMO_USERS.iter().map(|u| u.0).collect(); | |
| 581 | + let tiers: HashSet<_> = DEMO_USERS.iter().map(|u| u.1).collect(); | |
| 582 | + assert_eq!(tiers.len(), 5, "every trust tier"); | |
| 583 | + let titles: HashSet<_> = DEMO_TOPICS.iter().map(|t| t.title).collect(); | |
| 584 | + assert_eq!(titles.len(), DEMO_TOPICS.len(), "titles are the idempotency key"); | |
| 585 | + for t in DEMO_TOPICS { | |
| 586 | + assert!(CATEGORIES.iter().any(|c| c.slug == t.category)); | |
| 587 | + assert!(t.tags.iter().all(|s| TAGS.iter().any(|(_, slug)| slug == s))); | |
| 588 | + assert!(t.posts.iter().all(|p| users.contains(p.0))); | |
| 589 | + assert!(t.posts.windows(2).all(|w| w[0].1 < w[1].1), "posts in time order"); | |
| 590 | + } | |
| 591 | + let post_exists = |title: &str, n: i32| { | |
| 592 | + DEMO_TOPICS.iter().any(|t| t.title == title && n >= 1 && n as usize <= t.posts.len()) | |
| 593 | + }; | |
| 594 | + assert!(post_exists(EDITED.0, EDITED.1)); | |
| 595 | + assert!(post_exists(DELETED.0, DELETED.1)); | |
| 596 | + assert!(DEMO_TOPICS.iter().any(|t| t.pinned)); | |
| 597 | + for (u, key, title, n) in DEMO_REACTIONS { | |
| 598 | + assert!(users.contains(u) && REACTIONS.iter().any(|r| r.0 == *key) && post_exists(title, *n)); | |
| 599 | + } | |
| 600 | + let pairs: HashSet<_> = DEMO_REACTIONS.iter().map(|r| (r.0, r.2, r.3)).collect(); | |
| 601 | + assert_eq!(pairs.len(), DEMO_REACTIONS.len(), "one reaction per user per post"); | |
| 602 | + for (u, title, n) in DEMO_BOOKMARKS { | |
| 603 | + assert!(users.contains(u) && post_exists(title, *n)); | |
| 604 | + } | |
| 605 | + } | |
| 606 | +} |
Parents: de2cabc