Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 38 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@

import jwt
import requests
import sentry_sdk
from google.api_core import exceptions as api_exceptions
from google.api_core.client_options import ClientOptions
from google.auth.credentials import AnonymousCredentials
from google.cloud import bigquery
from sentry_sdk.integrations.logging import LoggingIntegration

BUG_RE = re.compile(r"\b(?:bug|b=)\s*#?(\d+)\b", re.I)

Expand Down Expand Up @@ -398,6 +400,25 @@ def setup_logging() -> None:
)


def setup_sentry() -> None:
"""
Report errors to Sentry when SENTRY_DSN is set; no-op otherwise.

logger.error/logger.exception calls become Sentry events and lower levels
are attached as breadcrumbs. SENTRY_ENVIRONMENT and SENTRY_RELEASE are read
from the environment by the SDK.
"""
dsn = os.environ.get("SENTRY_DSN")
if not dsn:
return
sentry_sdk.init(
dsn=dsn,
integrations=[
LoggingIntegration(level=logging.INFO, event_level=logging.ERROR)
Comment thread
dklawren marked this conversation as resolved.
Resolved
],
)
Comment thread
dklawren marked this conversation as resolved.
Resolved


def _parse_github_timestamp(value: str | None) -> datetime | None:
"""
Parse a GitHub ISO-8601 timestamp (e.g. ``2026-06-17T14:53:58Z``) into an
Expand Down Expand Up @@ -1722,11 +1743,19 @@ def main() -> int:
4. Repeat until no more data
"""
setup_logging()
setup_sentry()
try:
return _main()
except RuntimeError as e:
logger.error(str(e))
logger.exception(str(e))
return 1
except SystemExit as e:
# Missing configuration: report it, then still fail the run.
sentry_sdk.capture_message(str(e), level="fatal")
raise
finally:
# The process exits right after this; send queued events first.
sentry_sdk.flush()


def _main() -> int:
Expand Down Expand Up @@ -1835,7 +1864,10 @@ def _main() -> int:
# failed repo rather than propagating out of the executor and
# discarding the results of other in-flight repos. logger.exception
# records the worker thread's traceback for debugging in CI/prod.
logger.exception(f"Failed to process repo {repo}: {exc}")
# The Sentry event is tagged with the repo for filtering.
with sentry_sdk.new_scope() as scope:
scope.set_tag("repo", repo)
logger.exception(f"Failed to process repo {repo}: {exc}")
Comment thread
dklawren marked this conversation as resolved.
Resolved
failed_repos.append(repo)
continue
total_processed += processed
Expand All @@ -1844,10 +1876,12 @@ def _main() -> int:
)

if failed_repos:
logger.error(
# Per-repo failures were already reported to Sentry above. Exit 0 so a
# partial failure does not mark the cron job as failed.
logger.warning(
f"ETL completed with failures. Failed repos: {', '.join(failed_repos)}"
)
return 1
return 0
Comment thread
dklawren marked this conversation as resolved.
Resolved

logger.info(
f"GitHub ETL process completed successfully. Total PRs processed: {total_processed}"
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ dependencies = [
"requests>=2.25.0",
"google-cloud-bigquery==3.25.0",
"PyJWT[crypto]>=2.0.0",
"sentry-sdk>=2.0.0",
]

[project.optional-dependencies]
Expand Down
12 changes: 10 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
certifi==2026.1.4 \
--hash=sha256:9943707519e4add1115f44c2bc244f782c0249876bf51b6599fee1ffbedd685c \
--hash=sha256:ac726dd470482006e014ad384921ed6438c457018f4b3d204aea4281258b2120
# via requests
# via
# requests
# sentry-sdk
cffi==2.0.0 \
--hash=sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb \
--hash=sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b \
Expand Down Expand Up @@ -458,6 +460,10 @@ rsa==4.9.1 \
--hash=sha256:68635866661c6836b8d39430f97a996acbd61bfa49406748ea243539fe239762 \
--hash=sha256:e7bdbfdb5497da4c07dfd35530e1a902659db6ff241e39d9953cad06ebd0ae75
# via google-auth
sentry-sdk==2.71.0 \
--hash=sha256:7beb27a22f06396f3a05510c3da6ea10e1c79e02e859993c27ce4ff074e296d6 \
--hash=sha256:9ed36b4c206048aa67b5ddba0a6e28d59fc55cf10d60f5f7aea2c3917184bf4a
# via github-etl (pyproject.toml)
six==1.17.0 \
--hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \
--hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81
Expand All @@ -469,4 +475,6 @@ typing-extensions==4.15.0 \
urllib3==2.6.3 \
--hash=sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed \
--hash=sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4
# via requests
# via
# requests
# sentry-sdk
78 changes: 75 additions & 3 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,7 @@ def extract_side_effect(*args, **kwargs):
):
result = main.main()

assert result == 1 # partial failure
assert result == 0 # partial failure is reported to Sentry, not the exit code
assert mock_extract.call_count == 2 # both repos were attempted
mock_load.assert_called_once() # only the successful repo loaded data

Expand All @@ -562,7 +562,7 @@ def test_bare_exception_on_one_repo_is_isolated(
"""A bare Exception (e.g. from load_data) on one repo must not abort the others.

The executor catches broadly, so the failing repo is recorded in failed_repos
(overall exit code 1) while the healthy repo still completes its load.
(reported to Sentry, overall exit code 0) while the healthy repo still completes its load.
"""
# Fresh iterator per repo (a shared return_value iterator would be exhausted
# by whichever repo consumes it first).
Expand Down Expand Up @@ -597,11 +597,83 @@ def transform_side_effect(chunk, repo):
):
result = main.main()

assert result == 1 # partial failure recorded, run did not abort
assert result == 0 # partial failure recorded, run did not abort
assert mock_extract.call_count == 2 # both repos were attempted
assert mock_load.call_count == 2 # both repos reached the load step


@patch("main.sentry_sdk")
@patch("main.setup_logging")
@patch("main.bigquery.Client")
@patch("requests.Session")
@patch("main.extract_pull_requests")
def test_repo_failure_is_tagged_for_sentry(
mock_extract,
mock_session_class,
mock_bq_client,
mock_setup_logging,
mock_sentry,
):
"""A failed repo is reported under a Sentry scope tagged with the repo name."""
mock_extract.side_effect = main.TooManyRetriesError("GitHub API error 502")
scope = mock_sentry.new_scope.return_value.__enter__.return_value

with patch.dict(
os.environ,
{
"GITHUB_REPOS": "mozilla/firefox",
"BIGQUERY_PROJECT": "test",
"BIGQUERY_DATASET": "test",
},
clear=True,
):
result = main.main()

assert result == 0
scope.set_tag.assert_called_once_with("repo", "mozilla/firefox")
mock_sentry.flush.assert_called_once()


@patch("main.sentry_sdk")
@patch("main.setup_logging")
def test_missing_config_is_reported_and_still_fails(mock_setup_logging, mock_sentry):
"""Missing required env vars are sent to Sentry and still exit non-zero."""
with patch.dict(os.environ, {}, clear=True):
with pytest.raises(SystemExit):
main.main()

mock_sentry.capture_message.assert_called_once()
assert "BIGQUERY_PROJECT" in mock_sentry.capture_message.call_args.args[0]
mock_sentry.flush.assert_called_once()


@patch("main.sentry_sdk")
@patch("main.setup_logging")
@patch("main._main", side_effect=RuntimeError("token exchange failed"))
def test_runtime_error_still_fails(mock_main, mock_setup_logging, mock_sentry):
"""A top-level RuntimeError still returns a non-zero exit code."""
assert main.main() == 1
mock_sentry.flush.assert_called_once()


class TestSetupSentry:
"""Tests for setup_sentry initialization."""

@patch("main.sentry_sdk.init")
def test_noop_without_dsn(self, mock_init):
with patch.dict(os.environ, {}, clear=True):
main.setup_sentry()
mock_init.assert_not_called()

@patch("main.sentry_sdk.init")
def test_initializes_with_dsn(self, mock_init):
dsn = "https://key@o0.ingest.sentry.io/0"
with patch.dict(os.environ, {"SENTRY_DSN": dsn}, clear=True):
main.setup_sentry()
mock_init.assert_called_once()
assert mock_init.call_args.kwargs["dsn"] == dsn


class TestResolveMaxWorkers:
"""Tests for _resolve_max_workers worker-count resolution."""

Expand Down
Loading