Coverage for dao/apns_device_dao.py: 100.00%
49 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 14:44 +0000
1"""APNs Device DAO (SB-1236).
3One row per native iOS install. device_token is the hex token the app gets
4from registerForRemoteNotifications(); it identifies (device, app,
5environment) to APNs and is unique here.
7Idempotency: re-registering an existing token updates user_id and metadata
8in place, so a token signed into by a different user moves to that user
9(mirrors PushSubscriptionDAO's endpoint handling).
10"""
12from __future__ import annotations
14from datetime import UTC, datetime
16import structlog
18from dao.base_dao import BaseDAO
20logger = structlog.get_logger()
22TABLE = "apns_devices"
24# Columns the API returns to the owner. The token itself is write-only.
25_PUBLIC_COLUMNS = "id, environment, bundle_id, device_label, app_version, created_at, last_seen_at"
27# Columns the sender needs.
28_SEND_COLUMNS = "id, user_id, device_token, environment, bundle_id"
31class ApnsDeviceDAO(BaseDAO):
32 """Data access for APNs device registrations."""
34 def upsert(
35 self,
36 user_id: str,
37 device_token: str,
38 environment: str,
39 bundle_id: str | None = None,
40 device_label: str | None = None,
41 app_version: str | None = None,
42 ) -> dict | None:
43 """Create or update a device by device_token.
45 On token collision, moves the row to user_id and refreshes metadata +
46 last_seen_at; id and created_at are kept. Returns the row on success,
47 None on error.
48 """
49 payload: dict[str, str | None] = {
50 "user_id": user_id,
51 "device_token": device_token,
52 "environment": environment,
53 "device_label": device_label,
54 "app_version": app_version,
55 "last_seen_at": datetime.now(UTC).isoformat(),
56 }
57 if bundle_id:
58 payload["bundle_id"] = bundle_id
59 try:
60 response = self.client.table(TABLE).upsert(payload, on_conflict="device_token").execute()
61 return response.data[0] if response.data else None
62 except Exception:
63 logger.exception("apns_device_upsert_failed", user_id=user_id)
64 return None
66 def list_by_user(self, user_id: str) -> list[dict]:
67 """The user's devices, newest first, without tokens."""
68 try:
69 response = (
70 self.client.table(TABLE)
71 .select(_PUBLIC_COLUMNS)
72 .eq("user_id", user_id)
73 .order("created_at", desc=True)
74 .execute()
75 )
76 return response.data or []
77 except Exception:
78 logger.exception("apns_device_list_failed", user_id=user_id)
79 return []
81 def list_for_user_ids(self, user_ids: list[str]) -> list[dict]:
82 """Fan-out query: every device owned by any of these users, with tokens.
84 One row per device (a user with two iPhones gets two). Returns [] on
85 error — the dispatcher must never break on a lookup failure.
86 """
87 if not user_ids:
88 return []
89 try:
90 response = self.client.table(TABLE).select(_SEND_COLUMNS).in_("user_id", user_ids).execute()
91 return response.data or []
92 except Exception:
93 logger.exception("apns_device_list_for_users_failed", user_count=len(user_ids))
94 return []
96 def delete_for_user(self, user_id: str, device_id: str) -> bool:
97 """Delete one of the user's devices. Filters by user_id for defense-in-depth.
99 Returns True if a row was deleted, False otherwise.
100 """
101 try:
102 response = self.client.table(TABLE).delete().eq("id", device_id).eq("user_id", user_id).execute()
103 return bool(response.data)
104 except Exception:
105 logger.exception(
106 "apns_device_delete_failed",
107 user_id=user_id,
108 device_id=device_id,
109 )
110 return False
112 def delete_by_token(self, device_token: str) -> bool:
113 """Used when APNs reports the token gone (410, BadDeviceToken, ...).
115 Returns True if a row was deleted.
116 """
117 try:
118 response = self.client.table(TABLE).delete().eq("device_token", device_token).execute()
119 return bool(response.data)
120 except Exception:
121 logger.exception("apns_device_delete_by_token_failed")
122 return False