fix(review): close 5 follow-up gaps from Stage 6 audit re-review

- F-T-003 actually closed: clients/typescript/src/subscribe.ts now
  bounds the 401-refresh loop at 3 consecutive refusals, surfaces an
  onError describing the loop, and resets on any successful stream
  open. New test covers the cap. The Stage 2 dashboard fix only
  addressed adminRequest in dashboard/src/lib/api.ts; the originally-
  cited TS client file was untouched.

- users/invitations subtab dropped the redundant api.apps.get fetch
  the other 5 subtabs already shed in Stage 6.

- Queue visibility-timeout validator pulled out as
  validate_queue_visibility_timeout, with two thresholds: hard-reject
  below MIN_QUEUE_VISIBILITY_TIMEOUT_SECS (30s — catches typos), warn-
  log between MIN and SAFE_VISIBILITY_VS_EXEC_BUDGET_SECS (300s) so
  operators see when their visibility is below the dispatcher's
  per-message executor budget. Stage 6 only had the hard floor; the
  reviewer caught that a 60s handler still races a 30s visibility
  even after the floor. Four new unit tests cover none/above-safe/
  between/below-min.

- pic dead-letters count subcommand: cheap headless probe for
  unresolved DL totals, parallels the dashboard's badge query.

- pic dead-letters replay now has a happy-path integration test
  (replay_against_real_dl_row_succeeds): inserts a synthetic DL row
  directly via the rust-postgres sync driver (added as dev-dep),
  drives `pic dead-letters replay`, asserts the row is resolved with
  reason=replayed and count drops back to 0. Plus a count smoke test.

All 75 CLI integration tests + 16 TS client tests + 4 new
visibility-timeout unit tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-06-11 17:20:34 +02:00
parent 05ed9b00bb
commit b0f7b72dd6
10 changed files with 628 additions and 77 deletions

View File

@@ -40,3 +40,9 @@ predicates = "3"
tempfile = "3"
reqwest = { workspace = true, features = ["json", "blocking"] }
libc = "0.2"
# Synchronous Postgres driver used by the dead-letters integration test
# to inject a row the replay path can act on. Smaller compile cost than
# pulling sqlx into the CLI tree, and the existing tests are
# blocking-style anyway.
postgres = { version = "0.19", features = ["with-uuid-1", "with-serde_json-1"] }
uuid = { version = "1", features = ["v4"] }

View File

@@ -399,6 +399,18 @@ impl Client {
decode(resp).await
}
/// `GET /api/v1/admin/apps/{id}/dead_letters/count`
pub async fn dead_letters_count(&self, app: &str) -> Result<DeadLetterCountDto> {
let resp = self
.request(
Method::GET,
&format!("/api/v1/admin/apps/{app}/dead_letters/count"),
)
.send()
.await?;
decode(resp).await
}
/// `GET /api/v1/admin/apps/{id}/dead_letters?unresolved={bool}&limit={n}`
pub async fn dead_letters_list(
&self,
@@ -647,6 +659,11 @@ pub struct TriggerDto {
pub details: Value,
}
#[derive(Debug, Deserialize)]
pub struct DeadLetterCountDto {
pub unresolved: i64,
}
#[derive(Debug, Deserialize)]
pub struct DeadLetterListDto {
pub dead_letters: Vec<DeadLetterDto>,

View File

@@ -6,6 +6,18 @@ use crate::client::Client;
use crate::config;
use crate::output::{KvBlock, OutputMode, Table};
/// `pic dead-letters count --app <slug>` — print the unresolved DL
/// count for an app. Useful for headless probes (alerting / dashboards).
pub async fn count(app: &str, mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;
let resp = client.dead_letters_count(app).await?;
let mut table = Table::new(["unresolved"]);
table.row([resp.unresolved.to_string()]);
table.print(mode);
Ok(())
}
pub async fn ls(app: &str, unresolved: bool, limit: u32, mode: OutputMode) -> Result<()> {
let creds = config::resolve()?;
let client = Client::from_creds(&creds)?;

View File

@@ -466,6 +466,13 @@ enum TriggersCmd {
#[derive(Subcommand)]
enum DeadLettersCmd {
/// Print the unresolved DL count. Cheap probe for alerting /
/// dashboards — no row payloads, just the bare integer.
Count {
#[arg(long)]
app: String,
},
/// List dead-letter rows for an app.
Ls {
#[arg(long)]
@@ -822,6 +829,9 @@ async fn main() -> ExitCode {
Cmd::Triggers {
cmd: TriggersCmd::CreateFromJson { app, kind, body },
} => cmds::triggers::create_from_json(&app, &kind, &body, mode).await,
Cmd::DeadLetters {
cmd: DeadLettersCmd::Count { app },
} => cmds::dead_letters::count(&app, mode).await,
Cmd::DeadLetters {
cmd:
DeadLettersCmd::Ls {

View File

@@ -46,6 +46,136 @@ fn ls_empty_app_succeeds() {
assert_eq!(stdout.lines().count(), 1, "fresh app has no DL rows");
}
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn count_returns_unresolved_total() {
let Some(fx) = common::fixture_or_skip() else {
return;
};
let env = common::admin_env(fx);
let slug = common::unique_slug("dl-count");
common::pic_as(&env)
.args(["apps", "create", &slug])
.assert()
.success();
let _guard = AppGuard::new(&env.url, &env.token, &slug);
let out = common::pic_as(&env)
.args(["dead-letters", "count", "--app", &slug])
.output()
.expect("dl count");
assert!(out.status.success(), "count failed: {out:?}");
let stdout = String::from_utf8(out.stdout).unwrap();
let header = stdout.lines().next().expect("header");
assert_eq!(common::cells(header), vec!["unresolved"]);
let row = stdout.lines().nth(1).expect("data row");
assert_eq!(common::cells(row), vec!["0"]);
}
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn replay_against_real_dl_row_succeeds() {
use postgres::{Client as PgClient, NoTls};
use uuid::Uuid;
let Some(fx) = common::fixture_or_skip() else {
return;
};
let env = common::admin_env(fx);
let (script_id_str, guard) = common::deploy_fixture(&env, "dl-replay", "hello.rhai");
let app_slug = guard.slug().to_string();
// Need the app's UUID to inject the DL row. Resolve via the admin
// GET — picloud accepts either slug or id, returns both.
let app_id: String = reqwest::blocking::Client::new()
.get(format!("{}/api/v1/admin/apps/{}", env.url, app_slug))
.bearer_auth(&env.token)
.send()
.expect("apps_get")
.json::<serde_json::Value>()
.expect("apps_get json")["id"]
.as_str()
.expect("app id")
.to_string();
// Direct INSERT — no admin endpoint creates DL rows; the real ones
// come from the dispatcher's retry-exhaust path, which would take
// minutes to drive. The replay path doesn't care how the row got
// there, only that it exists, belongs to this app, and is
// unresolved.
let db_url =
std::env::var("DATABASE_URL").expect("DATABASE_URL required for replay happy-path test");
let mut pg = PgClient::connect(&db_url, NoTls).expect("postgres connect");
let dl_id = Uuid::new_v4();
let app_uuid = Uuid::parse_str(&app_id).expect("app uuid");
let script_uuid = Uuid::parse_str(&script_id_str).expect("script uuid");
// Payload shape must round-trip through the dispatcher: source="kv"
// matches a KV TriggerEvent, op="set" is a KvEventOp, and the
// service_kind=`kv` outbox row gets routed by resolve_trigger.
let payload = serde_json::json!({
"source": "kv",
"op": "set",
"kv": {
"collection": "x",
"key": "y",
"value": { "v": 1 }
}
});
pg.execute(
"INSERT INTO dead_letters (
id, app_id, original_event_id, source, op, trigger_id, script_id,
payload, attempt_count, first_attempt_at, last_attempt_at, last_error
) VALUES ($1, $2, $3, 'kv', 'set', NULL, $4, $5, 1, NOW(), NOW(), 'forced')",
&[&dl_id, &app_uuid, &Uuid::new_v4(), &script_uuid, &payload],
)
.expect("insert synthetic DL row");
// Verify CLI count picks the row up.
let out = common::pic_as(&env)
.args(["dead-letters", "count", "--app", &app_slug])
.output()
.expect("dl count");
let stdout = String::from_utf8(out.stdout).unwrap();
assert!(
stdout.lines().nth(1) == Some("1"),
"count should be 1: {stdout}"
);
// Replay — pic exits 0, the server resolves the row with reason=replayed.
common::pic_as(&env)
.args([
"dead-letters",
"replay",
"--app",
&app_slug,
&dl_id.to_string(),
])
.assert()
.success()
.stdout(predicate::str::contains("Replayed dead-letter"));
// Verify the row is now resolved with reason=replayed.
let row = pg
.query_one(
"SELECT resolution FROM dead_letters WHERE id = $1",
&[&dl_id],
)
.expect("dl row exists post-replay");
let resolution: Option<String> = row.get(0);
assert_eq!(resolution.as_deref(), Some("replayed"));
// And the unresolved count drops back to 0.
let out = common::pic_as(&env)
.args(["dead-letters", "count", "--app", &app_slug])
.output()
.expect("dl count");
let stdout = String::from_utf8(out.stdout).unwrap();
assert!(
stdout.lines().nth(1) == Some("0"),
"count should be 0 after replay: {stdout}"
);
}
#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn resolve_marks_row_resolved() {