forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle_utils.py
More file actions
269 lines (224 loc) · 9.95 KB
/
Copy pathgoogle_utils.py
File metadata and controls
269 lines (224 loc) · 9.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
"""
Shared utilities for Google OAuth integrations (Calendar, Gmail, etc.).
"""
import asyncio
import logging
import os
from typing import Any, Dict, Optional
import httpx
from google.cloud import firestore
import database.users as users_db
from utils.executors import db_executor, run_blocking
from utils.http_client import get_auth_client
from utils.integration_telemetry import (
GOOGLE_CALENDAR,
IntegrationTelemetryContext,
emit_auth_refresh_attempted,
emit_auth_refresh_failed,
emit_auth_refresh_succeeded,
)
from utils.integrations_registry import (
GMAIL_READ_SCOPE,
INTEGRATION_PROVIDERS,
oauth_scopes,
)
from utils.log_sanitizer import sanitize
logger = logging.getLogger(__name__)
# Google Calendar and Gmail share a single OAuth grant stored under this key.
GOOGLE_INTEGRATION_KEY = 'google_calendar'
GMAIL_READONLY_SCOPE = GMAIL_READ_SCOPE
# Scopes requested when the user connects their Google account. Derived from the
# registry that builds the consent request, so the scopes we ask for and the ones
# `google_integration_has_scope` verifies a stored grant against cannot drift: a
# scope requested but never verified is unenforced, and one required but never
# requested reads as ungranted forever and loops the user through reconnect.
GOOGLE_OAUTH_SCOPES = oauth_scopes(INTEGRATION_PROVIDERS[GOOGLE_INTEGRATION_KEY])
def google_integration_has_scope(integration: Optional[Dict[str, Any]], scope: str) -> bool:
"""Whether a stored Google integration was granted `scope`.
Grants created before a scope was requested have no `granted_scopes` field, so
they read as not granted and the user is asked to reconnect.
"""
if not integration:
return False
return scope in (integration.get('granted_scopes') or [])
# Transient HTTP status codes that should be retried
_RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504}
# Max retries for transient failures
_MAX_RETRIES = 3
class GoogleAPIError(Exception):
"""Structured exception for Google API failures."""
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message
super().__init__(f"Google API error {status_code}: {message}")
@property
def is_auth_error(self) -> bool:
return self.status_code == 401 or 'invalid_grant' in self.message.lower()
@property
def is_rate_limit(self) -> bool:
return self.status_code == 429
@property
def is_permission_error(self) -> bool:
return self.status_code == 403
@property
def is_retryable(self) -> bool:
return self.status_code in _RETRYABLE_STATUS_CODES
async def _mark_google_integration_reauth_required(
uid: str, integration: dict[str, Any], integration_key: str, reason: str
) -> None:
updated = dict(integration)
updated['connected'] = False
updated['reauth_required'] = True
updated['reauth_reason'] = reason
updated['access_token'] = firestore.DELETE_FIELD
await run_blocking(db_executor, users_db.set_integration, uid, integration_key, updated)
async def refresh_google_token(
uid: str,
integration: dict[str, Any],
*,
integration_name: str = GOOGLE_CALENDAR,
integration_key: str = 'google_calendar',
) -> Optional[str]:
"""
Refresh Google access token using refresh token.
Works for both Calendar and Gmail since they use the same OAuth.
Args:
uid: User ID
integration: Integration dict containing refresh_token
integration_name: Product-visible provider name for telemetry.
integration_key: Stored integration key to update after refresh.
Returns:
New access token or None if refresh failed
"""
refresh_token = integration.get('refresh_token')
telemetry_context = IntegrationTelemetryContext(
integration_name=integration_name,
operation='refresh_token',
uid=uid,
)
emit_auth_refresh_attempted(telemetry_context)
if not refresh_token:
logger.warning(f"🔄 No refresh_token stored for uid={uid}, cannot refresh")
emit_auth_refresh_failed(telemetry_context, 'missing_token')
await _mark_google_integration_reauth_required(uid, integration, integration_key, 'missing_refresh_token')
return None
client_id = os.getenv('GOOGLE_CLIENT_ID')
client_secret = os.getenv('GOOGLE_CLIENT_SECRET')
if not all([client_id, client_secret]):
logger.error("🔄 Missing GOOGLE_CLIENT_ID or GOOGLE_CLIENT_SECRET env vars")
emit_auth_refresh_failed(telemetry_context, 'missing_oauth_config')
return None
try:
client = get_auth_client()
response = await client.post(
'https://oauth2.googleapis.com/token',
data={
'client_id': client_id,
'client_secret': client_secret,
'refresh_token': refresh_token,
'grant_type': 'refresh_token',
},
)
if response.status_code == 200:
token_data = response.json()
new_access_token = token_data.get('access_token')
if new_access_token:
# Update stored token — offload the sync Firestore write to the
# DB executor so it does not block the event loop during
# concurrent chat/tool streaming.
integration['access_token'] = new_access_token
await run_blocking(db_executor, users_db.set_integration, uid, integration_key, integration)
logger.info(f"🔄 Successfully refreshed Google token for uid={uid}")
emit_auth_refresh_succeeded(telemetry_context)
return new_access_token
# Detect token revocation (invalid_grant) — user revoked access in Google settings
error_body = sanitize(response.text[:200]) if response.text else "No error body"
if response.status_code == 400 and 'invalid_grant' in (response.text or '').lower():
logger.error(
f"🔄 Google refresh token revoked for uid={uid} (invalid_grant). "
f"User needs to reconnect. Response: {error_body}"
)
await _mark_google_integration_reauth_required(uid, integration, integration_key, 'invalid_grant')
else:
logger.error(
f"🔄 Google token refresh failed for uid={uid}: " f"status={response.status_code}, body={error_body}"
)
emit_auth_refresh_failed(
telemetry_context, response.text or 'token_refresh_failed', provider_status_code=response.status_code
)
except httpx.TimeoutException:
logger.error(f"🔄 Timeout refreshing Google token for uid={uid}")
emit_auth_refresh_failed(telemetry_context, 'timeout')
except httpx.ConnectError:
logger.error(f"🔄 Network error refreshing Google token for uid={uid}")
emit_auth_refresh_failed(telemetry_context, 'connect_error')
except Exception as e:
logger.error(f"🔄 Unexpected error refreshing Google token for uid={uid}: {e}")
emit_auth_refresh_failed(telemetry_context, e)
return None
async def google_api_request(
method: str,
url: str,
access_token: str,
params: Optional[Dict[str, Any]] = None,
body: Optional[Dict[str, Any]] = None,
allow_204: bool = False,
) -> Any:
"""
Make a Google API request with automatic retry for transient failures.
Retries on 429 (rate limit) and 5xx (server errors) with exponential backoff.
Raises GoogleAPIError with status_code for structured error handling upstream.
Raises httpx.TimeoutException / httpx.ConnectError for network failures.
"""
logger.info(f"🌐 Google API {method.upper()} {url}")
client = get_auth_client()
last_error = None
for attempt in range(_MAX_RETRIES):
try:
r = await client.request(
method=method,
url=url,
headers={"Authorization": f"Bearer {access_token}"},
json=body,
params=params,
)
except httpx.TimeoutException:
logger.warning(f"🌐 Timeout on attempt {attempt + 1}/{_MAX_RETRIES} for {method.upper()} {url}")
last_error = httpx.TimeoutException(f"Timeout calling {url}")
if attempt < _MAX_RETRIES - 1:
await asyncio.sleep(2**attempt)
continue
except httpx.ConnectError as e:
logger.warning(f"🌐 Network error on attempt {attempt + 1}/{_MAX_RETRIES} for {method.upper()} {url}: {e}")
last_error = e
if attempt < _MAX_RETRIES - 1:
await asyncio.sleep(2**attempt)
continue
logger.info(f"🔎 Status {r.status_code}")
if allow_204 and r.status_code == 204:
return None
if r.status_code == 200:
return r.json()
snippet = sanitize(r.text[:200]) if r.text else "No error body"
# Retry on transient errors with exponential backoff
if r.status_code in _RETRYABLE_STATUS_CODES and attempt < _MAX_RETRIES - 1:
delay = 2**attempt
if r.status_code == 429:
# Respect Retry-After header if present
retry_after = r.headers.get('Retry-After')
if retry_after and retry_after.isdigit():
delay = max(delay, int(retry_after))
logger.warning(f"🌐 Rate limited (429), retrying in {delay}s (attempt {attempt + 1}/{_MAX_RETRIES})")
else:
logger.warning(
f"🌐 Server error {r.status_code}, retrying in {delay}s (attempt {attempt + 1}/{_MAX_RETRIES})"
)
await asyncio.sleep(delay)
continue
# Non-retryable error — raise immediately
raise GoogleAPIError(r.status_code, snippet)
# All retries exhausted
if last_error:
raise last_error
# Unreachable with _MAX_RETRIES >= 1, but kept as a safety net
raise GoogleAPIError(0, "All retries exhausted with no response")