Skip to content

Commit eae6948

Browse files
browstudio
andauthored
fix(push-gateway): retry, don't drop, a delivery replayed while its first attempt is in flight (#9802)
The relay gives up on a push gateway delivery call after 2 seconds and retries the same `request_id` with a fresh NIP-98 event. A gateway send can take much longer than that: an FCM token mint has a 15 second deadline, and the APNs and FCM sends each have a 15 second timeout. A retry that arrived while the first attempt was still sending hit the request replay fence and got `404 invalid_grant`. The relay reads a 404 on a retry as "the earlier attempt already finished" and completes the wake. If the first attempt then failed retryably, nothing ever sent the wake, and the notification was silently lost. This change makes the gateway tell an in-flight request apart from a finished one: - Admission records the request id as in flight. A terminal outcome marks it finished, and a retryable outcome releases it, as before. - A replay of an in-flight id now gets `503 {"status":"retry","retry_after_seconds":5}`. Nothing is sent and no quota is charged, so the relay's existing 503 path retries with backoff. - A replay of a finished id still gets 404, so the relay's existing handling of a finished attempt is unchanged. Postgres gets a `finished` column on `push_gateway_delivery_request_replays` (gateway migration 0009, mirrored in relay migration 0105). It defaults to `true`, and the gateway writes `false` explicitly on admission. Rows written before this migration, or by an older gateway during a rollout or rollback, therefore keep today's behavior. The constant default adds the column without rewriting the table. ### Validation - [`replay_while_first_attempt_is_in_flight_is_retried_not_dropped`](https://github.com/block/buzz/blob/3deaefb2b8f550484c8f15f8910e00d422c6f83e/crates/buzz-push-gateway/src/http_delivery_tests.rs) holds a first send open in the transport. It checks that a retry of the same request gets 503 retry without sending, that the first attempt's retryable failure releases the id so the next retry sends, and that a finished id still answers 404. - [`replay_of_unfinished_request_is_in_flight_until_it_finishes`](https://github.com/block/buzz/blob/3deaefb2b8f550484c8f15f8910e00d422c6f83e/crates/buzz-push-gateway/src/authority.rs) covers the in-memory store, and [`unfinished_request_replay_is_in_flight_on_real_postgres`](https://github.com/block/buzz/blob/3deaefb2b8f550484c8f15f8910e00d422c6f83e/crates/buzz-push-gateway/src/postgres.rs) covers Postgres, including that an in-flight replay charges no quota. - The gateway's Postgres suite, including the desired-state schema parity test, ran against a local PostgreSQL 17. ### Regressions - A gateway that crashes mid-send now leaves the request id in flight until the request expires, so the relay keeps retrying until its attempt limit (8 attempts, about 10.5 minutes) or the request expiry, whichever comes first. Before this change it got a 404 and dropped the wake. - Admission now runs one more indexed primary-key read inside the transaction that already locks the installation row. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
1 parent 7681371 commit eae6948

13 files changed

Lines changed: 512 additions & 39 deletions

File tree

‎crates/buzz-db/src/runtime/migration.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -879,7 +879,10 @@ mod postgres_tests {
879879
let mut migrations: Vec<_> = MIGRATOR.iter().collect();
880880
migrations.sort_by_key(|migration| migration.version);
881881

882-
assert_eq!(migrations.len(), 104);
882+
assert_eq!(migrations.len(), 105);
883+
assert_eq!(migrations[104].version, 105);
884+
assert!(strip_sql_comments(migrations[104].sql.as_str())
885+
.contains("ADD COLUMN finished BOOLEAN NOT NULL DEFAULT true;"));
883886
assert_eq!(migrations[103].version, 104);
884887
let event_table_drops = strip_sql_comments(migrations[103].sql.as_str());
885888
assert!(event_table_drops
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
-- Tell a replay of a request id that is still being delivered apart from one
2+
-- whose delivery finished. The gateway inserts new request ids with
3+
-- finished=false and sets it true on a terminal outcome; a replay of an
4+
-- unfinished id answers 503 retry instead of 404, so the relay retries rather
5+
-- than treating its own timed-out first attempt as delivered. Existing rows
6+
-- and rows written by an older gateway default to finished, which keeps the
7+
-- old 404 behavior for them. A constant default adds the column without a
8+
-- table rewrite.
9+
SET LOCAL lock_timeout = '5s';
10+
ALTER TABLE push_gateway_delivery_request_replays
11+
ADD COLUMN finished BOOLEAN NOT NULL DEFAULT true;

‎crates/buzz-push-gateway/schema/tables/public/push_gateway_delivery_request_replays.sql‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
-- Replay ledger for relay delivery request ids, retained until expiry.
2+
-- finished is false while the admitted attempt is still being delivered.
23
CREATE TABLE push_gateway_delivery_request_replays (
34
relay_pubkey BYTEA NOT NULL CHECK (length(relay_pubkey) = 32),
45
request_id UUID NOT NULL,
56
expires_at TIMESTAMPTZ NOT NULL,
7+
finished BOOLEAN NOT NULL DEFAULT true,
68
PRIMARY KEY (relay_pubkey, request_id)
79
);
810

‎crates/buzz-push-gateway/src/authority.rs‎

Lines changed: 51 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,11 @@ pub enum AuthorityError {
139139
RateLimited,
140140
#[error("authority store unavailable")]
141141
Unavailable,
142+
/// The request id was admitted by an attempt that has not finished yet.
143+
/// The caller should retry later: the first attempt may still fail
144+
/// retryably and release the id.
145+
#[error("delivery request is still in flight")]
146+
InFlight,
142147
}
143148

144149
/// Every mutating method is an atomic store operation. Implementations must
@@ -225,8 +230,12 @@ pub trait AuthorityStore: Send + Sync {
225230
quota_max_deliveries: i64,
226231
now: i64,
227232
) -> Result<DeliveryPermit, AuthorityError>;
228-
/// Retain terminal request ids; release retryable request ids while always
229-
/// retaining the one-use auth event admitted by `authorize_delivery`.
233+
/// Admission records the request id as in flight. A replay of it fails
234+
/// with `InFlight` until this call settles it: terminal outcomes retain the
235+
/// id as finished (later replays are `Rejected`), retryable outcomes
236+
/// release it. The one-use auth event admitted by `authorize_delivery` is
237+
/// always retained. If the gateway dies before finishing, the id stays in
238+
/// flight until its request expires, so the relay keeps retrying until then.
230239
async fn finish_delivery(
231240
&self,
232241
permit: DeliveryPermit,
@@ -244,7 +253,8 @@ struct MemoryState {
244253
delegations: HashMap<(Uuid, String), Delegation>,
245254
delegation_ids: HashMap<Uuid, (Uuid, String)>,
246255
delivery_auth_replays: HashMap<(String, String), i64>,
247-
delivery_request_replays: HashMap<(String, Uuid), i64>,
256+
/// Request id to (expires_at, finished).
257+
delivery_request_replays: HashMap<(String, Uuid), (i64, bool)>,
248258
endpoint_quotas: HashMap<[u8; 32], (i64, i64)>,
249259
}
250260

@@ -596,9 +606,12 @@ impl AuthorityStore for MemoryAuthorityStore {
596606
let fingerprint = i.token_fingerprint;
597607
let auth_key = (relay.to_owned(), event_id.to_owned());
598608
let request_key = (relay.to_owned(), request_id);
599-
if s.delivery_auth_replays.contains_key(&auth_key)
600-
|| s.delivery_request_replays.contains_key(&request_key)
601-
{
609+
match s.delivery_request_replays.get(&request_key) {
610+
Some((_, false)) => return Err(AuthorityError::InFlight),
611+
Some((_, true)) => return Err(AuthorityError::Rejected),
612+
None => {}
613+
}
614+
if s.delivery_auth_replays.contains_key(&auth_key) {
602615
return Err(AuthorityError::Rejected);
603616
}
604617
let quota = s.endpoint_quotas.entry(fingerprint).or_insert((now, 0));
@@ -611,7 +624,7 @@ impl AuthorityStore for MemoryAuthorityStore {
611624
quota.1 += 1;
612625
s.delivery_auth_replays.insert(auth_key, request_expires_at);
613626
s.delivery_request_replays
614-
.insert(request_key, request_expires_at);
627+
.insert(request_key, (request_expires_at, false));
615628
Ok(DeliveryPermit::new(authority, relay.to_owned(), request_id))
616629
}
617630

@@ -620,12 +633,17 @@ impl AuthorityStore for MemoryAuthorityStore {
620633
permit: DeliveryPermit,
621634
disposition: DeliveryDisposition,
622635
) -> Result<(), AuthorityError> {
623-
if disposition == DeliveryDisposition::Retryable {
624-
self.0
625-
.lock()
626-
.map_err(|_| AuthorityError::Unavailable)?
627-
.delivery_request_replays
628-
.remove(&(permit.relay_pubkey, permit.request_id));
636+
let mut s = self.0.lock().map_err(|_| AuthorityError::Unavailable)?;
637+
let key = (permit.relay_pubkey, permit.request_id);
638+
match disposition {
639+
DeliveryDisposition::Retryable => {
640+
s.delivery_request_replays.remove(&key);
641+
}
642+
DeliveryDisposition::Terminal => {
643+
if let Some((_, finished)) = s.delivery_request_replays.get_mut(&key) {
644+
*finished = true;
645+
}
646+
}
629647
}
630648
Ok(())
631649
}
@@ -637,7 +655,7 @@ impl AuthorityStore for MemoryAuthorityStore {
637655
s.delivery_auth_replays
638656
.retain(|_, expires_at| *expires_at >= now);
639657
s.delivery_request_replays
640-
.retain(|_, expires_at| *expires_at >= now);
658+
.retain(|_, (expires_at, _)| *expires_at >= now);
641659
s.endpoint_quotas
642660
.retain(|_, (started_at, _)| now.saturating_sub(*started_at) < 86_400);
643661
Ok(())
@@ -870,6 +888,25 @@ mod tests {
870888
.expect("fresh auth event may retry stable request id");
871889
}
872890

891+
#[tokio::test]
892+
async fn replay_of_unfinished_request_is_in_flight_until_it_finishes() {
893+
let store = store().await;
894+
let request = Uuid::new_v4();
895+
let permit = admitted(&store, &"22".repeat(32), request).await.unwrap();
896+
assert_eq!(
897+
admitted(&store, &"33".repeat(32), request).await.err(),
898+
Some(AuthorityError::InFlight)
899+
);
900+
store
901+
.finish_delivery(permit, DeliveryDisposition::Terminal)
902+
.await
903+
.unwrap();
904+
assert_eq!(
905+
admitted(&store, &"44".repeat(32), request).await.err(),
906+
Some(AuthorityError::Rejected)
907+
);
908+
}
909+
873910
#[tokio::test]
874911
async fn terminal_outcome_burns_request_id() {
875912
let store = store().await;

‎crates/buzz-push-gateway/src/http.rs‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ fn authority_error(e: AuthorityError) -> Response {
148148
AuthorityError::Rejected => error(StatusCode::NOT_FOUND, "not_authorized"),
149149
AuthorityError::Conflict => installation_conflict(),
150150
AuthorityError::RateLimited => error(StatusCode::TOO_MANY_REQUESTS, "rate_limited"),
151-
AuthorityError::Unavailable => {
151+
AuthorityError::Unavailable | AuthorityError::InFlight => {
152152
error(StatusCode::SERVICE_UNAVAILABLE, "temporarily_unavailable")
153153
}
154154
}
@@ -248,6 +248,12 @@ struct EnrollTranscript<'a> {
248248
/// Domain of the Android enrollment transcript, which the attestation
249249
/// challenge binds.
250250
const ANDROID_ENROLL_DOMAIN: &str = "buzz.push.enroll.android.v1";
251+
/// How long a relay should wait before retrying a request whose earlier
252+
/// attempt is still in flight. Long enough for a send that is minting or
253+
/// waiting on the push service to finish, short enough to keep wakes prompt.
254+
/// The relay doubles it on each attempt, so its retries land about 4, 14, 34
255+
/// and 74 seconds after the first attempt, not every 5 seconds.
256+
const IN_FLIGHT_RETRY_AFTER_SECONDS: i64 = 5;
251257

252258
/// The Android enrollment transcript: the iOS one without `key_id`, since the
253259
/// key is generated after (and from) this transcript's digest.
@@ -903,6 +909,19 @@ async fn deliver(
903909
crate::metrics::record_delivery_error("temporarily_unavailable");
904910
return error(StatusCode::SERVICE_UNAVAILABLE, "temporarily_unavailable");
905911
}
912+
// The relay gave up waiting on an earlier attempt of this request and
913+
// retried while that attempt is still sending. A 404 here would tell
914+
// the relay the wake was delivered; ask it to retry instead, after the
915+
// first attempt has had time to finish.
916+
Err(AuthorityError::InFlight) => {
917+
crate::metrics::record_admission(crate::metrics::Admission::InFlight);
918+
return delivery_outcome_response(
919+
DeliveryOutcome::Retry {
920+
retry_after_seconds: Some(IN_FLIGHT_RETRY_AFTER_SECONDS),
921+
},
922+
grant.generation,
923+
);
924+
}
906925
};
907926
let platform = permit.authority.platform;
908927
// An Android installation can exist only on a gateway configured for
@@ -956,13 +975,19 @@ async fn deliver(
956975
| DeliveryOutcome::InvalidEndpoint { .. }
957976
| DeliveryOutcome::PermanentRequestFault => DeliveryDisposition::Terminal,
958977
};
959-
authority_store
960-
.finish_delivery(permit, disposition)
961-
.await
962-
.map(|()| outcome)
978+
let finished = authority_store.finish_delivery(permit, disposition).await;
979+
(outcome, disposition, finished)
963980
});
964981
let outcome = match delivery.await {
965-
Ok(Ok(outcome)) => outcome,
982+
Ok((outcome, _, Ok(()))) => outcome,
983+
// The provider has answered for good, so report that answer. The id
984+
// stays in flight until its request expires, which only makes a
985+
// replay retry later; it can never cause a second send.
986+
Ok((outcome, DeliveryDisposition::Terminal, Err(err))) => {
987+
crate::metrics::record_delivery_error("finish_failed");
988+
tracing::warn!(error = %err, "failed to mark a terminal delivery finished");
989+
outcome
990+
}
966991
_ => {
967992
crate::metrics::record_delivery_error("finish_failed");
968993
return error(StatusCode::SERVICE_UNAVAILABLE, "temporarily_unavailable");

0 commit comments

Comments
 (0)