Skip to content

Commit 555ff9a

Browse files
authored
app/: screenshots:seed, the visual job's dataset (sc-8900 cutover) (#100)
* app/: screenshots:seed, the CI visual job's dataset on app/ (sc-8900 cutover): two organizations on the two plans, three projects, the demo's web builds, invoices with a missing PDF and a blog, tokens and credit usage, with every id and timestamp fixed so each run gives the same pixels; for the visual parity run against app/ * app/: the screenshots seed test checks each pid against its own id (ids don't restart in a reused test database) * app/: cargo fmt
1 parent 4e31e8a commit 555ff9a

4 files changed

Lines changed: 269 additions & 3 deletions

File tree

‎app/src/console/demo.rs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,19 @@ impl DemoReset {
2626
Ok(())
2727
}
2828
}
29+
30+
/// `screenshots:seed`: fill an empty database with the fixed dataset VisualCI's own screenshots are taken against
31+
/// (`scripts/screenshots`, the CI's visual job). Run after `migrate:fresh`; sign in as `ada@example.com`.
32+
#[derive(clap::Parser)]
33+
#[command(name = "screenshots:seed")]
34+
pub struct ScreenshotsSeed;
35+
36+
#[command]
37+
impl ScreenshotsSeed {
38+
async fn handle(self, console: &mut Console) -> laravel::Result<()> {
39+
let store = BlobStore::current().await?;
40+
Box::pin(demo::screenshots_seed(&store, &crate::http::api::builds::renderer_version())).await?;
41+
console.line(format!("seeded; sign in as {}", demo::SCREENSHOTS_EMAIL));
42+
Ok(())
43+
}
44+
}

‎app/src/domain/demo.rs‎

Lines changed: 205 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,16 +89,205 @@ pub async fn reset(store: &BlobStore, renderer_version: &str) -> laravel::Result
8989
Ok(usize::try_from(builds).unwrap_or_default())
9090
}
9191

92+
/// The signed-in user in VisualCI's own screenshots (`scripts/screenshots`).
93+
pub const SCREENSHOTS_EMAIL: &str = "ada@example.com";
94+
95+
/// Fill an empty database with the fixed dataset VisualCI's own screenshots are taken against (`scripts/screenshots`,
96+
/// the CI's visual job): two organizations (Team and Free), three projects, builds covering every kind of change
97+
/// (the demo's web builds, invoices with a missing PDF, a blog), tokens and credit usage. Afterwards every id the
98+
/// pages show (UUIDs, token prefixes) and every timestamp is fixed, so the same code gives the same pixels each run.
99+
///
100+
/// # Errors
101+
/// When the database isn't empty, or on a database or storage error.
102+
pub async fn screenshots_seed(store: &BlobStore, renderer_version: &str) -> laravel::Result<()> {
103+
if Organization::query().exists().await? {
104+
return Err(laravel::Error::msg("screenshots:seed needs an empty database (migrate:fresh first)"));
105+
}
106+
let ada = seed_user("Ada Lovelace", SCREENSHOTS_EMAIL, "ada").await?;
107+
let grace = seed_user("Grace Hopper", "grace@example.com", "grace").await?;
108+
109+
// Acme: the Team plan, two projects, a teammate who follows GitHub.
110+
let acme = seed_org("acme", "Acme", ada.id).await?;
111+
let (acme_id, grace_id) = (acme.id, grace.id);
112+
db::query!(
113+
"INSERT INTO memberships (organization_id, user_id, role, source, synced_at, created_at, updated_at) \
114+
VALUES ({acme_id}, {grace_id}, 'member', 'github', now(), now(), now())"
115+
)
116+
.insert()
117+
.await?;
118+
db::query!(
119+
"UPDATE organizations SET plan = 'team', stripe_customer_id = 'cus_seed', stripe_subscription_id = 'sub_seed', \
120+
credits_balance = 50000 WHERE id = {acme_id}"
121+
)
122+
.update()
123+
.await?;
124+
let web = seed_project(&acme, "web", "Web app").await?;
125+
let web_id = web.id;
126+
db::query!(
127+
"UPDATE projects SET forge = 'github', repository_url = 'https://github.com/acme/web', forge_installation = '1' \
128+
WHERE id = {web_id}"
129+
)
130+
.update()
131+
.await?;
132+
let web = Project::find_or_fail(web_id).await?;
133+
let invoices = seed_project(&acme, "invoices", "Invoices").await?;
134+
seed_token("project_tokens", web.id, "GitHub Actions", "vci").await?;
135+
seed_token("project_tokens", invoices.id, "CircleCI", "vci").await?;
136+
seed_token("user_tokens", ada.id, "Claude Code", "vcu").await?;
137+
138+
// Side project: the Free plan, one project.
139+
let side = seed_org("side-project", "Side project", ada.id).await?;
140+
let blog = seed_project(&side, "blog", "Blog").await?;
141+
142+
let seeder = Seeder { store, renderer_version };
143+
Box::pin(seeder.web_builds(&web, ada.id)).await?;
144+
let c1 = "e5f60718293a4b5c6d7e8f9012345678901a2b3c";
145+
Box::pin(seeder.build(
146+
&invoices,
147+
c1,
148+
"main",
149+
None,
150+
&[],
151+
vec![Item::Pdf { name: "invoice_typical.pdf", pages: receipt(false) }],
152+
))
153+
.await?;
154+
Box::pin(seeder.build(
155+
&invoices,
156+
"f60718293a4b5c6d7e8f9012345678901a2b3c4d",
157+
"main",
158+
None,
159+
&[c1],
160+
vec![
161+
Item::Pdf { name: "invoice_typical.pdf", pages: receipt(false) },
162+
Item::MissingPdf { name: "invoice_long.pdf" },
163+
],
164+
))
165+
.await?;
166+
Box::pin(seeder.build(
167+
&blog,
168+
"1111111111111111111111111111111111111111",
169+
"main",
170+
None,
171+
&[],
172+
vec![
173+
Item::Image { name: "home", png: screen(640, 400, Screen::default()) },
174+
Item::Text { name: "feed.xml", content_type: "text/plain", text: feed(3) },
175+
],
176+
))
177+
.await?;
178+
fix_ids_and_times().await
179+
}
180+
181+
async fn seed_user(name: &str, email: &str, login: &str) -> laravel::Result<User> {
182+
let user = create!(User { pid: laravel::str::uuid7(), name: name, email: email, staff: false }).await?;
183+
let (id, forge_user_id) = (user.id, format!("{}", 1000 + user.id));
184+
db::query!(
185+
"INSERT INTO identities (user_id, forge, site, forge_user_id, login, created_at, updated_at) \
186+
VALUES ({id}, 'github', 'github.com', {forge_user_id}, {login}, now(), now())"
187+
)
188+
.insert()
189+
.await?;
190+
db::query!("UPDATE users SET signup_notified_at = now() WHERE id = {id}").update().await?;
191+
Ok(user)
192+
}
193+
194+
async fn seed_org(slug: &str, name: &str, admin: i64) -> laravel::Result<Organization> {
195+
let org = create!(Organization { pid: laravel::str::uuid7(), slug: slug, name: name }).await?;
196+
create!(Membership { organization_id: org.id, user_id: admin, role: "admin", source: "created" }).await?;
197+
Ok(org)
198+
}
199+
200+
async fn seed_project(org: &Organization, slug: &str, name: &str) -> laravel::Result<Project> {
201+
create!(Project { pid: laravel::str::uuid7(), organization_id: org.id, slug: slug, name: name }).await
202+
}
203+
204+
/// A token (its plaintext is never needed: the screenshots show only its prefix, fixed afterwards).
205+
async fn seed_token(table: &str, owner: i64, name: &str, prefix: &str) -> laravel::Result<()> {
206+
let token = format!("{prefix}_{}", laravel::str::uuid7().simple());
207+
let hash = crate::models::token_hash(&token);
208+
if table == "user_tokens" {
209+
db::query!(
210+
"INSERT INTO user_tokens (user_id, name, token_hash, token_prefix, created_at, updated_at) \
211+
VALUES ({owner}, {name}, {hash}, {prefix}, now(), now())"
212+
)
213+
.insert()
214+
.await?;
215+
} else {
216+
db::query!(
217+
"INSERT INTO project_tokens (project_id, name, token_hash, token_prefix, created_at, updated_at) \
218+
VALUES ({owner}, {name}, {hash}, {prefix}, now(), now())"
219+
)
220+
.insert()
221+
.await?;
222+
}
223+
Ok(())
224+
}
225+
226+
/// Every UUID, token prefix and timestamp the pages show, set from the row's id (ids are fixed in a fresh database).
227+
async fn fix_ids_and_times() -> laravel::Result<()> {
228+
db::query!(
229+
"UPDATE users SET pid = md5('users:' || id)::uuid;
230+
UPDATE organizations SET pid = md5('organizations:' || id)::uuid;
231+
UPDATE projects SET pid = md5('projects:' || id)::uuid;
232+
UPDATE builds SET pid = md5('builds:' || id)::uuid;
233+
UPDATE snapshots SET pid = md5('snapshots:' || id)::uuid;
234+
UPDATE users SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00';
235+
UPDATE organizations SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00';
236+
UPDATE projects SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00';
237+
UPDATE memberships SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00';
238+
UPDATE blobs SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00';
239+
UPDATE renders SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00';
240+
UPDATE diffs SET created_at = timestamptz '2026-10-21 09:00:00+00', updated_at = timestamptz '2026-10-21 09:00:00+00';
241+
UPDATE blobs SET uploaded_at = created_at;
242+
UPDATE builds SET created_at = timestamptz '2026-11-20 09:00:00+00' + (id - 1) * interval '1 hour', \
243+
finalized_at = timestamptz '2026-11-20 09:00:00+00' + (id - 1) * interval '1 hour' + interval '2 minutes', \
244+
completed_at = timestamptz '2026-11-20 09:00:00+00' + (id - 1) * interval '1 hour' + interval '3 minutes', \
245+
updated_at = timestamptz '2026-11-20 09:00:00+00' + (id - 1) * interval '1 hour' + interval '3 minutes';
246+
UPDATE snapshots s SET created_at = b.created_at, updated_at = b.completed_at FROM builds b WHERE b.id = s.build_id;
247+
UPDATE snapshot_pages p SET created_at = s.created_at, updated_at = s.updated_at FROM snapshots s \
248+
WHERE s.id = p.snapshot_id;
249+
UPDATE reviews r SET created_at = b.completed_at + interval '20 minutes', \
250+
updated_at = b.completed_at + interval '20 minutes' FROM builds b WHERE b.id = r.build_id;
251+
UPDATE credit_transactions SET created_at = timestamptz '2026-11-15 09:00:00+00' + id * interval '1 minute', \
252+
updated_at = timestamptz '2026-11-15 09:00:00+00' + id * interval '1 minute';
253+
UPDATE credit_transactions c SET created_at = b.completed_at, updated_at = b.completed_at \
254+
FROM builds b WHERE c.kind = 'build' AND c.build_id = b.id;
255+
UPDATE project_tokens SET token_prefix = 'vci_' || substr(md5('project_tokens:' || id), 1, 6), \
256+
created_at = timestamptz '2026-10-31 09:00:00+00', updated_at = timestamptz '2026-10-31 09:00:00+00', \
257+
last_used_at = timestamptz '2026-11-20 13:00:00+00';
258+
UPDATE user_tokens SET token_prefix = 'vcu_' || substr(md5('user_tokens:' || id), 1, 6), \
259+
created_at = timestamptz '2026-10-31 09:00:00+00', updated_at = timestamptz '2026-10-31 09:00:00+00', \
260+
last_used_at = timestamptz '2026-11-20 13:00:00+00';"
261+
)
262+
.unprepared()
263+
.await?;
264+
Ok(())
265+
}
266+
92267
struct Seeder<'a> {
93268
store: &'a BlobStore,
94269
renderer_version: &'a str,
95270
}
96271

97272
/// One snapshot to send in a build.
98273
enum Item {
99-
Image { name: &'static str, png: Vec<u8> },
100-
Text { name: &'static str, content_type: &'static str, text: String },
101-
Pdf { name: &'static str, pages: Vec<PdfPage> },
274+
Image {
275+
name: &'static str,
276+
png: Vec<u8>,
277+
},
278+
Text {
279+
name: &'static str,
280+
content_type: &'static str,
281+
text: String,
282+
},
283+
Pdf {
284+
name: &'static str,
285+
pages: Vec<PdfPage>,
286+
},
287+
/// A PDF registered but never uploaded: the build's snapshot fails with "the file was never uploaded".
288+
MissingPdf {
289+
name: &'static str,
290+
},
102291
}
103292

104293
#[derive(Clone)]
@@ -264,6 +453,10 @@ impl Seeder<'_> {
264453
let blob = super::blobs::put(self.store, text.into_bytes(), content_type).await?;
265454
params(name, "text", fingerprint, blob.sha256, size, content_type)
266455
}
456+
Item::MissingPdf { name } => {
457+
let sha = visualci_core::sha256_hex(name.as_bytes());
458+
params(name, "document", sha.clone(), sha, 2048, "application/pdf")
459+
}
267460
Item::Pdf { name, pages } => {
268461
// The "PDF" is the pages' description; its render is recorded as done with the drawn pages.
269462
let mut rendered = Vec::new();
@@ -417,3 +610,12 @@ fn help_text(changed: bool) -> String {
417610
text.push_str(" logs Show recent logs\n");
418611
text
419612
}
613+
614+
fn feed(items: usize) -> String {
615+
let mut text = String::from("<rss version=\"2.0\">\n<channel>\n");
616+
for i in 1..=items {
617+
text.push_str(&format!(" <item><title>Post {i}</title></item>\n"));
618+
}
619+
text.push_str("</channel>\n</rss>\n");
620+
text
621+
}

‎app/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,5 +87,6 @@ pub fn configure() -> ApplicationBuilder {
8787
commands.add::<console::retention::RetentionPrune>();
8888
commands.add::<console::retention::GroupsCheck>();
8989
commands.add::<console::demo::DemoReset>();
90+
commands.add::<console::demo::ScreenshotsSeed>();
9091
})
9192
}

‎app/tests/screenshots_seed.rs‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
//! `screenshots:seed` (the CI visual job's dataset): two organizations on the two plans, three projects, builds that
2+
//! cover every kind of change, and ids and timestamps fixed so every run gives the same pixels.
3+
4+
use app::models::{Build, Organization, Snapshot};
5+
use app::testing::fixtures;
6+
use laravel::db;
7+
use laravel::testing::prelude::*;
8+
9+
#[laravel::test]
10+
async fn the_screenshots_dataset_is_seeded_the_same_every_time(_app: Application) -> laravel::Result<()> {
11+
Box::pin(seeded()).await
12+
}
13+
14+
async fn seeded() -> laravel::Result<()> {
15+
let store = fixtures::blob_store().await?;
16+
app::domain::demo::screenshots_seed(&store, "1").await?;
17+
18+
let plans: Vec<(String, String)> = Organization::query()
19+
.order_by(Organization::id.asc())
20+
.get()
21+
.await?
22+
.into_iter()
23+
.map(|o| (o.slug, o.plan))
24+
.collect();
25+
assert_eq!(plans, [("acme".to_string(), "team".to_string()), ("side-project".to_string(), "free".to_string())]);
26+
let builds = Build::query().order_by(Build::id.asc()).get().await?;
27+
assert!(builds.len() >= 7, "{} builds", builds.len());
28+
assert!(builds.iter().all(|b| b.state == "completed"), "every build concluded");
29+
// The invoices' second build has a PDF that was never uploaded.
30+
let failed =
31+
Snapshot::query().filter(Snapshot::name.eq("invoice_long.pdf")).first().await?.expect("the missing pdf");
32+
assert_eq!(failed.state, "failed");
33+
// Fixed ids and prefixes.
34+
// Ids don't restart in a reused test database (sequences survive the rollback), so each pid is checked against
35+
// its own row's id.
36+
let mismatched: i64 =
37+
db::query!("SELECT COUNT(*) FROM organizations WHERE pid <> md5('organizations:' || id)::uuid")
38+
.scalar()
39+
.await?
40+
.unwrap_or(1);
41+
assert_eq!(mismatched, 0, "every organization's pid comes from its id");
42+
let prefix: String = db::query!("SELECT token_prefix FROM user_tokens LIMIT 1").scalar().await?.unwrap();
43+
assert!(prefix.starts_with("vcu_") && prefix.len() == 10, "{prefix}");
44+
// A second run refuses: it needs an empty database.
45+
assert!(app::domain::demo::screenshots_seed(&store, "1").await.is_err());
46+
Ok(())
47+
}

0 commit comments

Comments
 (0)