diff --git a/app/src/console/demo.rs b/app/src/console/demo.rs index b48f5f37..01698d44 100644 --- a/app/src/console/demo.rs +++ b/app/src/console/demo.rs @@ -26,3 +26,19 @@ impl DemoReset { Ok(()) } } + +/// `screenshots:seed`: fill an empty database with the fixed dataset VisualCI's own screenshots are taken against +/// (`scripts/screenshots`, the CI's visual job). Run after `migrate:fresh`; sign in as `ada@example.com`. +#[derive(clap::Parser)] +#[command(name = "screenshots:seed")] +pub struct ScreenshotsSeed; + +#[command] +impl ScreenshotsSeed { + async fn handle(self, console: &mut Console) -> laravel::Result<()> { + let store = BlobStore::current().await?; + Box::pin(demo::screenshots_seed(&store, &crate::http::api::builds::renderer_version())).await?; + console.line(format!("seeded; sign in as {}", demo::SCREENSHOTS_EMAIL)); + Ok(()) + } +} diff --git a/app/src/domain/demo.rs b/app/src/domain/demo.rs index c7c744ba..dcd7078f 100644 --- a/app/src/domain/demo.rs +++ b/app/src/domain/demo.rs @@ -89,6 +89,181 @@ pub async fn reset(store: &BlobStore, renderer_version: &str) -> laravel::Result Ok(usize::try_from(builds).unwrap_or_default()) } +/// The signed-in user in VisualCI's own screenshots (`scripts/screenshots`). +pub const SCREENSHOTS_EMAIL: &str = "ada@example.com"; + +/// Fill an empty database with the fixed dataset VisualCI's own screenshots are taken against (`scripts/screenshots`, +/// the CI's visual job): two organizations (Team and Free), three projects, builds covering every kind of change +/// (the demo's web builds, invoices with a missing PDF, a blog), tokens and credit usage. Afterwards every id the +/// pages show (UUIDs, token prefixes) and every timestamp is fixed, so the same code gives the same pixels each run. +/// +/// # Errors +/// When the database isn't empty, or on a database or storage error. +pub async fn screenshots_seed(store: &BlobStore, renderer_version: &str) -> laravel::Result<()> { + if Organization::query().exists().await? { + return Err(laravel::Error::msg("screenshots:seed needs an empty database (migrate:fresh first)")); + } + let ada = seed_user("Ada Lovelace", SCREENSHOTS_EMAIL, "ada").await?; + let grace = seed_user("Grace Hopper", "grace@example.com", "grace").await?; + + // Acme: the Team plan, two projects, a teammate who follows GitHub. + let acme = seed_org("acme", "Acme", ada.id).await?; + let (acme_id, grace_id) = (acme.id, grace.id); + db::query!( + "INSERT INTO memberships (organization_id, user_id, role, source, synced_at, created_at, updated_at) \ + VALUES ({acme_id}, {grace_id}, 'member', 'github', now(), now(), now())" + ) + .insert() + .await?; + db::query!( + "UPDATE organizations SET plan = 'team', stripe_customer_id = 'cus_seed', stripe_subscription_id = 'sub_seed', \ + credits_balance = 50000 WHERE id = {acme_id}" + ) + .update() + .await?; + let web = seed_project(&acme, "web", "Web app").await?; + let web_id = web.id; + db::query!( + "UPDATE projects SET forge = 'github', repository_url = 'https://github.com/acme/web', forge_installation = '1' \ + WHERE id = {web_id}" + ) + .update() + .await?; + let web = Project::find_or_fail(web_id).await?; + let invoices = seed_project(&acme, "invoices", "Invoices").await?; + seed_token("project_tokens", web.id, "GitHub Actions", "vci").await?; + seed_token("project_tokens", invoices.id, "CircleCI", "vci").await?; + seed_token("user_tokens", ada.id, "Claude Code", "vcu").await?; + + // Side project: the Free plan, one project. + let side = seed_org("side-project", "Side project", ada.id).await?; + let blog = seed_project(&side, "blog", "Blog").await?; + + let seeder = Seeder { store, renderer_version }; + Box::pin(seeder.web_builds(&web, ada.id)).await?; + let c1 = "e5f60718293a4b5c6d7e8f9012345678901a2b3c"; + Box::pin(seeder.build( + &invoices, + c1, + "main", + None, + &[], + vec![Item::Pdf { name: "invoice_typical.pdf", pages: receipt(false) }], + )) + .await?; + Box::pin(seeder.build( + &invoices, + "f60718293a4b5c6d7e8f9012345678901a2b3c4d", + "main", + None, + &[c1], + vec![ + Item::Pdf { name: "invoice_typical.pdf", pages: receipt(false) }, + Item::MissingPdf { name: "invoice_long.pdf" }, + ], + )) + .await?; + Box::pin(seeder.build( + &blog, + "1111111111111111111111111111111111111111", + "main", + None, + &[], + vec![ + Item::Image { name: "home", png: screen(640, 400, Screen::default()) }, + Item::Text { name: "feed.xml", content_type: "text/plain", text: feed(3) }, + ], + )) + .await?; + fix_ids_and_times().await +} + +async fn seed_user(name: &str, email: &str, login: &str) -> laravel::Result { + let user = create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await?; + let (id, forge_user_id) = (user.id, format!("{}", 1000 + user.id)); + db::query!( + "INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \ + VALUES ({id}, 'github', 'github.com', {forge_user_id}, {login}, now(), now())" + ) + .insert() + .await?; + db::query!("UPDATE users SET signup_notified_at = now() WHERE id = {id}").update().await?; + Ok(user) +} + +async fn seed_org(slug: &str, name: &str, admin: i64) -> laravel::Result { + let org = create!(Organization { pid: laravel::str::uuid7(), slug: slug, name: name }).await?; + create!(Membership { organization_id: org.id, user_id: admin, role: "admin", source: "created" }).await?; + Ok(org) +} + +async fn seed_project(org: &Organization, slug: &str, name: &str) -> laravel::Result { + create!(Project { pid: laravel::str::uuid7(), organization_id: org.id, slug: slug, name: name }).await +} + +/// A token (its plaintext is never needed: the screenshots show only its prefix, fixed afterwards). +async fn seed_token(table: &str, owner: i64, name: &str, prefix: &str) -> laravel::Result<()> { + let token = format!("{prefix}_{}", laravel::str::uuid7().simple()); + let hash = crate::models::token_hash(&token); + if table == "user_tokens" { + db::query!( + "INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({owner}, {name}, {hash}, {prefix}, now(), now())" + ) + .insert() + .await?; + } else { + db::query!( + "INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \ + VALUES ({owner}, {name}, {hash}, {prefix}, now(), now())" + ) + .insert() + .await?; + } + Ok(()) +} + +/// Every UUID, token prefix and timestamp the pages show, set from the row's id (ids are fixed in a fresh database). +async fn fix_ids_and_times() -> laravel::Result<()> { + db::query!( + "UPDATE users SET pid = md5('users:' || id)::uuid; + UPDATE organizations SET pid = md5('organizations:' || id)::uuid; + UPDATE projects SET pid = md5('projects:' || id)::uuid; + UPDATE builds SET pid = md5('builds:' || id)::uuid; + UPDATE snapshots SET pid = md5('snapshots:' || id)::uuid; + UPDATE users SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00'; + UPDATE organizations SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00'; + UPDATE projects SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00'; + UPDATE memberships SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00'; + UPDATE blobs SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00'; + UPDATE renders SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00'; + UPDATE diffs SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00'; + UPDATE blobs SET uploaded_at = created_at; + UPDATE builds SET created_at = timestamptz '2026-11-20 09:00:00+00' + (id - 1) * interval '1 hour', \ + finalized_at = timestamptz '2026-11-20 09:00:00+00' + (id - 1) * interval '1 hour' + interval '2 minutes', \ + completed_at = timestamptz '2026-11-20 09:00:00+00' + (id - 1) * interval '1 hour' + interval '3 minutes', \ + updated_at = timestamptz '2026-11-20 09:00:00+00' + (id - 1) * interval '1 hour' + interval '3 minutes'; + UPDATE snapshots s SET created_at = b.created_at, updated_at = b.completed_at FROM builds b WHERE b.id = s.build_id; + UPDATE snapshot_pages p SET created_at = s.created_at, updated_at = s.updated_at FROM snapshots s \ + WHERE s.id = p.snapshot_id; + UPDATE reviews r SET created_at = b.completed_at + interval '20 minutes', \ + updated_at = b.completed_at + interval '20 minutes' FROM builds b WHERE b.id = r.build_id; + UPDATE credit_transactions SET created_at = timestamptz '2026-11-15 09:00:00+00' + id * interval '1 minute', \ + updated_at = timestamptz '2026-11-15 09:00:00+00' + id * interval '1 minute'; + UPDATE credit_transactions c SET created_at = b.completed_at, updated_at = b.completed_at \ + FROM builds b WHERE c.kind = 'build' AND c.build_id = b.id; + UPDATE project_tokens SET token_prefix = 'vci_' || substr(md5('project_tokens:' || id), 1, 6), \ + created_at = timestamptz '2026-10-31 09:00:00+00', updated_at = timestamptz '2026-10-31 09:00:00+00', \ + last_used_at = timestamptz '2026-11-20 13:00:00+00'; + UPDATE user_tokens SET token_prefix = 'vcu_' || substr(md5('user_tokens:' || id), 1, 6), \ + created_at = timestamptz '2026-10-31 09:00:00+00', updated_at = timestamptz '2026-10-31 09:00:00+00', \ + last_used_at = timestamptz '2026-11-20 13:00:00+00';" + ) + .unprepared() + .await?; + Ok(()) +} + struct Seeder<'a> { store: &'a BlobStore, renderer_version: &'a str, @@ -96,9 +271,23 @@ struct Seeder<'a> { /// One snapshot to send in a build. enum Item { - Image { name: &'static str, png: Vec }, - Text { name: &'static str, content_type: &'static str, text: String }, - Pdf { name: &'static str, pages: Vec }, + Image { + name: &'static str, + png: Vec, + }, + Text { + name: &'static str, + content_type: &'static str, + text: String, + }, + Pdf { + name: &'static str, + pages: Vec, + }, + /// A PDF registered but never uploaded: the build's snapshot fails with "the file was never uploaded". + MissingPdf { + name: &'static str, + }, } #[derive(Clone)] @@ -264,6 +453,10 @@ impl Seeder<'_> { let blob = super::blobs::put(self.store, text.into_bytes(), content_type).await?; params(name, "text", fingerprint, blob.sha256, size, content_type) } + Item::MissingPdf { name } => { + let sha = visualci_core::sha256_hex(name.as_bytes()); + params(name, "document", sha.clone(), sha, 2048, "application/pdf") + } Item::Pdf { name, pages } => { // The "PDF" is the pages' description; its render is recorded as done with the drawn pages. let mut rendered = Vec::new(); @@ -417,3 +610,12 @@ fn help_text(changed: bool) -> String { text.push_str(" logs Show recent logs\n"); text } + +fn feed(items: usize) -> String { + let mut text = String::from("\n\n"); + for i in 1..=items { + text.push_str(&format!(" Post {i}\n")); + } + text.push_str("\n\n"); + text +} diff --git a/app/src/lib.rs b/app/src/lib.rs index d175eb15..043bd950 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -87,5 +87,6 @@ pub fn configure() -> ApplicationBuilder { commands.add::(); commands.add::(); commands.add::(); + commands.add::(); }) } diff --git a/app/tests/screenshots_seed.rs b/app/tests/screenshots_seed.rs new file mode 100644 index 00000000..e239b635 --- /dev/null +++ b/app/tests/screenshots_seed.rs @@ -0,0 +1,47 @@ +//! `screenshots:seed` (the CI visual job's dataset): two organizations on the two plans, three projects, builds that +//! cover every kind of change, and ids and timestamps fixed so every run gives the same pixels. + +use app::models::{Build, Organization, Snapshot}; +use app::testing::fixtures; +use laravel::db; +use laravel::testing::prelude::*; + +#[laravel::test] +async fn the_screenshots_dataset_is_seeded_the_same_every_time(_app: Application) -> laravel::Result<()> { + Box::pin(seeded()).await +} + +async fn seeded() -> laravel::Result<()> { + let store = fixtures::blob_store().await?; + app::domain::demo::screenshots_seed(&store, "1").await?; + + let plans: Vec<(String, String)> = Organization::query() + .order_by(Organization::id.asc()) + .get() + .await? + .into_iter() + .map(|o| (o.slug, o.plan)) + .collect(); + assert_eq!(plans, [("acme".to_string(), "team".to_string()), ("side-project".to_string(), "free".to_string())]); + let builds = Build::query().order_by(Build::id.asc()).get().await?; + assert!(builds.len() >= 7, "{} builds", builds.len()); + assert!(builds.iter().all(|b| b.state == "completed"), "every build concluded"); + // The invoices' second build has a PDF that was never uploaded. + let failed = + Snapshot::query().filter(Snapshot::name.eq("invoice_long.pdf")).first().await?.expect("the missing pdf"); + assert_eq!(failed.state, "failed"); + // Fixed ids and prefixes. + // Ids don't restart in a reused test database (sequences survive the rollback), so each pid is checked against + // its own row's id. + let mismatched: i64 = + db::query!("SELECT COUNT(*) FROM organizations WHERE pid <> md5('organizations:' || id)::uuid") + .scalar() + .await? + .unwrap_or(1); + assert_eq!(mismatched, 0, "every organization's pid comes from its id"); + let prefix: String = db::query!("SELECT token_prefix FROM user_tokens LIMIT 1").scalar().await?.unwrap(); + assert!(prefix.starts_with("vcu_") && prefix.len() == 10, "{prefix}"); + // A second run refuses: it needs an empty database. + assert!(app::domain::demo::screenshots_seed(&store, "1").await.is_err()); + Ok(()) +}