Coverage for dao/push_subscription_dao.py: 23.64%

53 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 15:03 +0000

1"""Push Subscription DAO. 

2 

3One row per (user, device). Endpoint is the URL returned by the browser's 

4PushManager.subscribe(); it uniquely identifies a browser+device combination 

5to the push service. 

6 

7Idempotency: re-registering an existing endpoint updates the user_id and 

8metadata in place (handles "user signs into MT on a phone someone else 

9already used to follow another account"). 

10""" 

11 

12from __future__ import annotations 

13 

14from datetime import UTC, datetime 

15 

16import structlog 

17 

18from dao.base_dao import BaseDAO 

19 

20logger = structlog.get_logger() 

21 

22TABLE = "push_subscriptions" 

23 

24 

25class PushSubscriptionDAO(BaseDAO): 

26 """Data access for Web Push subscriptions.""" 

27 

28 def upsert( 

29 self, 

30 user_id: str, 

31 endpoint: str, 

32 p256dh_key: str, 

33 auth_key: str, 

34 device_label: str | None = None, 

35 user_agent: str | None = None, 

36 ) -> dict | None: 

37 """Create or update a subscription by endpoint. 

38 

39 On endpoint collision, updates user_id + label + keys + last_seen_at. 

40 Returns the row on success, None on error. 

41 """ 

42 now = datetime.now(UTC).isoformat() 

43 payload = { 

44 "user_id": user_id, 

45 "endpoint": endpoint, 

46 "p256dh_key": p256dh_key, 

47 "auth_key": auth_key, 

48 "device_label": device_label, 

49 "user_agent": user_agent, 

50 "last_seen_at": now, 

51 } 

52 try: 

53 existing = self.get_by_endpoint(endpoint) 

54 if existing: 

55 response = ( 

56 self.client.table(TABLE) 

57 .update(payload) 

58 .eq("endpoint", endpoint) 

59 .execute() 

60 ) 

61 return response.data[0] if response.data else None 

62 response = self.client.table(TABLE).insert(payload).execute() 

63 return response.data[0] if response.data else None 

64 except Exception: 

65 logger.exception("push_subscription_upsert_failed", user_id=user_id) 

66 return None 

67 

68 def get_by_endpoint(self, endpoint: str) -> dict | None: 

69 try: 

70 response = ( 

71 self.client.table(TABLE) 

72 .select("*") 

73 .eq("endpoint", endpoint) 

74 .limit(1) 

75 .execute() 

76 ) 

77 return response.data[0] if response.data else None 

78 except Exception: 

79 logger.exception("push_subscription_get_failed") 

80 return None 

81 

82 def list_by_user(self, user_id: str) -> list[dict]: 

83 try: 

84 response = ( 

85 self.client.table(TABLE) 

86 .select("id, device_label, user_agent, created_at, last_seen_at") 

87 .eq("user_id", user_id) 

88 .order("created_at", desc=True) 

89 .execute() 

90 ) 

91 return response.data or [] 

92 except Exception: 

93 logger.exception("push_subscription_list_failed", user_id=user_id) 

94 return [] 

95 

96 def delete_by_id(self, user_id: str, subscription_id: str) -> bool: 

97 """Delete a subscription. Filters by user_id for defense-in-depth. 

98 

99 Returns True if a row was deleted, False otherwise. 

100 """ 

101 try: 

102 response = ( 

103 self.client.table(TABLE) 

104 .delete() 

105 .eq("id", subscription_id) 

106 .eq("user_id", user_id) 

107 .execute() 

108 ) 

109 return bool(response.data) 

110 except Exception: 

111 logger.exception( 

112 "push_subscription_delete_failed", 

113 user_id=user_id, 

114 subscription_id=subscription_id, 

115 ) 

116 return False 

117 

118 def delete_by_endpoint(self, endpoint: str) -> bool: 

119 """Used when the push service returns 404/410 (subscription expired). 

120 

121 Returns True if a row was deleted. 

122 """ 

123 try: 

124 response = ( 

125 self.client.table(TABLE).delete().eq("endpoint", endpoint).execute() 

126 ) 

127 return bool(response.data) 

128 except Exception: 

129 logger.exception("push_subscription_delete_by_endpoint_failed") 

130 return False 

131 

132 def touch_last_seen(self, subscription_id: str) -> None: 

133 try: 

134 self.client.table(TABLE).update( 

135 {"last_seen_at": datetime.now(UTC).isoformat()} 

136 ).eq("id", subscription_id).execute() 

137 except Exception: 

138 logger.exception( 

139 "push_subscription_touch_failed", subscription_id=subscription_id 

140 )