Skip to content

Commit e2b7db5

Browse files
authored
Processing: redrawn bases charged, credit checks count pages, billing hears every finish (#199 leftovers) (#218)
* Processing: redrawn bases are charged, the credit check counts pages, billing hears a build finish even when its check fails (#199) - A document's base drawn again with the head's settings is a render the build made that none of its snapshots points at; the charge counted only renders its snapshots point at, so those pages were never charged. It now counts every render the build made. - The part-way credit check ran every 200 snapshots, so a build of long documents could compare thousands of pages past its credits. It now counts pages (a document's from its render). - finished() returned early when BuildChanged's dispatch failed (a forge that's down), so CreditsSpent (low-credit emails, automatic packs) never ran. Both run now, and the first error is returned. * Tests: each test's pool holds at most 4 connections (sc-9385) The suite is one binary whose tests boot at once, each with its own pool of up to 10: a CI runner's threads asked Postgres for more than its 100 connections, and tests failed at boot with "pool timed out".
1 parent 99ac104 commit e2b7db5

3 files changed

Lines changed: 62 additions & 13 deletions

File tree

‎app/src/domain/processing.rs‎

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -248,10 +248,25 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la
248248
Ok(())
249249
}
250250

251-
/// How many snapshots a run compares between credit checks: a build that runs out part-way overruns by at most this
252-
/// many comparisons (and the builds of the organization running at the same moment).
251+
/// How many pages a run compares between credit checks (a screenshot or text snapshot is one, a document one per page):
252+
/// a build that runs out part-way overruns by at most this many pages, plus the document that crosses the line, and
253+
/// the builds of the organization running at the same moment. Counting snapshots let a build of long documents
254+
/// compare 200 of them, thousands of pages, between checks (#199).
253255
pub const CREDIT_CHECK_EVERY: usize = 200;
254256

257+
/// Each of the build's documents' page counts, by snapshot id, from their renders.
258+
async fn document_page_counts(build_id: i64) -> laravel::Result<HashMap<i64, usize>> {
259+
let rows = db::query!(
260+
"SELECT s.id, jsonb_array_length(r.pages)::BIGINT AS pages FROM snapshots s JOIN renders r ON r.id = s.render_id \
261+
WHERE s.build_id = {build_id} AND s.kind = 'document'"
262+
)
263+
.select()
264+
.await?;
265+
rows.iter()
266+
.map(|r| Ok((r.try_get::<i64>("id")?, usize::try_from(r.try_get::<i64>("pages")?).unwrap_or(0))))
267+
.collect()
268+
}
269+
255270
/// Charge what the build has used so far and, when its organization is now out of credits, stop it as `run` does
256271
/// (billing's listeners get their chance to reload first). `true` when it stopped. Outside any transaction.
257272
async fn stop_part_way(build: &Build) -> laravel::Result<bool> {
@@ -294,12 +309,15 @@ async fn fail_for_config(mut build: Build, invalid: &ConfigInvalid) -> laravel::
294309
/// The build concluded (or stopped): billing hears what was spent, and its checks, comment and pages follow.
295310
async fn finished(build_id: i64, project_id: i64) -> laravel::Result<()> {
296311
// The build's check and live pages first: billing's listeners (an automatic pack, the low-credit emails) call
297-
// Stripe and the outbox, and mustn't hold them up.
298-
crate::events::BuildChanged { build_id }.dispatch().await?;
299-
if let Some(project) = Project::find(project_id).await? {
300-
crate::events::CreditsSpent { organization_id: project.organization_id }.dispatch().await?;
301-
}
302-
Ok(())
312+
// Stripe and the outbox, and mustn't hold them up. Billing still hears when they fail (a forge that's down), and
313+
// the first error is returned.
314+
let changed = crate::events::BuildChanged { build_id }.dispatch().await;
315+
let spent = match Project::find(project_id).await {
316+
Ok(Some(project)) => crate::events::CreditsSpent { organization_id: project.organization_id }.dispatch().await,
317+
Ok(None) => Ok(()),
318+
Err(e) => Err(e),
319+
};
320+
changed.and(spent)
303321
}
304322

305323
/// A document's base, drawn the way the head is drawn.
@@ -581,7 +599,8 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
581599

582600
let compare_started = std::time::Instant::now();
583601
let mut seen = HashSet::new();
584-
let mut compared = 0usize;
602+
let page_counts = document_page_counts(id).await?;
603+
let (mut compared, mut next_check) = (0usize, CREDIT_CHECK_EVERY);
585604
for mut snapshot in snapshots {
586605
seen.insert((snapshot.name.clone(), snapshot.platform.clone()));
587606
if snapshot.state == "failed" {
@@ -603,9 +622,12 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
603622
if super::shutdown::stopping() {
604623
return Err(super::shutdown::Stopped.into());
605624
}
606-
compared += 1;
607-
if compared.is_multiple_of(CREDIT_CHECK_EVERY) && Box::pin(stop_part_way(&build)).await? {
608-
return Ok(true);
625+
compared += page_counts.get(&snapshot.id).copied().unwrap_or(1).max(1);
626+
if compared >= next_check {
627+
next_check = compared + CREDIT_CHECK_EVERY;
628+
if Box::pin(stop_part_way(&build)).await? {
629+
return Ok(true);
630+
}
609631
}
610632
let key = (snapshot.name.clone(), snapshot.platform.clone());
611633
match Box::pin(compare(&mut snapshot, store, &settings, base_snapshots.get(&key))).await {
@@ -944,7 +966,7 @@ async fn charge_locked(build: &Build) -> laravel::Result<()> {
944966
(SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed')::BIGINT AS checks, \
945967
(SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND kind = 'text' AND state = 'changed')::BIGINT AS text_diffs, \
946968
(SELECT COALESCE(SUM(jsonb_array_length(r.pages)), 0) FROM renders r \
947-
WHERE r.id IN (SELECT render_id FROM snapshots WHERE build_id = {id}) AND r.made_by_build_id = {id})::BIGINT AS pages, \
969+
WHERE r.made_by_build_id = {id})::BIGINT AS pages, \
948970
(SELECT COUNT(DISTINCT d.id) FROM diffs d JOIN snapshot_pages p ON p.diff_id = d.id \
949971
JOIN snapshots s ON s.id = p.snapshot_id WHERE s.build_id = {id} AND d.made_by_build_id = {id})::BIGINT AS image_diffs"
950972
)

‎app/src/testing.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ pub fn configure() -> ApplicationBuilder {
4545
("SESSION_DRIVER", "database"),
4646
("WORKFLOW_STORE", "memory"),
4747
("DB_CONNECTION", "pgsql"),
48+
// Each test has its own application and pool, and the whole suite is one binary whose tests boot at once:
49+
// at the default 10 connections each, a CI runner's threads asked Postgres for more than its 100 and tests
50+
// failed at boot with "pool timed out" (sc-9385). A test needs a few at most.
51+
("DB_MAX_CONNECTIONS", "4"),
4852
("VISUALCI_S3_BUCKET", "visualci-test"),
4953
("VISUALCI_S3_ACCESS_KEY_ID", "visualci"),
5054
("VISUALCI_S3_SECRET_ACCESS_KEY", "visualci-dev-secret"),

‎app/tests/processing.rs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,3 +607,26 @@ async fn a_test_that_crashed_shows_its_snapshot_failed_in_place_and_keeps_the_ba
607607
assert_eq!(third["conclusion"], "unchanged", "{third}");
608608
Ok(())
609609
}
610+
611+
/// A document's base drawn again the way its head is drawn (another engine, DPI or renderer version) is a render the
612+
/// head's build made but none of its snapshots points at: the build pays for its pages like any other it drew (#199).
613+
#[laravel::test]
614+
async fn a_build_pays_for_the_base_it_drew_again(app: Application) -> laravel::Result<()> {
615+
fixtures::blob_store().await?;
616+
let token = project_token().await?;
617+
let id = send(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0])]).await;
618+
finalize(&app, &token, &id).await;
619+
let build = Build::query().filter(Build::number.eq(1)).first().await?.expect("the build");
620+
let (build_id, project_id) = (build.id, build.project_id);
621+
let pages = json!([{ "image": "a" }, { "image": "b" }, { "image": "c" }]);
622+
db::query!(
623+
"INSERT INTO renders (project_id, source_fingerprint, renderer, source_blob, state, pages, made_by_build_id) \
624+
SELECT {project_id}, 'base-fp', 'pdfium-300', sha256, 'done', {pages}, {build_id} FROM blobs LIMIT 1"
625+
)
626+
.insert()
627+
.await?;
628+
app::domain::processing::charge(&build).await?;
629+
let charged = Build::find_or_fail(build_id).await?.charged;
630+
assert_eq!(charged["rendered_pages"], 3, "{charged}");
631+
Ok(())
632+
}

0 commit comments

Comments
 (0)