manage seed: a one-time pinned welcome topic in Announcements

313874d · gmorell · 2026-12-03 04:45

12 files +347 -12
Message
{commit_body(@commit)}

Files changed

modified README.md
+22 −7
@@ -33,6 +33,7 @@ just assets # build CSS + JS + webfonts
33 33 just db-up # start Postgres via podman compose; a fresh DB is migrated and gets demo content
34 34 just migrate # apply migrations
35 35 just admin alice alice@example.com # first (staff) account; prints its password
36 +just seed # starter categories, reactions, tags and the welcome topic (needs the staff account above)
36 37 just serve # run the web service on :3000
37 38 ```
38 39
@@ -45,28 +46,42 @@ Sign in with the printed password. Further members join through invites
45 46 up to three levels deep (Development › Backend › Databases, Hobbies › Games
46 47 › Board Games, …) with distinct colors, a members-only category ("Members
47 48 Lounge", any signed-in account) and a min-trust one ("Regulars' Corner",
48 − trust level 3+), the default reaction types if missing, and a few tags.
49 + trust level 3+), the default reaction types if missing, a few tags, and a
50 + pinned **"Welcome to {APP_NAME}"** topic in Announcements: a short starter
51 + (what the forum is for, left for staff to fill in, then verifying email,
52 + trust levels, layouts, reactions/bookmarks/watching, flagging, Markdown and
53 + the exit page) written by the oldest staff account, for staff to edit. It
54 + is made once, ever: a `seed_markers` row records it, so renaming, editing or
55 + deleting the topic (or changing `APP_NAME`) never brings it back. With no
56 + staff account yet it's skipped ("create a staff account first … then re-run
57 + manage seed"), so create the first account before seeding; with no
58 + `announcements` category it's skipped too. It's inserted quietly: no
59 + notifications. `manage seed` prints `Welcome topic: created`, `already
60 + seeded`, or why it was skipped.
49 61 - `just seed-demo` (`manage seed --demo`) adds development data: verified
50 62 accounts `demo-admin` (staff, Leader), `demo-leader`, `demo-regular`,
51 63 `demo-member`, `demo-basic` and `demo-new` (one per trust level), **all with
52 64 the password `recourse-demo`**, and topics spread over the last six weeks
53 65 with replies, an edited post, a soft-deleted post, reactions, bookmarks,
54 − tags and a pinned announcement; and moderation in use: staff-only
66 + tags and a pinned announcement (the demo's own welcome; the baseline welcome
67 + above is added by `demo-admin` too, so both show); and moderation in use: staff-only
55 68 Announcements with reactions off, a read-only "Leaders' Council" (Basic reads, Regulars post),
56 69 a locked topic with a staff-moderated post whose original is hidden, a
57 70 pending flag, and their moderation-log lines.
58 71
59 72 Both are idempotent: rows are matched by slug / key / username / topic title
60 −and only missing ones are created, so re-running changes nothing and never
61 −overwrites edits. `just db-up` runs `seed --demo` only when the database has
73 +(the welcome by its `seed_markers` row) and only missing ones are created, so
74 +re-running changes nothing and never overwrites edits. An instance seeded
75 +before the welcome existed gets it on its next `manage seed`, and nothing else
76 +changes. `just db-up` runs `seed --demo` only when the database has
62 77 no users yet.
63 78
64 79 **Production never gets demo content.** Demo accounts share a published
65 80 password, so nothing automatic runs `--demo`: not the image, not compose, not
66 81 `AUTO_MIGRATE`. `manage seed --demo` also refuses to run when `PUBLIC_URL` is
67 82 https unless given `--allow-public`. Plain `manage seed` is safe in production
68 −(it only adds missing categories/reactions/tags); run it by hand if you want
69 −the starter categories.
83 +(it only adds missing categories/reactions/tags and, once, the welcome topic);
84 +run it by hand, after creating the first staff account, if you want them.
70 85
71 86 ### Staff
72 87
@@ -540,5 +555,5 @@ With `auto` they get a fresh account the next time they sign in.
540 555 - `manage user strikes <name> [--clear [--by STAFF]]` — lameness strikes and the next ladder step; `--clear` resets them (logged)
541 556 - `manage invite create [--email E] [--days N] | list | show <token>`
542 557 - `manage email test <to>` — send a test message through mail-prism (or report it isn't configured)
543 − - `manage seed [--demo [--allow-public]]` — baseline categories/reactions/tags; `--demo` adds demo users and content
558 + - `manage seed [--demo [--allow-public]]` — baseline categories/reactions/tags and the one-time welcome topic; `--demo` adds demo users and content
544 559 - Justfile shortcuts: `just manage …`, `just admin <name> <email>`, `just invite [days]`, `just staff <name>`, `just trust <name> <level>`, `just seed`, `just seed-demo`
modified migration/src/lib.rs
+2 −0
@@ -24,6 +24,7 @@ mod m20240101_000021_category_reactions;
24 24 mod m20240101_000022_post_holds;
25 25 mod m20240101_000023_search_and_hot_indexes;
26 26 mod m20240101_000024_topic_held;
27 +mod m20240101_000025_seed_markers;
27 28
28 29 pub struct Migrator;
29 30
@@ -59,6 +60,7 @@ impl MigratorTrait for Migrator {
59 60 Box::new(m20240101_000022_post_holds::Migration),
60 61 Box::new(m20240101_000023_search_and_hot_indexes::Migration),
61 62 Box::new(m20240101_000024_topic_held::Migration),
63 + Box::new(m20240101_000025_seed_markers::Migration),
62 64 ]
63 65 }
64 66 }
added migration/src/m20240101_000025_seed_markers.rs
+31 −0
@@ -0,0 +1,31 @@
1 +//! `seed_markers`: one row per one-time seed step that has run (`manage
2 +//! seed`). A step checks its key, not the rows it made, so content staff
3 +//! have since edited, renamed or deleted is never brought back.
4 +use sea_orm_migration::prelude::*;
5 +
6 +#[derive(DeriveMigrationName)]
7 +pub struct Migration;
8 +
9 +const UP: &str = r#"
10 +CREATE TABLE seed_markers (
11 + key TEXT PRIMARY KEY,
12 + created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
13 + -- What the step made, for the curious (e.g. the welcome topic's id).
14 + note TEXT NULL
15 +);
16 +"#;
17 +
18 +const DOWN: &str = r#"
19 +DROP TABLE IF EXISTS seed_markers;
20 +"#;
21 +
22 +#[async_trait::async_trait]
23 +impl MigrationTrait for Migration {
24 + async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
25 + manager.get_connection().execute_unprepared(UP).await.map(|_| ())
26 + }
27 +
28 + async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
29 + manager.get_connection().execute_unprepared(DOWN).await.map(|_| ())
30 + }
31 +}
modified src/bin/manage.rs
+10 −1
@@ -642,7 +642,7 @@ async fn run_seed(db: &DatabaseConnection, config: &Config, demo: bool, allow_pu
642 642 )
643 643 .into());
644 644 }
645 − let base = seed::seed_base(db).await.map_err(|e| format!("{e:#}"))?;
645 + let base = seed::seed_base(db, &config.app_name).await.map_err(|e| format!("{e:#}"))?;
646 646 println!(
647 647 "Baseline: {} categories, {} reaction types, {} tags created{}.",
648 648 base.categories,
@@ -650,8 +650,17 @@ async fn run_seed(db: &DatabaseConnection, config: &Config, demo: bool, allow_pu
650 650 base.tags,
651 651 if base.is_empty() { " (already seeded)" } else { "" }
652 652 );
653 + // A fresh --demo database has no staff yet: the welcome waits for
654 + // demo-admin (below), next to the demo's own welcome.
655 + if let Some(w) = base.welcome.filter(|w| !(demo && *w == seed::Welcome::NoStaff)) {
656 + println!("{}", w.describe());
657 + }
653 658 if demo {
654 659 let d = seed::seed_demo(db).await.map_err(|e| format!("{e:#}"))?;
660 + if base.welcome == Some(seed::Welcome::NoStaff) {
661 + let w = seed::seed_welcome(db, &config.app_name).await.map_err(|e| format!("{e:#}"))?;
662 + println!("{}", w.describe());
663 + }
655 664 println!(
656 665 "Demo: {} users, {} topics, {} posts created{}.",
657 666 d.users,
modified src/lameness.rs
+1 −0
@@ -547,6 +547,7 @@ mod tests {
547 547 ("this file, as a code block", &format!("Here's the filter:\n\n```rust\n{}\n```\n", include_str!("lameness.rs"))),
548 548 ("Cargo.lock in a fence", &format!("```\n{}\n```", include_str!("../Cargo.lock"))),
549 549 ("seed demo posts", &crate::seed::demo_post_bodies().join("\n\n")),
550 + ("the seeded welcome", crate::seed::WELCOME_BODY),
550 551 ] {
551 552 assert_clean(name, text);
552 553 }
modified src/seed.rs
+153 −4
@@ -8,7 +8,11 @@
8 8 //! * `seed` — what a real forum can keep: a category tree three levels deep
9 9 //! with distinct colors, a members-only category (`min_trust_level = 0`: any
10 10 //! signed-in account) and a min-trust one (Regular, 3), the default reaction
11 −//! types, and a few tags.
11 +//! types, a few tags, and a pinned welcome topic in Announcements by the
12 +//! oldest staff account ([`seed_welcome`]). The welcome is made once, ever:
13 +//! a `seed_markers` row records it, so editing, renaming or deleting it
14 +//! never brings it back. With no staff account yet it is skipped until a
15 +//! later run.
12 16 //! * `seed --demo` — fake people and conversations for development: `demo-*`
13 17 //! accounts at every trust tier (verified, password [`DEMO_PASSWORD`]),
14 18 //! topics with replies, an edited post, a soft-deleted post, reactions,
@@ -101,16 +105,160 @@ pub struct Report {
101 105 pub users: usize,
102 106 pub topics: usize,
103 107 pub posts: usize,
108 + /// The welcome topic ([`seed_welcome`]); `None` for `seed_demo`.
109 + pub welcome: Option<Welcome>,
104 110 }
105 111
106 112 impl Report {
113 + /// Nothing new (the welcome aside).
107 114 pub fn is_empty(&self) -> bool {
108 − *self == Report::default()
115 + Report { welcome: None, ..*self } == Report::default()
109 116 }
110 117 }
111 118
112 −/// The baseline: categories, reaction types, tags.
113 −pub async fn seed_base<C: ConnectionTrait>(db: &C) -> Result<Report> {
119 +/// What became of the welcome topic.
120 +#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121 +pub enum Welcome {
122 + Created,
123 + /// Its marker is there: made before (and maybe since edited or deleted).
124 + AlreadySeeded,
125 + /// No staff account to write it.
126 + NoStaff,
127 + /// No `announcements` category.
128 + NoCategory,
129 +}
130 +
131 +impl Welcome {
132 + /// `manage seed`'s line.
133 + pub fn describe(self) -> &'static str {
134 + match self {
135 + Welcome::Created => "Welcome topic: created.",
136 + Welcome::AlreadySeeded => "Welcome topic: already seeded.",
137 + Welcome::NoStaff => {
138 + "Welcome topic skipped: create a staff account first (manage user create … --staff), then re-run manage seed."
139 + }
140 + Welcome::NoCategory => {
141 + "Welcome topic skipped: there is no `announcements` category (renamed or deleted); nothing was created."
142 + }
143 + }
144 + }
145 +}
146 +
147 +/// The `seed_markers` key of the welcome topic.
148 +pub const WELCOME_MARKER: &str = "welcome_topic";
149 +
150 +/// The welcome topic's opening post: a starter for staff to edit.
151 +pub const WELCOME_BODY: &str = r#"**What this place is for:** *Staff: replace this line with a sentence or two about this community, who it's for and what belongs here.*
152 +
153 +## Getting started
154 +
155 +- **Verify your email.** Follow the link we mailed you. Until then you can read but not post; the banner at the top has a "Resend link" button.
156 +- **Trust grows with participation.** Everyone starts as New. Reading, posting and sticking around move you up through Basic, Member, Regular and Leader, and each level unlocks a little more: flagging, creating tags, some categories.
157 +- **Pick a layout.** Profile → Layout switches between Classic (lists) and Focus (tiles with a reader).
158 +- **React, bookmark, watch.** React to a post instead of replying "+1", bookmark posts to find them later, and watch a category to hear about new topics in it.
159 +- **Flag what breaks the rules.** The flag on a post sends it to staff, and enough flags hide it until someone looks.
160 +- **Formatting.** Posts are Markdown: `**bold**`, `*italic*`, links, lists, code blocks and tables. Links to other sites go through an exit page that shows where they lead.
161 +
162 +---
163 +
164 +*Staff: edit this post to make it yours: the purpose, the rules, who to ask. Renaming or deleting it is fine; `manage seed` won't put it back.*
165 +"#;
166 +
167 +/// The pinned welcome topic in Announcements, by the oldest staff account,
168 +/// once ever (see [`WELCOME_MARKER`]). Inserted like a normal topic (one
169 +/// post, its first revision, bumped now, no views) but quietly: nobody is
170 +/// notified, since it's the forum's own furniture.
171 +pub async fn seed_welcome<C: ConnectionTrait + TransactionTrait>(db: &C, app_name: &str) -> Result<Welcome> {
172 + #[derive(FromQueryResult)]
173 + struct Marker {
174 + #[allow(dead_code)]
175 + key: String,
176 + }
177 + let marker = Marker::find_by_statement(Statement::from_sql_and_values(
178 + DbBackend::Postgres,
179 + "SELECT key FROM seed_markers WHERE key = $1",
180 + [WELCOME_MARKER.into()],
181 + ))
182 + .one(db)
183 + .await?;
184 + if marker.is_some() {
185 + return Ok(Welcome::AlreadySeeded);
186 + }
187 + let Some(category) = categories::Entity::find().filter(categories::Column::Slug.eq("announcements")).one(db).await?
188 + else {
189 + return Ok(Welcome::NoCategory);
190 + };
191 + let Some(author) = users::Entity::find()
192 + .filter(users::Column::IsStaff.eq(true))
193 + .filter(users::Column::IsActive.eq(true))
194 + .order_by_asc(users::Column::CreatedAt)
195 + .order_by_asc(users::Column::Id)
196 + .one(db)
197 + .await?
198 + else {
199 + return Ok(Welcome::NoStaff);
200 + };
201 +
202 + let txn = db.begin().await?;
203 + // The marker first: a concurrent run fails on its primary key instead
204 + // of making a second topic.
205 + let now: DateTime<FixedOffset> = Utc::now().into();
206 + let topic_id = Uuid::now_v7();
207 + txn.execute(Statement::from_sql_and_values(
208 + DbBackend::Postgres,
209 + "INSERT INTO seed_markers (key, note) VALUES ($1, $2)",
210 + [WELCOME_MARKER.into(), format!("topic {topic_id}").into()],
211 + ))
212 + .await?;
213 + topics::ActiveModel {
214 + id: Set(topic_id),
215 + category_id: Set(category.id),
216 + user_id: Set(author.id),
217 + title: Set(format!("Welcome to {app_name}")),
218 + is_pinned: Set(true),
219 + is_closed: Set(false),
220 + views: Set(0),
221 + posts_count: Set(1),
222 + created_at: Set(now),
223 + updated_at: Set(now),
224 + bumped_at: Set(now),
225 + deleted_at: Set(None),
226 + deleted_by_id: Set(None),
227 + closed_at: Set(None),
228 + closed_by_id: Set(None),
229 + closed_reason: Set(None),
230 + held_at: Set(None),
231 + }
232 + .insert(&txn)
233 + .await?;
234 + let cooked = markdown::render(WELCOME_BODY);
235 + let post = posts::ActiveModel {
236 + id: Set(Uuid::now_v7()),
237 + topic_id: Set(topic_id),
238 + user_id: Set(author.id),
239 + post_number: Set(1),
240 + raw: Set(WELCOME_BODY.into()),
241 + cooked: Set(cooked.clone()),
242 + created_at: Set(now),
243 + updated_at: Set(now),
244 + edited_at: Set(None),
245 + edit_count: Set(0),
246 + last_editor_id: Set(None),
247 + deleted_at: Set(None),
248 + deleted_by_id: Set(None),
249 + moderated_at: Set(None),
250 + moderated_by_id: Set(None),
251 + hidden_at: Set(None),
252 + }
253 + .insert(&txn)
254 + .await?;
255 + revision(&txn, post.id, 1, author.id, WELCOME_BODY, &cooked, now, "edit").await?;
256 + txn.commit().await?;
257 + Ok(Welcome::Created)
258 +}
259 +
260 +/// The baseline: categories, reaction types, tags, and the welcome topic.
261 +pub async fn seed_base<C: ConnectionTrait + TransactionTrait>(db: &C, app_name: &str) -> Result<Report> {
114 262 let mut report = Report::default();
115 263 let now: DateTime<FixedOffset> = Utc::now().into();
116 264
@@ -182,6 +330,7 @@ pub async fn seed_base<C: ConnectionTrait>(db: &C) -> Result<Report> {
182 330 report.tags += 1;
183 331 }
184 332 }
333 + report.welcome = Some(seed_welcome(db, app_name).await.context("welcome topic")?);
185 334 Ok(report)
186 335 }
187 336
added tests/seed_db.rs
+128 −0
@@ -0,0 +1,128 @@
1 +//! `manage seed`'s welcome topic, each case on a fresh database of its own
2 +//! (created next to `TEST_DATABASE_URL`'s and dropped after).
3 +use migration::MigratorTrait;
4 +use recourse::auth;
5 +use recourse::entities::{categories, posts, topics, users};
6 +use recourse::seed::{self, Welcome};
7 +use sea_orm::*;
8 +use uuid::Uuid;
9 +
10 +/// A fresh, migrated database, and a way to drop it.
11 +struct Fresh {
12 + db: DatabaseConnection,
13 + admin: DatabaseConnection,
14 + name: String,
15 +}
16 +
17 +impl Fresh {
18 + async fn new() -> Option<Fresh> {
19 + let url = std::env::var("TEST_DATABASE_URL").ok()?;
20 + let admin = Database::connect(&url).await.expect("connect to TEST_DATABASE_URL");
21 + let name = format!("seed_{}", Uuid::now_v7().simple());
22 + admin.execute_unprepared(&format!("CREATE DATABASE {name}")).await.unwrap();
23 + let base = &url[..url.rfind('/').unwrap()];
24 + let db = Database::connect(format!("{base}/{name}")).await.unwrap();
25 + migration::Migrator::up(&db, None).await.unwrap();
26 + Some(Fresh { db, admin, name })
27 + }
28 +
29 + async fn drop(self) {
30 + self.db.close().await.ok();
31 + self.admin.execute_unprepared(&format!("DROP DATABASE IF EXISTS {} WITH (FORCE)", self.name)).await.ok();
32 + }
33 +
34 + async fn staff(&self, name: &str) -> users::Model {
35 + auth::create_user_direct(&self.db, name, &format!("{name}@example.test"), "pw-for-tests-123", true).await.unwrap()
36 + }
37 +
38 + async fn welcomes(&self) -> Vec<topics::Model> {
39 + let ann = categories::Entity::find().filter(categories::Column::Slug.eq("announcements")).one(&self.db).await.unwrap();
40 + match ann {
41 + Some(a) => topics::Entity::find().filter(topics::Column::CategoryId.eq(a.id)).all(&self.db).await.unwrap(),
42 + None => vec![],
43 + }
44 + }
45 +}
46 +
47 +#[tokio::test]
48 +async fn the_welcome_topic_is_seeded_once_by_the_oldest_staff() {
49 + let Some(f) = Fresh::new().await else { return };
50 +
51 + // No staff yet: skipped, everything else seeded.
52 + let r = seed::seed_base(&f.db, "Tower").await.unwrap();
53 + assert_eq!(r.welcome, Some(Welcome::NoStaff));
54 + assert!(Welcome::NoStaff.describe().contains("manage user create"));
55 + assert!(r.categories > 0);
56 + assert!(f.welcomes().await.is_empty());
57 +
58 + // A plain member doesn't count; the oldest staff writes it.
59 + auth::create_user_direct(&f.db, "member", "member@example.test", "pw-for-tests-123", false).await.unwrap();
60 + let first = f.staff("first").await;
61 + f.staff("second").await;
62 + let r = seed::seed_base(&f.db, "Tower").await.unwrap();
63 + assert_eq!(r.welcome, Some(Welcome::Created));
64 + assert!(r.is_empty(), "nothing else new: {r:?}");
65 + let w = f.welcomes().await;
66 + assert_eq!(w.len(), 1);
67 + let t = &w[0];
68 + assert_eq!(t.title, "Welcome to Tower");
69 + assert!(t.is_pinned && !t.is_closed && t.held_at.is_none() && t.deleted_at.is_none());
70 + assert_eq!((t.user_id, t.views, t.posts_count), (first.id, 0, 1));
71 + assert!(t.bumped_at > chrono::Utc::now() - chrono::Duration::minutes(5));
72 + let op = posts::Entity::find().filter(posts::Column::TopicId.eq(t.id)).all(&f.db).await.unwrap();
73 + assert_eq!(op.len(), 1);
74 + assert_eq!((op[0].post_number, op[0].user_id), (1, first.id));
75 + assert!(op[0].raw.contains("Staff: edit this post") && op[0].cooked.contains("<h2>"));
76 + let notified: i64 = f
77 + .db
78 + .query_one(Statement::from_string(DbBackend::Postgres, "SELECT count(*) AS n FROM notifications"))
79 + .await
80 + .unwrap()
81 + .unwrap()
82 + .try_get("", "n")
83 + .unwrap();
84 + assert_eq!(notified, 0, "nobody is notified of the seed");
85 +
86 + // Again: no duplicate.
87 + let r = seed::seed_base(&f.db, "Tower").await.unwrap();
88 + assert_eq!(r.welcome, Some(Welcome::AlreadySeeded));
89 + assert_eq!(f.welcomes().await.len(), 1);
90 +
91 + // Edited (title, body) or renamed site: still not recreated.
92 + let mut am: topics::ActiveModel = t.clone().into();
93 + am.title = Set("Read me first".into());
94 + am.update(&f.db).await.unwrap();
95 + let mut am: posts::ActiveModel = op[0].clone().into();
96 + am.raw = Set("Our rules: be kind.".into());
97 + am.update(&f.db).await.unwrap();
98 + assert_eq!(seed::seed_base(&f.db, "Tower Forever").await.unwrap().welcome, Some(Welcome::AlreadySeeded));
99 + assert_eq!(f.welcomes().await.len(), 1);
100 +
101 + // Deleted outright: still not recreated.
102 + posts::Entity::delete_many().filter(posts::Column::TopicId.eq(t.id)).exec(&f.db).await.unwrap();
103 + topics::Entity::delete_by_id(t.id).exec(&f.db).await.unwrap();
104 + assert_eq!(seed::seed_base(&f.db, "Tower").await.unwrap().welcome, Some(Welcome::AlreadySeeded));
105 + assert!(f.welcomes().await.is_empty());
106 + f.drop().await;
107 +}
108 +
109 +#[tokio::test]
110 +async fn no_announcements_category_no_welcome() {
111 + let Some(f) = Fresh::new().await else { return };
112 + f.staff("boss").await;
113 + // Renamed: the slug is what's looked up.
114 + let ann = categories::Entity::find().filter(categories::Column::Slug.eq("announcements")).one(&f.db).await.unwrap().unwrap();
115 + let mut am: categories::ActiveModel = ann.into();
116 + am.slug = Set("news".into());
117 + let news = am.update(&f.db).await.unwrap();
118 + // seed_base would recreate `announcements`; the welcome step alone sees
119 + // the state an operator left.
120 + assert_eq!(seed::seed_welcome(&f.db, "Tower").await.unwrap(), Welcome::NoCategory);
121 + assert!(Welcome::NoCategory.describe().contains("skipped"));
122 + let n = topics::Entity::find().filter(topics::Column::CategoryId.eq(news.id)).count(&f.db).await.unwrap();
123 + assert_eq!(n, 0);
124 + // Not marked: once the category is back, it's made.
125 + let r = seed::seed_base(&f.db, "Tower").await.unwrap();
126 + assert_eq!(r.welcome, Some(Welcome::Created));
127 + f.drop().await;
128 +}

Parents: dba9c4f