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
5 changes: 2 additions & 3 deletions app/src/domain/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,10 +408,9 @@ impl Seeder<'_> {
}
let build = outcome(super::builds::finalize_shard(build, None, false).await)?;
let id = build.id;
let concluded = Box::pin(db::transaction(async |_| {
super::processing::lock(id).await?;
let concluded = Box::pin(super::processing::exclusive(id, 300, || async {
let build = Build::find_or_fail(id).await?;
super::processing::process(build, self.store, self.renderer_version).await
Box::pin(super::processing::process(build, self.store, self.renderer_version)).await
}))
.await?;
if !concluded {
Expand Down
194 changes: 164 additions & 30 deletions app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ impl Usage {
}
}

/// Hold the build's lock until the transaction ends: one worker (or one early comparison) works on a build at a time.
/// Hold the build's advisory lock until the transaction ends. Only short transactions take it: charging, concluding,
/// and reviews, which must not interleave with a conclusion. A whole processing run holds [`exclusive`] instead.
///
/// # Errors
/// On a database error.
Expand All @@ -80,6 +81,113 @@ pub async fn lock(build_id: i64) -> laravel::Result<()> {
Ok(())
}

/// How long [`exclusive`] holds a build at most: longer than `ProcessBuild`'s 15-minute timeout, so a run never
/// outlives its lock. A run that stops early releases it at once, even when its worker kills it.
pub const HOLD_MINUTES: i64 = 20;

/// How long a processing job waits for another run of the same build. Then it leaves that run a note to process the
/// build again when it's done ([`exclusive`]), rather than hold a worker while it waits.
pub const JOB_WAIT_SECONDS: i64 = 10;

/// The note a job leaves when another run holds the build: run it again once that run is done.
fn again_key(build_id: i64) -> String {
format!("builds.process-again:{build_id}")
}

/// Run `work` while holding the build's processing lock, waiting up to `wait_seconds` for it (0 tries once): one
/// worker (or one early comparison, or the demo reset) works on a build at a time. The lock is a row in the cache
/// store, taken and released in statements of their own, so the work runs outside any transaction: its downloads,
/// decoding and diffing hold no database connection and no row locks, and its writes commit as they go (an upload
/// registering the same blob never waits for a run). Released when `work` ends, fails or is dropped. After releasing
/// it, a job that gave up waiting meanwhile is queued again.
///
/// # Errors
/// [`laravel::cache::LockTimeout`] when another run holds the build for longer than `wait_seconds`, or `work`'s error.
pub async fn exclusive<T, F, Fut>(build_id: i64, wait_seconds: i64, work: F) -> laravel::Result<T>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = laravel::Result<T>>,
{
use laravel::time::ToSpan;
let out = laravel::cache::lock(&format!("builds.process:{build_id}"), HOLD_MINUTES.minutes())?
.block(wait_seconds.seconds())
.get(work)
.await;
if !matches!(&out, Err(e) if e.is::<laravel::cache::LockTimeout>())
&& laravel::cache::pull::<bool>(&again_key(build_id)).await?.is_some()
{
Box::pin(crate::jobs::process_build::ProcessBuild { build_id }.dispatch().into_future()).await?;
}
out
}

/// What `ProcessBuild` does: charge what the build used so far, stop it when its organization is out of credits, and
/// otherwise process it as far as it can go ([`process`]) under [`exclusive`]. A failure fails the build. When another
/// run holds the build past [`JOB_WAIT_SECONDS`], that run processes it again when it's done, so a render that finished
/// during it isn't missed.
///
/// # Errors
/// On a database or queue error.
pub async fn run(build_id: i64, store: &BlobStore, renderer_version: &str) -> laravel::Result<()> {
use laravel::time::ToSpan;
let id = build_id;
// Charge what the build has used so far ([`charge`] is its own short transaction): the organization's row is
// locked only while it's charged, and what's charged stays charged if the run fails.
let build = Build::find_or_fail(id).await?;
if build.state != "processing" {
return Ok(());
}
Box::pin(charge(&build)).await?;
// Out of credits part-way (a large build's pages): stop here rather than draw the rest. Outside any transaction,
// so billing's listeners (an automatic reload charges the card) run on committed data.
let build = stop_if_out_of_credits(Build::find_or_fail(id).await?).await?;
if build.state == "failed" {
drop_unneeded_renders(id).await?;
return finished(id, build.project_id).await;
}
let work = move || async move {
let build = Build::find_or_fail(id).await?;
if build.state != "processing" {
return Ok(false);
}
// Boxed: processing's future is large, and the lock's own future holds it.
Box::pin(process(build, store, renderer_version)).await
};
let busy = |r: &laravel::Result<bool>| matches!(r, Err(e) if e.is::<laravel::cache::LockTimeout>());
let mut result = Box::pin(exclusive(id, JOB_WAIT_SECONDS, work)).await;
if busy(&result) {
// Leave the note first, then try once more: either this run takes the build, or whoever holds it now finds
// the note when it releases it.
laravel::cache::put(&again_key(id), true, HOLD_MINUTES.minutes()).await?;
result = Box::pin(exclusive(id, 0, work)).await;
}
match result {
Ok(true) => finished(id, build.project_id).await?,
Ok(false) => tracing::debug!(build_id = id, "build waiting for renders"),
Err(e) if e.is::<laravel::cache::LockTimeout>() => {
tracing::info!(build_id = id, "another run is processing the build; it runs it again when it's done");
}
Err(e) => {
tracing::error!(build_id = id, error = %e, "processing a build failed");
let error = Some(e.to_string());
if let Some(mut build) = Build::find(id).await? {
update!(build { state: "failed", error }).await?;
}
crate::events::BuildChanged { build_id: id }.dispatch().await?;
}
}
Ok(())
}

/// 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<()> {
if let Some(project) = Project::find(project_id).await? {
crate::events::CreditsSpent { organization_id: project.organization_id }.dispatch().await?;
}
crate::events::BuildChanged { build_id }.dispatch().await?;
Ok(())
}

/// A document's base, drawn the way the head is drawn.
enum Redraw {
Ready(Box<Snapshot>),
Expand Down Expand Up @@ -148,7 +256,10 @@ async fn approved_settings_build(mut build: Build) -> laravel::Result<Build> {
}

/// Process a finalized build as far as it can go: confirm uploads, queue renders, and once every render is done,
/// compare and conclude. Returns whether the build concluded (false while renders are outstanding).
/// compare and conclude. Returns whether the build concluded (false while renders are outstanding). The caller holds
/// [`exclusive`]; this runs outside any transaction, so storage requests, decoding and diffing never hold a database
/// connection or a row lock (blob rows above all, which uploads register). Per-snapshot results commit as they go and
/// are safe to write again (a run killed part-way is run again); the conclusion is one short transaction at the end.
///
/// # Errors
/// On a database or storage error.
Expand Down Expand Up @@ -245,7 +356,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
continue;
}
let key = (snapshot.name.clone(), snapshot.platform.clone());
match compare(&mut snapshot, store, &settings, base_snapshots.get(&key)).await {
match Box::pin(compare(&mut snapshot, store, &settings, base_snapshots.get(&key))).await {
Ok(()) => set_baseline_id(&mut snapshot, baseline_rows.get(&key).copied()).await?,
Err(e) => {
tracing::warn!(build = id, snapshot = snapshot.id, error = %e, "comparing a snapshot failed");
Expand Down Expand Up @@ -296,7 +407,7 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
}
for key in keys {
let Some(base) = base_snapshots.get(key) else { continue };
carry_forward(&build, &settings, store, base).await?;
Box::pin(carry_forward(&build, &settings, store, base)).await?;
}
}
for (name, platform) in &removed {
Expand Down Expand Up @@ -364,29 +475,41 @@ pub async fn process(build: Build, store: &BlobStore, renderer_version: &str) ->
}
let has_base = !base_snapshots.is_empty();

// What depends on the build's own rows comes before sourcing deletes the unchanged ones: the charge, and whether
// it sent anything (an empty build fails).
charge(&build).await?;
let sent: i64 = db::query!(
"SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed' \
AND platform <> 'visualci'"
)
.scalar()
.await?
.unwrap_or(0);
groups::source_unchanged(&build).await?;

let mut build = build;
let warnings = serde_json::json!(warnings);
update!(build { warnings }).await?;
let build = conclude(build, base_build_id, has_base, sent).await?;
if build.review_state == "auto_approved" {
// Nothing to review (or the project's first build): its changes are the baselines now.
let all = super::snapshots::of_build(build.id).await?;
let changes: Vec<&Snapshot> = all.iter().filter(|s| !is_config_item(s)).collect();
baselines::record(&build, &changes, None, None, "auto").await?;
}
Ok(true)

// The conclusion, in one short transaction of database work only, under the build's advisory lock (a review takes
// it too): still processing (another run may have concluded it), it's charged, its unchanged groups are read from
// the builds that hold them, and it's concluded, all or nothing.
Box::pin(db::transaction(async |_| {
lock(id).await?;
let mut build = Build::find_or_fail(id).await?;
if build.state != "processing" {
return Ok(build.state == "completed");
}
// What depends on the build's own rows comes before sourcing deletes the unchanged ones: the charge, and
// whether it sent anything (an empty build fails). The build's advisory lock is held already.
Box::pin(charge_locked(&build)).await?;
let sent: i64 = db::query!(
"SELECT COUNT(*) FROM snapshots WHERE build_id = {id} AND NOT carried_forward AND state <> 'removed' \
AND platform <> 'visualci'"
)
.scalar()
.await?
.unwrap_or(0);
groups::source_unchanged(&build).await?;

let warnings = warnings.clone();
update!(build { warnings }).await?;
let build = conclude(build, base_build_id, has_base, sent).await?;
if build.review_state == "auto_approved" {
// Nothing to review (or the project's first build): its changes are the baselines now.
let all = super::snapshots::of_build(build.id).await?;
let changes: Vec<&Snapshot> = all.iter().filter(|s| !is_config_item(s)).collect();
baselines::record(&build, &changes, None, None, "auto").await?;
}
Ok(true)
}))
.await
}

/// Carry a base snapshot forward into a build as its own row, compared with the base (unchanged).
Expand All @@ -413,7 +536,8 @@ async fn carry_forward(
base.ignore_anti_aliasing,
&base.meta,
);
// A second run of this processing (the job retried, or run twice at once) finds the row there already.
// A second run of this processing (the job retried after a run that stopped part-way) finds the row there
// already: it compares it again only when that run stopped before comparing it.
let inserted = db::query!(
"INSERT INTO snapshots (pid, build_id, group_key, name, platform, kind, format, source_fingerprint, source_blob, \
render_id, engine, ignore_rules, environment, threshold, ignore_anti_aliasing, meta, state, carried_forward) \
Expand All @@ -424,14 +548,14 @@ async fn carry_forward(
.insert()
.await?
.rows_affected();
if inserted == 0 {
return Ok(());
}
let mut carried = Snapshot::query()
.filter(Snapshot::build_id.eq(id) & Snapshot::name.eq(name.as_str()) & Snapshot::platform.eq(platform.as_str()))
.first()
.await?
.ok_or_else(|| laravel::Error::msg("the carried snapshot wasn't saved"))?;
if inserted == 0 && !(carried.carried_forward && carried.state == "pending") {
return Ok(());
}
if let Err(e) = compare(&mut carried, store, settings, Some(base)).await {
tracing::warn!(build = id, snapshot = carried.id, error = %e, "carrying a snapshot forward failed");
mark_failed(&mut carried, &format!("comparison failed: {e}")).await?;
Expand Down Expand Up @@ -516,6 +640,16 @@ pub async fn recount(mut build: Build) -> laravel::Result<Build> {
/// # Errors
/// On a database error.
pub async fn charge(build: &Build) -> laravel::Result<()> {
// Its own short transaction under the build's advisory lock (a savepoint inside the conclusion's), so two charges
// of one build (a run's, an early comparison's) never both charge the same delta.
db::transaction(async |_| {
lock(build.id).await?;
charge_locked(build).await
})
.await
}

async fn charge_locked(build: &Build) -> laravel::Result<()> {
let project = Project::find_or_fail(build.project_id).await?;
let mut fresh = Build::find_or_fail(build.id).await?;
let charged: Usage = serde_json::from_value(fresh.charged.clone()).unwrap_or_default();
Expand Down
18 changes: 15 additions & 3 deletions app/src/http/api/builds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,10 @@ struct CompareTarget {
platform: String,
}

/// How long an early comparison waits for another one of the same build (a local run's parallel tests) or its
/// processing, before it answers 409 to be asked again.
const COMPARE_WAIT_SECONDS: i64 = 20;

/// `POST /api/v1/builds/{pid}/compare`: compare some snapshots of a build that's still receiving, for a local run that
/// checks each test as it goes. Each comes back with its state: `pending` while its file is missing or its PDF is
/// rendering (ask again), `unchanged`, `changed`, `added`, `ignored` or `failed`.
Expand All @@ -332,12 +336,20 @@ pub async fn compare(
}
let wanted: Vec<(String, String)> = params.snapshots.into_iter().map(|t| (t.name, t.platform)).collect();
let version = renderer_version();
let compared = laravel::db::transaction(async |_| {
crate::domain::processing::lock(build.id).await?;
// Under the build's processing lock and outside any transaction: the comparisons' downloads and diffs hold
// no database connection or row locks (uploads register the same blobs meanwhile).
let compared = crate::domain::processing::exclusive(build.id, COMPARE_WAIT_SECONDS, || async {
let build = Build::find_or_fail(build.id).await?;
crate::domain::processing::compare_now(&build, &store, &version, &wanted).await
})
.await?
.await
.map_err(|e| {
if e.is::<laravel::cache::LockTimeout>() {
ApiError::conflict("the build is busy comparing other snapshots; ask again in a few seconds")
} else {
e.into()
}
})?
.map_err(ApiError::bad_request)?;
let missing: Vec<&str> = wanted
.iter()
Expand Down
64 changes: 5 additions & 59 deletions app/src/jobs/process_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,82 +2,28 @@
//! when a build's last shard finalizes, and again whenever a render it waits on finishes: dispatches for one build
//! within a few seconds run once (a build of 1,000 PDFs finishing its renders together is one run, not 1,000).

use laravel::db;
use laravel::queue::{Queueable, job};

use crate::domain::processing;
use crate::events::{BuildChanged, CreditsSpent};
use crate::models::Build;
use crate::storage::BlobStore;

#[derive(Queueable)]
pub struct ProcessBuild {
pub build_id: i64,
}

#[job(name = "builds.process", debounce_for = 3.seconds(), max_wait = 30.seconds())]
// A big build downloads, decodes and diffs thousands of images: 15 minutes, well within the build's processing lock
// (`processing::HOLD_MINUTES`), so the lock always outlives the run that holds it.
#[job(name = "builds.process", debounce_for = 3.seconds(), max_wait = 30.seconds(), timeout = 15.minutes())]
impl ProcessBuild {
fn debounce_id(&self) -> i64 {
self.build_id
}

async fn handle(self) -> laravel::Result<()> {
let id = self.build_id;
let store = BlobStore::current().await?;
let version = crate::http::api::builds::renderer_version();
// Charge what the build has used so far in a short transaction of its own: the organization's row is locked
// only while it's charged, never for a whole run, and what's charged stays charged if the run fails.
let charged = db::transaction(async |_| {
processing::lock(id).await?;
let build = Build::find_or_fail(id).await?;
if build.state == "processing" {
processing::charge(&build).await?;
}
Ok(build)
})
.await?;
if charged.state != "processing" {
return Ok(());
}
// Out of credits part-way (a large build's pages): stop here rather than draw the rest. Outside any
// transaction, so billing's listeners (an automatic reload charges the card) run on committed data.
let build = processing::stop_if_out_of_credits(charged).await?;
if build.state == "failed" {
processing::drop_unneeded_renders(id).await?;
finished(id, build.project_id).await?;
return Ok(());
}
// One run at a time per build (the advisory lock), all its comparison writes together.
let result = db::transaction(async |_| {
processing::lock(id).await?;
let build = Build::find_or_fail(id).await?;
if build.state != "processing" {
return Ok(false);
}
processing::process(build, &store, &version).await
})
.await;
match result {
Ok(true) => finished(id, build.project_id).await?,
Ok(false) => tracing::debug!(build_id = id, "build waiting for renders"),
Err(e) => {
tracing::error!(build_id = id, error = %e, "processing a build failed");
let error = Some(e.to_string());
if let Some(mut build) = Build::find(id).await? {
laravel::model::update!(build { state: "failed", error }).await?;
}
BuildChanged { build_id: id }.dispatch().await?;
}
}
Ok(())
// Boxed: a sync queue (tests) runs this inside the request that dispatched it.
Box::pin(processing::run(self.build_id, &store, &version)).await
}
}

/// 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<()> {
if let Some(project) = crate::models::Project::find(project_id).await? {
CreditsSpent { organization_id: project.organization_id }.dispatch().await?;
}
BuildChanged { build_id }.dispatch().await?;
Ok(())
}
Loading
Loading