Skip to content
Open
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
57 changes: 56 additions & 1 deletion app/tests/billing_branches.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Billing branches the #199 review found untested: a reload whose pay call is cut off and Stripe then says the invoice
//! is still open (declined) or can't say (left alone, the claim kept); the unpaid subscription's notice; and Checkout
//! refusing a second subscription while one is unpaid.
//! refusing a second subscription while one is unpaid; and the re-check under the reload's claim.

use app::events::CreditsRanOut;
use app::models::User;
Expand Down Expand Up @@ -177,3 +177,58 @@ async fn checkout_refuses_a_second_subscription_while_one_is_unpaid(app: Applica
assert!(stripe.sent().is_empty(), "no Checkout session");
Ok(())
}

/// What changes under the claim in [`race_the_claim`].
enum Race {
PackBought,
MovedToFree,
}

/// Make the claim's own UPDATE change the organization, as if another reload (or a plan change) finished between the
/// first checks and the claim.
async fn race_the_claim(race: Race) -> laravel::Result<()> {
match race {
Race::PackBought => db::query!(
"CREATE OR REPLACE FUNCTION test_reload_race() RETURNS trigger AS $$ \
BEGIN NEW.credits_balance := 500000; RETURN NEW; END $$ LANGUAGE plpgsql"
),
Race::MovedToFree => db::query!(
"CREATE OR REPLACE FUNCTION test_reload_race() RETURNS trigger AS $$ \
BEGIN NEW.plan := 'free'; RETURN NEW; END $$ LANGUAGE plpgsql"
),
}
.statement()
.await?;
db::query!(
"CREATE TRIGGER test_reload_race BEFORE UPDATE OF reload_started_at ON organizations FOR EACH ROW \
WHEN (NEW.reload_started_at IS NOT NULL) EXECUTE FUNCTION test_reload_race()"
)
.statement()
.await?;
Ok(())
}

/// A pack another reload bought while this one was claiming: the re-check under the claim sees the credits, and
/// buys nothing more.
#[laravel::test(app = with_stripe_key)]
async fn the_check_under_the_claim_sees_a_pack_another_reload_just_bought(_app: Application) -> laravel::Result<()> {
let org = team_out_of_credits("acme").await?;
race_the_claim(Race::PackBought).await?;
let fake = pay_cut_off(Some("paid"));
CreditsRanOut { organization_id: org }.dispatch().await?;
assert_eq!(posts_to(&fake, "invoices"), 0, "no second pack");
let (balance, paused, claimed, problem) = org_row(org).await?;
assert_eq!((balance, paused, claimed, problem), (500_000, false, false, None), "the claim is released");
Ok(())
}

/// A move to Free while this reload was claiming: Free has no packs, so the re-check buys none.
#[laravel::test(app = with_stripe_key)]
async fn the_check_under_the_claim_sees_a_move_to_free(_app: Application) -> laravel::Result<()> {
let org = team_out_of_credits("acme").await?;
race_the_claim(Race::MovedToFree).await?;
let fake = pay_cut_off(Some("paid"));
CreditsRanOut { organization_id: org }.dispatch().await?;
assert_eq!(posts_to(&fake, "invoices"), 0, "no pack on Free");
Ok(())
}
74 changes: 74 additions & 0 deletions app/tests/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,20 @@ async fn a_build_pays_for_the_image_diffs_it_makes_and_another_project_reusing_o
second.contains("snapshot checked") && !second.contains("image diff"),
"the same two images again: {second}"
);
// The second project's changed page points at the diff row the first one made.
let (one, two) = (orgs[0], orgs[1]);
let diffs: Vec<Option<i64>> = db::query!(
"SELECT sp.diff_id FROM snapshot_pages sp JOIN snapshots s ON s.id = sp.snapshot_id \
JOIN builds b ON b.id = s.build_id JOIN projects p ON p.id = b.project_id \
WHERE sp.state = 'changed' AND sp.diff_id IS NOT NULL AND p.organization_id IN ({one}, {two}) ORDER BY p.organization_id"
)
.select()
.await?
.iter()
.map(|r| r.try_get("diff_id").unwrap())
.collect();
assert_eq!(diffs.len(), 2, "one diffed page each: {diffs:?}");
assert!(diffs[0].is_some() && diffs[0] == diffs[1], "one diff row, shared: {diffs:?}");
Ok(())
}

Expand Down Expand Up @@ -630,3 +644,63 @@ async fn a_build_pays_for_the_base_it_drew_again(app: Application) -> laravel::R
assert_eq!(charged["rendered_pages"], 3, "{charged}");
Ok(())
}

/// What the recording listeners below heard, by organization: "changed" for `BuildChanged`, "spent" for `CreditsSpent`.
static HEARD: std::sync::Mutex<Vec<(i64, &'static str)>> = std::sync::Mutex::new(Vec::new());
/// Organizations whose `BuildChanged` listeners fail, as a forge that's down makes the check's update fail.
static CHECK_FAILS: std::sync::Mutex<Vec<i64>> = std::sync::Mutex::new(Vec::new());

async fn organization_of_build(build_id: i64) -> laravel::Result<i64> {
Ok(db::query!(
"SELECT p.organization_id FROM builds b JOIN projects p ON p.id = b.project_id WHERE b.id = {build_id}"
)
.scalar()
.await?
.unwrap_or_default())
}

#[laravel::event::listener]
async fn record_build_changed(event: laravel::event::Event<app::events::BuildChanged>) -> laravel::Result<()> {
let org = organization_of_build(event.build_id).await?;
HEARD.lock().unwrap().push((org, "changed"));
if CHECK_FAILS.lock().unwrap().contains(&org) {
return Err(laravel::Error::msg("the forge is down"));
}
Ok(())
}

#[laravel::event::listener]
async fn record_credits_spent(event: laravel::event::Event<app::events::CreditsSpent>) -> laravel::Result<()> {
HEARD.lock().unwrap().push((event.organization_id, "spent"));
Ok(())
}

/// A finished build updates its own check and pages first, then billing hears it spent credits (an automatic pack and
/// the low-credit emails call Stripe and mustn't hold up the check). Billing hears even when the check's update fails
/// (#199).
#[laravel::test]
async fn billing_hears_a_finished_build_after_its_check_even_when_the_check_fails(
app: Application,
) -> laravel::Result<()> {
fixtures::blob_store().await?;
let token = project_token().await?;
let org: i64 = db::query!(
"SELECT p.organization_id FROM project_tokens t JOIN projects p ON p.id = t.project_id ORDER BY t.id DESC LIMIT 1"
)
.scalar()
.await?
.unwrap();
let heard = || HEARD.lock().unwrap().iter().filter(|(o, _)| *o == org).map(|(_, e)| *e).collect::<Vec<_>>();

run(&app, &token, "c1", "c0", &[("home/desktop.png", [255, 0, 0])]).await;
let first = heard();
let spent = first.iter().position(|e| *e == "spent").expect("billing heard the build finish");
assert!(first[..spent].contains(&"changed"), "the check first: {first:?}");

CHECK_FAILS.lock().unwrap().push(org);
let id = send(&app, &token, "c2", "c1", &[("home/desktop.png", [0, 0, 255])]).await;
app.post(format!("/api/v1/builds/{id}/finalize")).header("authorization", format!("Bearer {token}")).await;
let second = heard()[first.len()..].to_vec();
assert!(second.contains(&"changed") && second.contains(&"spent"), "billing hears it anyway: {second:?}");
Ok(())
}
15 changes: 15 additions & 0 deletions app/tests/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,21 @@ async fn pays_for_pages_once(app: Application) -> laravel::Result<()> {
}
assert!(drawn[0].contains("2 pages drawn"), "the build that queued the render pays for its pages: {}", drawn[0]);
assert!(!drawn[1].contains("drawn"), "the build sharing it doesn't pay again: {}", drawn[1]);
// It did share the render (its group reads the first build's row), and it was charged, with none of the pages.
let (one, two) = (
Build::query().filter(Build::number.eq(1)).first().await?.unwrap(),
Build::query().filter(Build::number.eq(2)).first().await?.unwrap(),
);
let render_of = |id: i64| async move {
db::query!("SELECT render_id FROM effective_snapshots WHERE build_id = {id} AND kind = 'document'")
.scalar::<i64>()
.await
};
assert_eq!(render_of(one.id).await?, Some(render_id));
assert_eq!(render_of(two.id).await?, Some(render_id), "one render, waited on by both");
assert_eq!(one.charged["rendered_pages"], 2, "{}", one.charged);
assert_eq!(two.charged["rendered_pages"], 0, "charged, without the shared pages: {}", two.charged);
assert!(!drawn[1].is_empty(), "the second build was charged at all");
Ok(())
}

Expand Down
Loading