Webpush: Fix FK issue with Postgres

This commit is contained in:
binwiederhier
2026-03-16 10:24:16 -04:00
parent 6b38acb23a
commit 3a37ea32f7
4 changed files with 8 additions and 3 deletions

View File

@@ -1791,4 +1791,5 @@ and the [ntfy Android app](https://github.com/binwiederhier/ntfy-android/release
**Bug fixes + maintenance:**
* Fix race condition in web push subscription causing FK constraint violation when concurrent requests hit the same endpoint
* Route authorization query to read-only database replica to reduce primary database load

View File

@@ -26,6 +26,7 @@ var (
type Store struct {
db *db.DB
queries queries
}
// queries holds the database-specific SQL queries.
@@ -63,9 +64,10 @@ func (s *Store) UpsertSubscription(endpoint string, auth, p256dh, userID string,
} else if err != nil {
return err
}
// Insert or update subscription
// Insert or update subscription, and read back the actual ID (which may differ from
// the generated one if another request for the same endpoint raced us and inserted first)
updatedAt, warnedAt := time.Now().Unix(), 0
if _, err := tx.Exec(s.queries.upsertSubscription, subscriptionID, endpoint, auth, p256dh, userID, subscriberIP.String(), updatedAt, warnedAt); err != nil {
if err := tx.QueryRow(s.queries.upsertSubscription, subscriptionID, endpoint, auth, p256dh, userID, subscriberIP.String(), updatedAt, warnedAt).Scan(&subscriptionID); err != nil {
return err
}
// Replace all subscription topics

View File

@@ -53,6 +53,7 @@ const (
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (endpoint)
DO UPDATE SET key_auth = excluded.key_auth, key_p256dh = excluded.key_p256dh, user_id = excluded.user_id, subscriber_ip = excluded.subscriber_ip, updated_at = excluded.updated_at, warned_at = excluded.warned_at
RETURNING id
`
postgresUpdateSubscriptionWarningSentQuery = `UPDATE webpush_subscription SET warned_at = $1 WHERE id = $2`
postgresUpdateSubscriptionUpdatedAtQuery = `UPDATE webpush_subscription SET updated_at = $1 WHERE endpoint = $2`

View File

@@ -58,6 +58,7 @@ const (
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (endpoint)
DO UPDATE SET key_auth = excluded.key_auth, key_p256dh = excluded.key_p256dh, user_id = excluded.user_id, subscriber_ip = excluded.subscriber_ip, updated_at = excluded.updated_at, warned_at = excluded.warned_at
RETURNING id
`
sqliteUpdateSubscriptionWarningSentQuery = `UPDATE subscription SET warned_at = ? WHERE id = ?`
sqliteUpdateSubscriptionUpdatedAtQuery = `UPDATE subscription SET updated_at = ? WHERE endpoint = ?`