(ctx context.Context, userID uuid.UUID, msg codersdk.WebpushMessage)
| 191 | } |
| 192 | |
| 193 | func (n *Webpusher) Dispatch(ctx context.Context, userID uuid.UUID, msg codersdk.WebpushMessage) error { |
| 194 | subscriptions, err := n.subscriptionsForUser(ctx, userID) |
| 195 | if err != nil { |
| 196 | return xerrors.Errorf("get web push subscriptions by user ID: %w", err) |
| 197 | } |
| 198 | if len(subscriptions) == 0 { |
| 199 | return nil |
| 200 | } |
| 201 | |
| 202 | msgJSON, err := json.Marshal(msg) |
| 203 | if err != nil { |
| 204 | return xerrors.Errorf("marshal webpush notification: %w", err) |
| 205 | } |
| 206 | |
| 207 | cleanupSubscriptions := make([]uuid.UUID, 0) |
| 208 | var mu sync.Mutex |
| 209 | var eg errgroup.Group |
| 210 | for _, subscription := range subscriptions { |
| 211 | eg.Go(func() error { |
| 212 | // TODO: Implement some retry logic here. For now, this is just a |
| 213 | // best-effort attempt. |
| 214 | statusCode, body, err := n.webpushSend(ctx, msgJSON, subscription.Endpoint, webpush.Keys{ |
| 215 | Auth: subscription.EndpointAuthKey, |
| 216 | P256dh: subscription.EndpointP256dhKey, |
| 217 | }) |
| 218 | if err != nil { |
| 219 | return xerrors.Errorf("send webpush notification: %w", err) |
| 220 | } |
| 221 | |
| 222 | if isStaleSubscriptionStatus(statusCode) { |
| 223 | // Remove subscriptions that the push service has marked as |
| 224 | // permanently invalid (Apple returns 403 BadJwtToken and 404 |
| 225 | // for invalidated subscriptions, FCM returns 404 for |
| 226 | // expired endpoints, all push services return 410 for |
| 227 | // permanently gone subscriptions, and 400 indicates a |
| 228 | // malformed subscription that cannot be retried). Without |
| 229 | // this, stale rows accumulate after PWA reinstalls and the |
| 230 | // in-memory cache keeps trying to deliver to dead |
| 231 | // subscriptions. |
| 232 | mu.Lock() |
| 233 | cleanupSubscriptions = append(cleanupSubscriptions, subscription.ID) |
| 234 | mu.Unlock() |
| 235 | } |
| 236 | |
| 237 | if statusCode == http.StatusGone { |
| 238 | // 410 Gone is informational, not a delivery error. |
| 239 | return nil |
| 240 | } |
| 241 | |
| 242 | // 200, 201, and 202 are common for successful delivery. |
| 243 | if statusCode > http.StatusAccepted { |
| 244 | // It's likely the subscription failed to deliver for some reason. |
| 245 | return xerrors.Errorf("web push dispatch failed with status code %d: %s", statusCode, string(body)) |
| 246 | } |
| 247 | |
| 248 | return nil |
| 249 | }) |
| 250 | } |
nothing calls this directly
no test coverage detected