Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 35 additions & 13 deletions app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,10 +248,25 @@ pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> la
Ok(())
}

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

/// Each of the build's documents' page counts, by snapshot id, from their renders.
async fn document_page_counts(build_id: i64) -> laravel::Result<HashMap<i64, usize>> {
let rows = db::query!(
"SELECT s.id, jsonb_array_length(r.pages)::BIGINT AS pages FROM snapshots s JOIN renders r ON r.id = s.render_id \
WHERE s.build_id = {build_id} AND s.kind = 'document'"
)
.select()
.await?;
rows.iter()
.map(|r| Ok((r.try_get::<i64>("id")?, usize::try_from(r.try_get::<i64>("pages")?).unwrap_or(0))))
.collect()
}

/// Charge what the build has used so far and, when its organization is now out of credits, stop it as `run` does
/// (billing's listeners get their chance to reload first). `true` when it stopped. Outside any transaction.
async fn stop_part_way(build: &Build) -> laravel::Result<bool> {
Expand Down Expand Up @@ -294,12 +309,15 @@ async fn fail_for_config(mut build: Build, invalid: &ConfigInvalid) -> laravel::
/// The build concluded (or stopped): billing hears what was spent, and its checks, comment and pages follow.
async fn finished(build_id: i64, project_id: i64) -> laravel::Result<()> {
// The build's check and live pages first: billing's listeners (an automatic pack, the low-credit emails) call
// Stripe and the outbox, and mustn't hold them up.
crate::events::BuildChanged { build_id }.dispatch().await?;
if let Some(project) = Project::find(project_id).await? {
crate::events::CreditsSpent { organization_id: project.organization_id }.dispatch().await?;
}
Ok(())
// Stripe and the outbox, and mustn't hold them up. Billing still hears when they fail (a forge that's down), and
// the first error is returned.
let changed = crate::events::BuildChanged { build_id }.dispatch().await;
let spent = match Project::find(project_id).await {
Ok(Some(project)) => crate::events::CreditsSpent { organization_id: project.organization_id }.dispatch().await,
Ok(None) => Ok(()),
Err(e) => Err(e),
};
changed.and(spent)
}

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

let compare_started = std::time::Instant::now();
let mut seen = HashSet::new();
let mut compared = 0usize;
let page_counts = document_page_counts(id).await?;
let (mut compared, mut next_check) = (0usize, CREDIT_CHECK_EVERY);
for mut snapshot in snapshots {
seen.insert((snapshot.name.clone(), snapshot.platform.clone()));
if snapshot.state == "failed" {
Expand All @@ -603,9 +622,12 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
if super::shutdown::stopping() {
return Err(super::shutdown::Stopped.into());
}
compared += 1;
if compared.is_multiple_of(CREDIT_CHECK_EVERY) && Box::pin(stop_part_way(&build)).await? {
return Ok(true);
compared += page_counts.get(&snapshot.id).copied().unwrap_or(1).max(1);
if compared >= next_check {
next_check = compared + CREDIT_CHECK_EVERY;
if Box::pin(stop_part_way(&build)).await? {
return Ok(true);
}
}
let key = (snapshot.name.clone(), snapshot.platform.clone());
match Box::pin(compare(&mut snapshot, store, &settings, base_snapshots.get(&key))).await {
Expand Down Expand Up @@ -944,7 +966,7 @@ async fn charge_locked(build: &Build) -> laravel::Result<()> {
(SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed')::BIGINT AS checks, \
(SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND kind = 'text' AND state = 'changed')::BIGINT AS text_diffs, \
(SELECT COALESCE(SUM(jsonb_array_length(r.pages)), 0) FROM renders r \
WHERE r.id IN (SELECT render_id FROM snapshots WHERE build_id = {id}) AND r.made_by_build_id = {id})::BIGINT AS pages, \
WHERE r.made_by_build_id = {id})::BIGINT AS pages, \
(SELECT COUNT(DISTINCT d.id) FROM diffs d JOIN snapshot_pages p ON p.diff_id = d.id \
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"
)
Expand Down
4 changes: 4 additions & 0 deletions app/src/testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ pub fn configure() -> ApplicationBuilder {
("SESSION_DRIVER", "database"),
("WORKFLOW_STORE", "memory"),
("DB_CONNECTION", "pgsql"),
// Each test has its own application and pool, and the whole suite is one binary whose tests boot at once:
// at the default 10 connections each, a CI runner's threads asked Postgres for more than its 100 and tests
// failed at boot with "pool timed out" (sc-9385). A test needs a few at most.
("DB_MAX_CONNECTIONS", "4"),
("VISUALCI_S3_BUCKET", "visualci-test"),
("VISUALCI_S3_ACCESS_KEY_ID", "visualci"),
("VISUALCI_S3_SECRET_ACCESS_KEY", "visualci-dev-secret"),
Expand Down
23 changes: 23 additions & 0 deletions app/tests/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,3 +607,26 @@ async fn a_test_that_crashed_shows_its_snapshot_failed_in_place_and_keeps_the_ba
assert_eq!(third["conclusion"], "unchanged", "{third}");
Ok(())
}

/// A document's base drawn again the way its head is drawn (another engine, DPI or renderer version) is a render the
/// head's build made but none of its snapshots points at: the build pays for its pages like any other it drew (#199).
#[laravel::test]
async fn a_build_pays_for_the_base_it_drew_again(app: Application) -> laravel::Result<()> {
fixtures::blob_store().await?;
let token = project_token().await?;
let id = send(&app, &token, "c1", "c0", &[("home/hero/desktop.png", [255, 0, 0])]).await;
finalize(&app, &token, &id).await;
let build = Build::query().filter(Build::number.eq(1)).first().await?.expect("the build");
let (build_id, project_id) = (build.id, build.project_id);
let pages = json!([{ "image": "a" }, { "image": "b" }, { "image": "c" }]);
db::query!(
"INSERT INTO renders (project_id, source_fingerprint, renderer, source_blob, state, pages, made_by_build_id) \
SELECT {project_id}, 'base-fp', 'pdfium-300', sha256, 'done', {pages}, {build_id} FROM blobs LIMIT 1"
)
.insert()
.await?;
app::domain::processing::charge(&build).await?;
let charged = Build::find_or_fail(build_id).await?.charged;
assert_eq!(charged["rendered_pages"], 3, "{charged}");
Ok(())
}
Loading