axt-google-api 1.0.0__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,34 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: axt-google-api
3
- Version: 1.0.0
3
+ Version: 1.1.0
4
4
  Summary: Python client library for the Google API
5
5
  Requires-Dist: google-api-python-client>=2.202.0
6
6
  Requires-Dist: google-auth-oauthlib>=1.5.0
7
7
  Requires-Dist: pydantic>=2.13.1
8
8
  Requires-Dist: pydantic-settings>=2.13.1
9
- Requires-Python: >=3.13
9
+ Requires-Dist: tenacity>=9.1.2
10
+ Requires-Python: >=3.11
10
11
  Description-Content-Type: text/markdown
11
12
 
12
13
  # axt-google-api
13
14
 
14
15
  Python client library for the Google API.
15
16
 
17
+ ## Development checks
18
+
19
+ Install the development dependencies and enable the local pre-commit checks:
20
+
21
+ ```sh
22
+ uv sync --group dev
23
+ uv run prek install
24
+ ```
25
+
26
+ The pre-commit hook formats Python files with Ruff, then runs tests, Ruff checks,
27
+ and `ty` before each commit. VS Code is configured to format Python files with
28
+ Ruff on save; install the recommended Ruff and Python extensions. Run the same
29
+ checks manually with `uv run prek run --all-files`. CI runs the checks
30
+ independently before building, so validation does not depend on local hooks.
31
+
16
32
  ## Publishing
17
33
 
18
34
  Commits pushed to `main` are checked by
@@ -2,6 +2,21 @@
2
2
 
3
3
  Python client library for the Google API.
4
4
 
5
+ ## Development checks
6
+
7
+ Install the development dependencies and enable the local pre-commit checks:
8
+
9
+ ```sh
10
+ uv sync --group dev
11
+ uv run prek install
12
+ ```
13
+
14
+ The pre-commit hook formats Python files with Ruff, then runs tests, Ruff checks,
15
+ and `ty` before each commit. VS Code is configured to format Python files with
16
+ Ruff on save; install the recommended Ruff and Python extensions. Run the same
17
+ checks manually with `uv run prek run --all-files`. CI runs the checks
18
+ independently before building, so validation does not depend on local hooks.
19
+
5
20
  ## Publishing
6
21
 
7
22
  Commits pushed to `main` are checked by
@@ -1,14 +1,15 @@
1
1
  [project]
2
2
  name = "axt-google-api"
3
- version = "1.0.0"
3
+ version = "1.1.0"
4
4
  description = "Python client library for the Google API"
5
5
  readme = "README.md"
6
- requires-python = ">=3.13"
6
+ requires-python = ">=3.11"
7
7
  dependencies = [
8
8
  "google-api-python-client>=2.202.0",
9
9
  "google-auth-oauthlib>=1.5.0",
10
10
  "pydantic>=2.13.1",
11
11
  "pydantic-settings>=2.13.1",
12
+ "tenacity>=9.1.2",
12
13
  ]
13
14
 
14
15
  [build-system]
@@ -24,5 +25,8 @@ version_toml = ["pyproject.toml:project.version"]
24
25
 
25
26
  [dependency-groups]
26
27
  dev = [
28
+ "prek>=0.5.12",
29
+ "pytest>=9.2.0",
27
30
  "ruff>=0.17.5",
31
+ "ty>=0.0.112",
28
32
  ]
@@ -0,0 +1,3 @@
1
+ from .gmail import GmailClient
2
+
3
+ __all__ = ["GmailClient"]
@@ -0,0 +1,7 @@
1
+ from axt_google_api.exceptions.exceptions import (
2
+ ApiRateLimitError,
3
+ HistoryNotFoundError,
4
+ MessageNotFoundError,
5
+ )
6
+
7
+ __all__ = ["ApiRateLimitError", "HistoryNotFoundError", "MessageNotFoundError"]
@@ -0,0 +1,10 @@
1
+ class MessageNotFoundError(Exception):
2
+ """Raised when a Gmail message cannot be found."""
3
+
4
+
5
+ class HistoryNotFoundError(Exception):
6
+ """Raised when a Gmail history cannot be found."""
7
+
8
+
9
+ class ApiRateLimitError(Exception):
10
+ """Raised when Gmail API rate limits persist after retries are exhausted."""
@@ -1,9 +1,29 @@
1
1
  import base64
2
+ import json
3
+ from collections.abc import Callable
4
+ from typing import Any
2
5
 
3
6
  from googleapiclient.errors import HttpError
4
7
  from pydantic import SecretStr
8
+ from tenacity import (
9
+ RetryError,
10
+ Retrying,
11
+ retry_if_exception,
12
+ stop_after_attempt,
13
+ wait_random_exponential,
14
+ )
5
15
 
6
16
  from axt_google_api.base import GoogleClient
17
+ from axt_google_api.exceptions import ApiRateLimitError, MessageNotFoundError
18
+ from axt_google_api.exceptions.exceptions import HistoryNotFoundError
19
+
20
+ MAX_RETRY_ATTEMPTS = 6
21
+ MAX_RETRY_DELAY_SECONDS = 60
22
+ RETRYABLE_403_REASONS = {
23
+ "dailyLimitExceeded",
24
+ "rateLimitExceeded",
25
+ "userRateLimitExceeded",
26
+ }
7
27
 
8
28
 
9
29
  class GmailClient(GoogleClient):
@@ -46,6 +66,44 @@ class GmailClient(GoogleClient):
46
66
 
47
67
  return ""
48
68
 
69
+ @staticmethod
70
+ def _execute_with_quota_retry(execute: Callable[[], Any]) -> Any:
71
+ """Retry Gmail quota errors with bounded exponential backoff and jitter."""
72
+ retrying = Retrying(
73
+ retry=retry_if_exception(GmailClient._is_retryable_quota_error),
74
+ wait=wait_random_exponential(min=1, max=MAX_RETRY_DELAY_SECONDS),
75
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
76
+ )
77
+ try:
78
+ return retrying(execute)
79
+ except RetryError as error:
80
+ last_error = error.last_attempt.exception()
81
+ raise ApiRateLimitError(
82
+ f"Gmail API rate limit persisted after {MAX_RETRY_ATTEMPTS} attempts."
83
+ ) from last_error
84
+
85
+ @staticmethod
86
+ def _is_retryable_quota_error(error: BaseException) -> bool:
87
+ """Identify Gmail rate-limit responses that are safe to retry."""
88
+ if not isinstance(error, HttpError):
89
+ return False
90
+ if error.resp.status == 429:
91
+ return True
92
+ if error.resp.status != 403:
93
+ return False
94
+
95
+ try:
96
+ payload = json.loads(error.content)
97
+ except (TypeError, ValueError):
98
+ return False
99
+
100
+ reasons = {
101
+ detail.get("reason")
102
+ for detail in payload.get("error", {}).get("errors", [])
103
+ if isinstance(detail, dict)
104
+ }
105
+ return bool(reasons & RETRYABLE_403_REASONS)
106
+
49
107
  def fetch_email(self, message_id: str, client=None) -> dict:
50
108
  """Fetch an email by its message ID.
51
109
 
@@ -61,9 +119,8 @@ class GmailClient(GoogleClient):
61
119
 
62
120
  with client as service:
63
121
  try:
64
- message = (
65
- service.users().messages().get(userId="me", id=message_id).execute()
66
- )
122
+ request = service.users().messages().get(userId="me", id=message_id)
123
+ message = self._execute_with_quota_retry(request.execute)
67
124
 
68
125
  headers = {
69
126
  h["name"].lower(): h["value"]
@@ -78,7 +135,9 @@ class GmailClient(GoogleClient):
78
135
  }
79
136
  except HttpError as e:
80
137
  if e.resp.status == 404:
81
- raise ValueError(f"Message ID {message_id} not found.") from e
138
+ raise MessageNotFoundError(
139
+ f"Message ID {message_id} not found."
140
+ ) from e
82
141
  raise
83
142
 
84
143
  def fetch_received_email_history(
@@ -99,6 +158,12 @@ class GmailClient(GoogleClient):
99
158
  A list of dictionaries containing the email information.
100
159
  """
101
160
 
161
+ added_ids = set()
162
+ deleted_ids = set()
163
+ trash_ids = set()
164
+
165
+ history_records: list[dict] = []
166
+
102
167
  added_messages = []
103
168
 
104
169
  with self._build_client() as service:
@@ -109,36 +174,49 @@ class GmailClient(GoogleClient):
109
174
  userId="me",
110
175
  startHistoryId=history_id,
111
176
  maxResults=max_results,
112
- historyTypes=["messageAdded"],
113
177
  )
114
178
  )
115
179
  while request is not None:
116
180
  try:
117
- response = request.execute()
181
+ response = self._execute_with_quota_retry(request.execute)
118
182
  except HttpError as e:
119
183
  if e.resp.status == 404:
120
- raise ValueError(
184
+ raise HistoryNotFoundError(
121
185
  f"History ID {history_id} not found. It may be too old or invalid."
122
186
  ) from e
123
187
  raise
124
- added_messages.extend(
125
- message
126
- for h in response.get("history", [])
127
- for message in h.get("messagesAdded", [])
128
- if not exclude_message_ids
129
- or message["message"]["id"] not in exclude_message_ids
130
- )
188
+
189
+ history_records.extend(response.get("history", []))
131
190
 
132
191
  request = service.users().history().list_next(request, response)
133
192
 
134
- emails = []
193
+ for history in history_records:
194
+ if added := history.get("messagesAdded", []):
195
+ for message in added:
196
+ if (
197
+ not exclude_message_ids
198
+ or message["message"]["id"] not in exclude_message_ids
199
+ ):
200
+ added_ids.add(message["message"]["id"])
201
+
202
+ if deleted := history.get("messagesDeleted", []):
203
+ for message in deleted:
204
+ deleted_ids.add(message["message"]["id"])
205
+
206
+ if labels_added := history.get("labelsAdded", []):
207
+ for message in labels_added:
208
+ if "TRASH" in message["labelIds"]:
209
+ trash_ids.add(message["message"]["id"])
210
+
211
+ retained_ids = added_ids - deleted_ids - trash_ids
212
+
213
+ for message_id in retained_ids:
214
+ try:
215
+ message = self.fetch_email(message_id)
216
+ except MessageNotFoundError:
217
+ continue
135
218
 
136
- for message in added_messages:
137
- message = self.fetch_email(message["message"]["id"])
138
- if senders_filter is None or any(
139
- message["sender"] is not None and s in message["sender"]
140
- for s in senders_filter
141
- ):
142
- emails.append(message)
219
+ if senders_filter is None or message["sender"] in senders_filter:
220
+ added_messages.append(message)
143
221
 
144
- return emails
222
+ return added_messages
@@ -1,5 +0,0 @@
1
- from .gmail import GmailClient
2
-
3
- __all__ = [
4
- "GmailClient",
5
- ]