Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Prune unregistered FCM tokens

Manav Rathie969e3863101
diff --git a/server/pkg/controller/push.go b/server/pkg/controller/push.go
index e67b67da37..5c901b519e 100644
--- a/server/pkg/controller/push.go
+++ b/server/pkg/controller/push.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
@@ -176,6 +177,8 @@ func (c *PushController) sendFCMPushes(pushTokens []ente.PushToken, payload map[
log.Info("Sending pushes to " + strconv.Itoa(len(pushTokens)) + " devices")
var successCount, failureCount int64
var lastErr atomic.Value
+ var staleMu sync.Mutex
+ var staleTokens []string
var wg sync.WaitGroup
sem := make(chan struct{}, fcmSendConcurrency)
for _, pushToken := range pushTokens {
@@ -187,6 +190,11 @@ func (c *PushController) sendFCMPushes(pushTokens []ente.PushToken, payload map[
if err := c.fcm.send(context.Background(), token, payload); err != nil {
atomic.AddInt64(&failureCount, 1)
lastErr.Store(err.Error())
+ if errors.Is(err, errStaleToken) {
+ staleMu.Lock()
+ staleTokens = append(staleTokens, token)
+ staleMu.Unlock()
+ }
} else {
atomic.AddInt64(&successCount, 1)
}
@@ -202,9 +210,22 @@ func (c *PushController) sendFCMPushes(pushTokens []ente.PushToken, payload map[
log.Info("Send push result: success count: " + strconv.FormatInt(successCount, 10) +
", failure count: " + strconv.FormatInt(failureCount, 10))
}
+
+ c.pruneStaleTokens(staleTokens)
return nil
}
+func (c *PushController) pruneStaleTokens(fcmTokens []string) {
+ if len(fcmTokens) == 0 {
+ return
+ }
+ if err := c.PushRepo.RemoveTokensByFCM(fcmTokens); err != nil {
+ log.Error(fmt.Errorf("error pruning %d stale FCM tokens: %w", len(fcmTokens), err))
+ return
+ }
+ log.Info("Pruned " + strconv.Itoa(len(fcmTokens)) + " stale FCM tokens")
+}
+
func (c *fcmClient) send(ctx context.Context, token string, data map[string]string) error {
body, err := json.Marshal(map[string]any{
"message": map[string]any{
@@ -237,7 +258,34 @@ func (c *fcmClient) send(ctx context.Context, token string, data map[string]stri
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
+ if fcmErrorCode(b) == "UNREGISTERED" {
+ return fmt.Errorf("%w (status %d)", errStaleToken, resp.StatusCode)
+ }
return fmt.Errorf("status %d: %s", resp.StatusCode, string(b))
}
return nil
}
+
+// errStaleToken marks a token FCM rejected as permanently invalid
+// (UNREGISTERED) β€” the only signal we prune on. Notably not INVALID_ARGUMENT,
+// which a bad message on our side would also raise for every token.
+var errStaleToken = errors.New("fcm: unregistered token")
+
+func fcmErrorCode(body []byte) string {
+ var e struct {
+ Error struct {
+ Details []struct {
+ ErrorCode string `json:"errorCode"`
+ } `json:"details"`
+ } `json:"error"`
+ }
+ if json.Unmarshal(body, &e) != nil {
+ return ""
+ }
+ for _, d := range e.Error.Details {
+ if d.ErrorCode != "" {
+ return d.ErrorCode
+ }
+ }
+ return ""
+}
diff --git a/server/pkg/controller/push_test.go b/server/pkg/controller/push_test.go
index ddbe06df44..c245e38a79 100644
--- a/server/pkg/controller/push_test.go
+++ b/server/pkg/controller/push_test.go
@@ -3,6 +3,7 @@ package controller
import (
"context"
"encoding/json"
+ "errors"
"io"
"net/http"
"strings"
@@ -132,6 +133,44 @@ func TestSendFCMPushesTotalFailureLogsError(t *testing.T) {
require.True(t, hasLog(hook, log.ErrorLevel, "Failed to send any pushes to 2 devices"))
}
+const fcmUnregisteredBody = `{"error":{"code":404,"status":"NOT_FOUND","message":"Requested entity was not found.","details":[{"@type":"type.googleapis.com/google.firebase.fcm.v1.FcmError","errorCode":"UNREGISTERED"}]}}`
+
+const fcmInvalidArgumentBody = `{"error":{"code":400,"status":"INVALID_ARGUMENT","message":"The registration token is not a valid FCM registration token","details":[{"@type":"type.googleapis.com/google.firebase.fcm.v1.FcmError","errorCode":"INVALID_ARGUMENT"},{"@type":"type.googleapis.com/google.rpc.BadRequest","fieldViolations":[{"field":"message.token","description":"The registration token is not a valid FCM registration token"}]}]}}`
+
+func TestFCMSendClassifiesUnregisteredAsStale(t *testing.T) {
+ c := &fcmClient{
+ projectID: "p",
+ httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ return jsonResponse(http.StatusNotFound, fcmUnregisteredBody), nil
+ })},
+ }
+ err := c.send(context.Background(), "tok", map[string]string{"action": "sync"})
+ require.Error(t, err)
+ require.True(t, errors.Is(err, errStaleToken))
+}
+
+// A bad message on our side raises INVALID_ARGUMENT for every token; pruning on
+// it would wipe the table on a bad deploy, so it must not be treated as stale.
+func TestFCMSendDoesNotClassifyInvalidArgumentAsStale(t *testing.T) {
+ c := &fcmClient{
+ projectID: "p",
+ httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ return jsonResponse(http.StatusBadRequest, fcmInvalidArgumentBody), nil
+ })},
+ }
+ err := c.send(context.Background(), "tok", map[string]string{"action": "sync"})
+ require.Error(t, err)
+ require.False(t, errors.Is(err, errStaleToken))
+}
+
+func TestFCMErrorCode(t *testing.T) {
+ require.Equal(t, "UNREGISTERED", fcmErrorCode([]byte(fcmUnregisteredBody)))
+ require.Equal(t, "INVALID_ARGUMENT", fcmErrorCode([]byte(fcmInvalidArgumentBody)))
+ require.Equal(t, "", fcmErrorCode([]byte(`{"error":"bad"}`)))
+ require.Equal(t, "", fcmErrorCode([]byte("not json")))
+ require.Equal(t, "", fcmErrorCode(nil))
+}
+
func captureLogs(t *testing.T) *logtest.Hook {
t.Helper()
logger := log.StandardLogger()
diff --git a/server/pkg/repo/push.go b/server/pkg/repo/push.go
index 522c3bf0e4..93f4551a92 100644
--- a/server/pkg/repo/push.go
+++ b/server/pkg/repo/push.go
@@ -53,6 +53,11 @@ func (repo *PushTokenRepository) RemoveTokensOlderThan(creationTime int64) error
return stacktrace.Propagate(err, "")
}
+func (repo *PushTokenRepository) RemoveTokensByFCM(fcmTokens []string) error {
+ _, err := repo.DB.Exec(`DELETE FROM push_tokens WHERE fcm_token = ANY($1)`, pq.Array(fcmTokens))
+ return stacktrace.Propagate(err, "")
+}
+
func (repo *PushTokenRepository) RemoveTokensForUser(userID int64) error {
// Does a seq scan but should be fine since this is relatively infrequent
// and the size of the push tokens table will be small (as it gets