Coverage for dao/fcm_device_dao.py: 100.00%
51 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 17:31 +0000
1"""FCM Device DAO (SB-1463).
3One row per native Android install. fid is the Firebase Installation ID the
4app gets from FirebaseInstallations.getId(); FCM HTTP v1 addresses a device
5by it, and it is unique here.
7Idempotency: re-registering an existing fid updates user_id and metadata in
8place, so an fid signed into by a different user moves to that user (mirrors
9ApnsDeviceDAO).
10"""
12from __future__ import annotations
14from datetime import UTC, datetime
16import structlog
18from dao.base_dao import BaseDAO
20logger = structlog.get_logger()
22TABLE = "fcm_devices"
24# Columns the API returns to the owner. The fid itself is write-only.
25_PUBLIC_COLUMNS = "id, device_label, app_version, created_at, last_seen_at"
27# Columns the sender needs.
28_SEND_COLUMNS = "id, user_id, fid"
31class FcmDeviceDAO(BaseDAO):
32 """Data access for FCM device registrations."""
34 def upsert(
35 self,
36 user_id: str,
37 fid: str,
38 device_label: str | None = None,
39 app_version: str | None = None,
40 ) -> dict | None:
41 """Create or update a device by fid.
43 On fid collision, moves the row to user_id and refreshes last_seen_at
44 plus whichever metadata was given — an omitted label or version keeps
45 the stored one. id and created_at are kept. Returns the row on
46 success, None on error.
47 """
48 payload: dict[str, str] = {
49 "user_id": user_id,
50 "fid": fid,
51 "last_seen_at": datetime.now(UTC).isoformat(),
52 }
53 if device_label is not None:
54 payload["device_label"] = device_label
55 if app_version is not None:
56 payload["app_version"] = app_version
57 try:
58 response = self.client.table(TABLE).upsert(payload, on_conflict="fid").execute()
59 return response.data[0] if response.data else None
60 except Exception:
61 logger.exception("fcm_device_upsert_failed", user_id=user_id)
62 return None
64 def list_by_user(self, user_id: str) -> list[dict]:
65 """The user's devices, newest first, without fids."""
66 try:
67 response = (
68 self.client.table(TABLE)
69 .select(_PUBLIC_COLUMNS)
70 .eq("user_id", user_id)
71 .order("created_at", desc=True)
72 .execute()
73 )
74 return response.data or []
75 except Exception:
76 logger.exception("fcm_device_list_failed", user_id=user_id)
77 return []
79 def list_for_user_ids(self, user_ids: list[str]) -> list[dict]:
80 """Fan-out query: every device owned by any of these users, with fids.
82 One row per device. Returns [] on error — the dispatcher must never
83 break on a lookup failure.
84 """
85 if not user_ids:
86 return []
87 try:
88 response = self.client.table(TABLE).select(_SEND_COLUMNS).in_("user_id", user_ids).execute()
89 return response.data or []
90 except Exception:
91 logger.exception("fcm_device_list_for_users_failed", user_count=len(user_ids))
92 return []
94 def delete_for_user(self, user_id: str, device_id: str) -> bool:
95 """Delete one of the user's devices. Filters by user_id for defense-in-depth.
97 Returns True if a row was deleted, False otherwise.
98 """
99 try:
100 response = self.client.table(TABLE).delete().eq("id", device_id).eq("user_id", user_id).execute()
101 return bool(response.data)
102 except Exception:
103 logger.exception(
104 "fcm_device_delete_failed",
105 user_id=user_id,
106 device_id=device_id,
107 )
108 return False
110 def delete_by_fid(self, fid: str) -> bool:
111 """Used when FCM reports the installation gone (UNREGISTERED, ...).
113 Returns True if a row was deleted.
114 """
115 try:
116 response = self.client.table(TABLE).delete().eq("fid", fid).execute()
117 return bool(response.data)
118 except Exception:
119 logger.exception("fcm_device_delete_by_fid_failed")
120 return False