skip deleted users when cleaning up expired push subscriptions

Cleaning up expired push subscriptions raised DoesNotExist when the user had been deleted, so the expired list never reset, other users' dead endpoints were never pruned, and every later alert logged a traceback until restart. Cleanup now skips missing users and malformed stored tokens, and swaps the expired list out under a lock shared with the sender thread so the two no longer race.
This commit is contained in:
Josh Hawkins
2026-11-24 08:21:09 -06:00
parent f45fae1ef5
commit 758b2c96e1
2 changed files with 73 additions and 21 deletions
+28 -21
View File
@@ -180,6 +180,7 @@ class WebPushClient(Communicator):
self.refresh: int = 0 self.refresh: int = 0
self.web_pushers: dict[str, list[WebPusher]] = {} self.web_pushers: dict[str, list[WebPusher]] = {}
self.expired_subs: dict[str, list[str]] = {} self.expired_subs: dict[str, list[str]] = {}
self.expired_subs_lock = threading.Lock()
self.suspended_cameras: dict[str, int] = { self.suspended_cameras: dict[str, int] = {
c.name: 0 # type: ignore[misc] c.name: 0 # type: ignore[misc]
for c in self.config.cameras.values() for c in self.config.cameras.values()
@@ -261,30 +262,35 @@ class WebPushClient(Communicator):
def cleanup_registrations(self) -> None: def cleanup_registrations(self) -> None:
# delete any expired subs # delete any expired subs
if len(self.expired_subs) > 0: with self.expired_subs_lock:
for user, expired in self.expired_subs.items(): expired_subs, self.expired_subs = self.expired_subs, {}
user_subs = []
# get all subscriptions, removing ones that are expired for user, expired in expired_subs.items():
stored_user: User = User.get_by_id(user) user_subs = []
for token in stored_user.notification_tokens:
if token["endpoint"] in expired:
continue
user_subs.append(token) # get all subscriptions, removing ones that are expired
stored_user: User | None = User.get_or_none(User.username == user)
# overwrite the database and reset web pushers # the user was deleted after the endpoint expired
User.update(notification_tokens=user_subs).where( if stored_user is None:
User.username == user continue
).execute()
self.web_pushers[user] = _build_web_pushers(user, user_subs) for token in stored_user.notification_tokens:
if isinstance(token, dict) and token.get("endpoint") in expired:
continue
logger.info( user_subs.append(token)
f"Cleaned up {len(expired)} notification subscriptions for {user}"
)
self.expired_subs = {} # overwrite the database and reset web pushers
User.update(notification_tokens=user_subs).where(
User.username == user
).execute()
self.web_pushers[user] = _build_web_pushers(user, user_subs)
logger.info(
f"Cleaned up {len(expired)} notification subscriptions for {user}"
)
def suspend_notifications(self, camera: str, minutes: int) -> None: def suspend_notifications(self, camera: str, minutes: int) -> None:
"""Suspend notifications for a specific camera.""" """Suspend notifications for a specific camera."""
@@ -460,9 +466,10 @@ class WebPushClient(Communicator):
) )
if resp.status_code in (404, 410): if resp.status_code in (404, 410):
self.expired_subs.setdefault(notification.user, []).append( with self.expired_subs_lock:
endpoint self.expired_subs.setdefault(notification.user, []).append(
) endpoint
)
logger.debug( logger.debug(
f"Notification endpoint expired for {notification.user}, received {resp.status_code}" f"Notification endpoint expired for {notification.user}, received {resp.status_code}"
) )
+45
View File
@@ -0,0 +1,45 @@
"""Tests for expired push subscription cleanup."""
import threading
import unittest
from unittest.mock import patch
from peewee import SqliteDatabase
from frigate.comms.webpush import WebPushClient
from frigate.models import User
LIVE = {"endpoint": "https://push.example.com/live", "keys": {}}
DEAD = {"endpoint": "https://push.example.com/dead", "keys": {}}
class TestCleanupRegistrations(unittest.TestCase):
def setUp(self):
self.db = SqliteDatabase(":memory:")
self.db.bind([User])
self.db.create_tables([User])
User.create(
username="alice", password_hash="x", notification_tokens=[LIVE, DEAD]
)
self.client = WebPushClient.__new__(WebPushClient)
self.client.web_pushers = {}
self.client.expired_subs = {}
self.client.expired_subs_lock = threading.Lock()
def tearDown(self):
self.db.close()
@patch("frigate.comms.webpush._build_web_pushers", return_value=[])
def test_skips_deleted_user_and_prunes_the_rest(self, _build):
self.client.expired_subs = {
"deleted": ["https://push.example.com/gone"],
"alice": [DEAD["endpoint"]],
}
self.client.cleanup_registrations()
self.assertEqual(User.get_by_id("alice").notification_tokens, [LIVE])
self.assertEqual(self.client.expired_subs, {})
_build.assert_called_once_with("alice", [LIVE])