Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: respect GitHub rate limiting #377

Merged
merged 4 commits into from
Oct 31, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
18 changes: 17 additions & 1 deletion src/vunnel/providers/github/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import datetime
import logging
import os
import time
from decimal import Decimal, DecimalException

import requests
Expand All @@ -42,6 +43,9 @@
"SWIFT": "swift",
}

GITHUB_RATE_LIMIT_REMAINING_HEADER = "x-ratelimit-remaining"
GITHUB_RATE_LIMIT_RESET_HEADER = "x-ratelimit-reset"


class Parser:
def __init__( # noqa: PLR0913
Expand Down Expand Up @@ -207,9 +211,21 @@ def get_query(token, query, timeout=125, api_url="https://api.github.com/graphql
logger = logging.getLogger("get-query")

headers = {"Authorization": f"token {token}"}
logger.debug(f"downloading github advisories from {api_url}")
logger.info(f"downloading github advisories from {api_url}")

response = requests.post(api_url, json={"query": query}, timeout=timeout, headers=headers)
if GITHUB_RATE_LIMIT_REMAINING_HEADER in response.headers and GITHUB_RATE_LIMIT_RESET_HEADER in response.headers:
remaining = int(response.headers[GITHUB_RATE_LIMIT_REMAINING_HEADER])
# reset time is the time in UNIX Epoch Seconds at which
# the rate limit will reset.
reset_time = int(response.headers[GITHUB_RATE_LIMIT_RESET_HEADER])
logger.debug(f"github rate limit has {remaining} requests left {reset_time}")
if remaining < 10:
current_time = int(time.time())
sleep_time = reset_time - current_time
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should have a sensible cap here since we're sleeping based on user data (e.g. a min of 1 a max of 1 hour?)

# note that the rate limit resets 1x / hour, so this could be a long time
logger.info(f"sleeping for {sleep_time} seconds to allow GitHub rate limit to reset")
time.sleep(sleep_time)
response.raise_for_status()
if response.status_code == 200:
return response.json()
Expand Down
44 changes: 44 additions & 0 deletions tests/unit/providers/github/test_github.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

import pytest
import time
from unittest.mock import patch, Mock
from vunnel import result, workspace
from vunnel.providers.github import Config, Provider, parser
from vunnel.utils import fdb as db
Expand Down Expand Up @@ -447,6 +449,48 @@ def test_provider_schema(helpers, fake_get_query, advisories):
assert workspace.result_schemas_valid(require_entries=True)


@patch("time.sleep")
@patch("requests.post")
def test_provider_respects_github_rate_limit(mock_post, mock_sleep):
response = Mock()
in_five_seconds = int(time.time()) + 5
response.headers = {"x-ratelimit-remaining": 9, "x-ratelimit-reset": in_five_seconds}
response.status_code = 200
mock_post.return_value = response

def mock_json():
return "{}"

def mock_raise_for_status():
pass

response.json = mock_json
response.raise_for_status = mock_raise_for_status
parser.get_query("some-token", "some-query")
mock_sleep.assert_called_once()


@patch("time.sleep")
@patch("requests.post")
def test_provider_respects_github_rate_limit(mock_post, mock_sleep):
response = Mock()
in_five_seconds = int(time.time()) + 5
response.headers = {"x-ratelimit-remaining": 11, "x-ratelimit-reset": in_five_seconds}
response.status_code = 200
mock_post.return_value = response

def mock_json():
return "{}"

def mock_raise_for_status():
pass

response.json = mock_json
response.raise_for_status = mock_raise_for_status
parser.get_query("some-token", "some-query")
mock_sleep.assert_not_called()


def test_provider_via_snapshot(helpers, fake_get_query, advisories):
fake_get_query([advisories(), advisories(has_next_page=True)])
workspace = helpers.provider_workspace_helper(name=Provider.name())
Expand Down
Loading