From 93af53c91dc933850fba9739dc44cfa3b10cde0c Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Fri, 17 Mar 2023 00:00:50 +0100 Subject: [PATCH] Prune old Web Push subscriptions --- downstream.go | 2 -- server.go | 1 + user.go | 21 +++++++++++++++++++-- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/downstream.go b/downstream.go index f2135dd..c4f3c82 100644 --- a/downstream.go +++ b/downstream.go @@ -3249,8 +3249,6 @@ func (dc *downstreamConn) handleMessageRegistered(ctx context.Context, msg *irc. }} } - // TODO: limit max number of subscriptions, prune old ones - if err := dc.user.srv.db.StoreWebPushSubscription(ctx, dc.user.ID, networkID, &newSub); err != nil { dc.logger.Printf("failed to store Web push subscription: %v", err) return ircError{&irc.Message{ diff --git a/server.go b/server.go index e7fdefa..f96a5e3 100644 --- a/server.go +++ b/server.go @@ -38,6 +38,7 @@ var backlogTimeout = 10 * time.Second var handleDownstreamMessageTimeout = 10 * time.Second var downstreamRegisterTimeout = 30 * time.Second var webpushCheckSubscriptionDelay = 24 * time.Hour +var webpushPruneSubscriptionDelay = 30 * 24 * time.Hour var chatHistoryLimit = 1000 var backlogLimit = 4000 diff --git a/user.go b/user.go index a619760..b10dc92 100644 --- a/user.go +++ b/user.go @@ -484,7 +484,23 @@ func (net *network) broadcastWebPush(msg *irc.Message) { return } + // First, prune old subscriptions + var active []database.WebPushSubscription for _, sub := range subs { + if time.Since(sub.UpdatedAt) <= webpushPruneSubscriptionDelay { + active = append(active, sub) + continue + } + + if err := net.user.srv.db.DeleteWebPushSubscription(ctx, sub.ID); err != nil { + net.logger.Printf("failed to delete pruned Web Push subscription %q: %v", sub.Endpoint, err) + } else { + net.logger.Debugf("deleted pruned Web Push subscription %q", sub.Endpoint) + } + } + + // Then broadcast the message + for _, sub := range active { err := net.user.srv.sendWebPush(ctx, &webpush.Subscription{ Endpoint: sub.Endpoint, Keys: webpush.Keys{ @@ -494,9 +510,10 @@ func (net *network) broadcastWebPush(msg *irc.Message) { }, sub.Keys.VAPID, msg) if err == errWebPushSubscriptionExpired { if err := net.user.srv.db.DeleteWebPushSubscription(ctx, sub.ID); err != nil { - net.logger.Printf("failed to delete expired Web Push subscription: %v", err) + net.logger.Printf("failed to delete expired Web Push subscription %q: %v", sub.Endpoint, err) + } else { + net.logger.Debugf("deleted expired Web Push subscription %q", sub.Endpoint) } - net.logger.Debugf("deleted expired Web Push subscription %q", sub.Endpoint) } else if err != nil { net.logger.Printf("failed to send Web push notification to endpoint %q: %v", sub.Endpoint, err) }