Coverage for r2_client.py: 35.00%

56 statements  

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

1"""Cloudflare R2 client for match-photo storage (SB-31). 

2 

3R2 is S3-compatible, so we use boto3. Credentials are loaded from env vars; if 

4any are missing the module reports `is_configured() == False` and callers should 

5return HTTP 503 with a helpful message rather than crashing. 

6 

7Why R2 (not Supabase Storage): zero egress fees + 10GB free preserves our 

8Supabase free-tier headroom. See Linear SB-19 for the cost analysis. 

9""" 

10 

11from __future__ import annotations 

12 

13import os 

14from typing import TYPE_CHECKING 

15 

16import structlog 

17 

18if TYPE_CHECKING: 

19 from mypy_boto3_s3 import S3Client 

20 

21logger = structlog.get_logger(__name__) 

22 

23_R2_ENV_VARS = ( 

24 "R2_ACCOUNT_ID", 

25 "R2_ACCESS_KEY_ID", 

26 "R2_SECRET_ACCESS_KEY", 

27 "R2_BUCKET", 

28) 

29 

30R2_NOT_CONFIGURED_MSG = ( 

31 "Cloudflare R2 is not configured. Set R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, " 

32 "R2_SECRET_ACCESS_KEY, R2_BUCKET env vars to enable match-photo upload." 

33) 

34 

35DEFAULT_SIGNED_URL_TTL_SECONDS = 3600 

36 

37_client: S3Client | None = None 

38 

39 

40def is_configured() -> bool: 

41 """True iff all required R2 env vars are present and non-empty.""" 

42 return all(os.environ.get(var) for var in _R2_ENV_VARS) 

43 

44 

45def _bucket() -> str: 

46 return os.environ["R2_BUCKET"] 

47 

48 

49def _get_client() -> S3Client: 

50 """Lazily build and cache the boto3 S3 client pointed at R2. 

51 

52 R2 endpoint format: https://<account_id>.r2.cloudflarestorage.com. 

53 R2 ignores the region but boto3 requires one — use 'auto'. 

54 """ 

55 global _client 

56 if _client is not None: 

57 return _client 

58 

59 if not is_configured(): 

60 raise RuntimeError(R2_NOT_CONFIGURED_MSG) 

61 

62 import boto3 

63 

64 account_id = os.environ["R2_ACCOUNT_ID"] 

65 endpoint_url = os.environ.get( 

66 "R2_ENDPOINT_URL", 

67 f"https://{account_id}.r2.cloudflarestorage.com", 

68 ) 

69 

70 _client = boto3.client( 

71 "s3", 

72 endpoint_url=endpoint_url, 

73 aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"], 

74 aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"], 

75 region_name="auto", 

76 ) 

77 return _client 

78 

79 

80def _reset_client_for_tests() -> None: 

81 """Drop the cached client. Tests use this between configurations.""" 

82 global _client 

83 _client = None 

84 

85 

86def upload_photo(key: str, content: bytes, content_type: str = "image/jpeg") -> str: 

87 """Upload bytes to R2 at the given key, return a signed URL (1h TTL). 

88 

89 Overwrites any existing object at the same key (upsert semantics, matching 

90 the club-logo upload pattern in `backend/app.py`). 

91 """ 

92 client = _get_client() 

93 client.put_object( 

94 Bucket=_bucket(), 

95 Key=key, 

96 Body=content, 

97 ContentType=content_type, 

98 ) 

99 logger.info("r2_upload_succeeded", key=key, bytes=len(content)) 

100 return get_signed_url(key) 

101 

102 

103def get_signed_url(key: str, expires_in: int = DEFAULT_SIGNED_URL_TTL_SECONDS) -> str: 

104 """Mint a presigned GET URL for an object. Local-only HMAC, no network call.""" 

105 client = _get_client() 

106 return client.generate_presigned_url( 

107 "get_object", 

108 Params={"Bucket": _bucket(), "Key": key}, 

109 ExpiresIn=expires_in, 

110 ) 

111 

112 

113def delete_photo(key: str) -> None: 

114 """Delete an object from R2. Idempotent — succeeds on a missing key.""" 

115 client = _get_client() 

116 client.delete_object(Bucket=_bucket(), Key=key) 

117 logger.info("r2_delete_succeeded", key=key) 

118 

119 

120# ── Android APK distribution (SB-313) ──────────────────────────────────────── 

121# The release CI uploads the signed APK to a SEPARATE, PRIVATE bucket 

122# (mt-android-releases). It's private on purpose: MT is invite-only, so the APK 

123# must not be anonymously downloadable. The backend hands authenticated users a 

124# short-lived presigned URL instead. 

125 

126ANDROID_APK_KEY = "latest/missingtable.apk" 

127ANDROID_APK_URL_TTL_SECONDS = 300 # 5 min: minted per authenticated request 

128 

129 

130def _android_bucket() -> str: 

131 return os.environ.get("R2_ANDROID_BUCKET", "mt-android-releases") 

132 

133 

134def get_apk_download_url(expires_in: int = ANDROID_APK_URL_TTL_SECONDS) -> str: 

135 """Mint a short-lived presigned GET URL for the latest Android APK. 

136 

137 Reuses the account-level R2 client; the backend's R2 credentials must have 

138 read access to R2_ANDROID_BUCKET (default 'mt-android-releases'). Local HMAC 

139 signing, no network call. 

140 """ 

141 client = _get_client() 

142 return client.generate_presigned_url( 

143 "get_object", 

144 Params={"Bucket": _android_bucket(), "Key": ANDROID_APK_KEY}, 

145 ExpiresIn=expires_in, 

146 ) 

147 

148 

149def get_apk_versions() -> tuple[int | None, int | None]: 

150 """(version_code, min_version_code) from the latest APK's R2 metadata. 

151 

152 The Android release CI stamps `versioncode` (this build) and 

153 `minversioncode` (oldest still-supported build — SB-328 force-upgrade) on 

154 upload. One head_object serves both. Missing metadata or any R2 error 

155 degrades to None, which the app treats as "no update information". 

156 """ 

157 try: 

158 client = _get_client() 

159 head = client.head_object(Bucket=_android_bucket(), Key=ANDROID_APK_KEY) 

160 meta = head.get("Metadata") or {} 

161 

162 def _int(key: str) -> int | None: 

163 raw = meta.get(key) 

164 return int(raw) if raw else None 

165 

166 return _int("versioncode"), _int("minversioncode") 

167 except Exception: 

168 logger.warning("r2_apk_version_lookup_failed", exc_info=True) 

169 return None, None