Files
PiCloud/crates/picloud/tests/retry_e2e.rs
MechaCat02 328d7d55e6 test(v1.1.9): queue_e2e + invoke_e2e + retry_e2e + migration test
Four new test binaries, DB-gated via the established pool_or_skip()
pattern (returns Some(pool) when DATABASE_URL is set; prints a skip
notice and returns None otherwise — so plain `cargo test` stays green
locally while CI runs them).

crates/picloud/tests/queue_e2e.rs (4 tests):
  - queue_receive_acks_on_success: enqueue → consumer fires → KV
    marker observable → queue row deleted (ack worked)
  - queue_receive_dead_letters_after_max_attempts: throwing handler
    retries 3× via the dispatcher's compute_backoff path → dead_letters
    row written, queue row deleted
  - queue_one_consumer_per_queue_rejected: second trigger create for the
    same (app_id, queue_name) returns 4xx with the documented "already
    has a consumer trigger" message (advisory-lock guard works)
  - queue_visibility_timeout_reclaim: insert message with stale claim
    (claimed_at = NOW() - 60s, visibility_timeout = 5s); either the
    dispatcher re-claims after reclaim runs, or the claim clears

crates/picloud/tests/invoke_e2e.rs (4 tests):
  - invoke_by_name_same_app_returns_value: callee returns body.x+1;
    caller invokes by name and writes the result to KV (42 round-trips)
  - invoke_cross_app_rejects: callee in app_B, caller in app_A; error
    string contains "different app" or "CrossApp"
  - invoke_depth_limit_exceeds_cleanly: recursive script throws with
    "depth" in the message at the bound (Limits::trigger_depth_max=8)
  - invoke_async_enqueues_outbox_row: invoke_async returns execution_id,
    dispatcher fires the OutboxSourceKind::Invoke arm, callee marker
    appears

crates/picloud/tests/retry_e2e.rs (3 tests):
  - retry_run_eventually_succeeds_inside_http_handler: counter mutates
    across 3 retries through a real HTTP route, returns 3
  - retry_run_surfaces_last_error_after_max_attempts: max_attempts=2,
    always throws — caller's try/catch surfaces "boom"
  - retry_on_codes_filters_unmatched_errors: counter == 1 after a
    throw NOT in the codes list (immediate surface, no retry)

crates/manager-core/tests/migration_queue_messages.rs (4 tests):
  - queue_messages_table_exists_with_expected_columns: shape +
    nullability of every column
  - queue_trigger_details_table_exists: shape
  - queue_widens_trigger_kind_and_outbox_source_kind: triggers.kind
    CHECK admits 'queue'; outbox.source_kind admits 'invoke'
  - queue_messages_dispatch_index_is_partial: idx_queue_messages_dispatch
    has WHERE claim_token IS NULL (guards against future migrations
    accidentally dropping the partial)

All 15 tests pass clean skip when DATABASE_URL is unset. Workspace unit
suite remains at 432 passing (306 manager-core + 74 executor-core + 34
shared + 18 orchestrator-core).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-07 10:25:22 +02:00

176 lines
5.7 KiB
Rust

//! v1.1.9 retry::* end-to-end test against a real engine inside the
//! all-in-one binary. Smaller surface than queue/invoke (no async
//! plumbing) — covers policy clamping, success-on-Nth-attempt, and
//! on_codes filtering through a real HTTP route.
//!
//! Skips when DATABASE_URL is unset.
#![allow(clippy::needless_pass_by_value)]
use axum_test::TestServer;
use serde_json::{json, Value};
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use uuid::Uuid;
async fn pool_or_skip() -> Option<PgPool> {
let Ok(url) = std::env::var("DATABASE_URL") else {
eprintln!("retry_e2e: DATABASE_URL unset — skipping");
return None;
};
let pool = PgPoolOptions::new()
.max_connections(2)
.connect(&url)
.await
.expect("connect");
sqlx::migrate!("../manager-core/migrations")
.run(&pool)
.await
.expect("migrate");
Some(pool)
}
async fn server_for(pool: PgPool, suffix: &str) -> (TestServer, String) {
use picloud_manager_core::auth::hash_password;
use picloud_shared::InstanceRole;
let unique = format!("{suffix}-{}", Uuid::new_v4().simple());
let auth = picloud::AuthDeps::from_pool(pool.clone());
let username = format!("e2e-{unique}");
let hash = hash_password("pw").expect("hash");
auth.users
.create(&username, &hash, InstanceRole::Owner, None)
.await
.expect("seed admin");
let app = picloud::build_app(
pool,
auth,
picloud_shared::MasterKey::from_bytes([0x42u8; 32]),
)
.await
.expect("build_app");
let mut server = TestServer::new(app).expect("TestServer");
let resp = server
.post("/api/v1/admin/auth/login")
.json(&json!({ "username": username, "password": "pw" }))
.await;
resp.assert_status_ok();
let token = resp.json::<Value>()["token"]
.as_str()
.expect("token")
.to_string();
server.add_header("authorization", format!("Bearer {token}"));
let slug = format!("e2e-{unique}");
let created: Value = server
.post("/api/v1/admin/apps")
.json(&json!({ "slug": slug, "name": slug }))
.await
.json();
let app_id = created["id"].as_str().expect("app id").to_string();
(server, app_id)
}
async fn create_route_for(
server: &TestServer,
app_id: &str,
name: &str,
source: &str,
path: &str,
) {
let created: Value = server
.post("/api/v1/admin/scripts")
.json(&json!({ "app_id": app_id, "name": name, "source": source }))
.await
.json();
let script_id = created["id"].as_str().expect("script id");
let resp = server
.post(&format!("/api/v1/admin/apps/{app_id}/routes"))
.json(&json!({
"script_id": script_id,
"method": "GET",
"path": path,
"host": null,
"dispatch_mode": "sync"
}))
.await;
resp.assert_status(axum::http::StatusCode::CREATED);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn retry_run_eventually_succeeds_inside_http_handler() {
let Some(pool) = pool_or_skip().await else { return };
let (server, app_id) = server_for(pool, "retry-succ").await;
// attempt counter mutates across retries; the 3rd attempt returns
// the count.
let src = r#"
let attempts = 0;
let p = retry::policy(#{ max_attempts: 5, base_ms: 1, jitter_pct: 0 });
let v = retry::run(p, || {
attempts += 1;
if attempts < 3 { throw "transient" } else { attempts }
});
#{ statusCode: 200, body: v }
"#;
create_route_for(&server, &app_id, "succ", src, "/r/succ").await;
let resp = server.get("/r/succ").await;
resp.assert_status_ok();
let body: Value = resp.json();
assert_eq!(body, json!(3));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn retry_run_surfaces_last_error_after_max_attempts() {
let Some(pool) = pool_or_skip().await else { return };
let (server, app_id) = server_for(pool, "retry-surf").await;
let src = r#"
let p = retry::policy(#{ max_attempts: 2, base_ms: 1, jitter_pct: 0 });
try {
retry::run(p, || { throw "boom" });
#{ statusCode: 200, body: "did not throw" }
} catch(e) {
#{ statusCode: 200, body: e }
}
"#;
create_route_for(&server, &app_id, "surf", src, "/r/surf").await;
let resp = server.get("/r/surf").await;
resp.assert_status_ok();
let body: Value = resp.json();
let s = body.as_str().unwrap_or_default();
assert!(s.contains("boom"), "expected 'boom' in error, got: {s}");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn retry_on_codes_filters_unmatched_errors() {
let Some(pool) = pool_or_skip().await else { return };
let (server, app_id) = server_for(pool, "retry-codes").await;
// attempts is mutated on every entry; we throw a non-matching code
// → must surface immediately (attempts == 1).
let src = r#"
let attempts = 0;
let p = retry::policy(#{ max_attempts: 5, base_ms: 1, jitter_pct: 0 });
let p2 = retry::on_codes(p, ["http: 503"]);
try {
retry::run(p2, || {
attempts += 1;
throw "other failure"
});
} catch(_e) {
// swallow — assert via attempts count.
}
#{ statusCode: 200, body: attempts }
"#;
create_route_for(&server, &app_id, "codes", src, "/r/codes").await;
let resp = server.get("/r/codes").await;
resp.assert_status_ok();
let body: Value = resp.json();
assert_eq!(body, json!(1), "non-matching error should surface immediately");
}