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

Headerset #563

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,4 @@ video_cache_py3.sqlite
cache.sqlite

chefdata/
audio_cache.sqlite
Copy link
Member

Choose a reason for hiding this comment

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

This has been added in develop from your other PR - you are still committing the file itself here as well too, so that needs to be removed from the commit history.

11 changes: 11 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[[source]]
Copy link
Member

Choose a reason for hiding this comment

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

This still needs to be removed, as does the file below.

url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]

[dev-packages]

[requires]
python_version = "3.12"
20 changes: 20 additions & 0 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added audio_cache.sqlite
Binary file not shown.
1 change: 1 addition & 0 deletions ricecooker/managers/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ def get_file_diff(self, files_to_diff):
if not exists
]


def do_file_upload(self, filename):
file_data = self.file_map[filename]
if file_data.skip_upload:
Expand Down
21 changes: 20 additions & 1 deletion ricecooker/utils/downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,22 @@
}


def configure_download_session(session, user_email=None):
"""
Configure the download session with a custom User-Agent header.

Args:
session: The requests session to configure
user_email: Optional user email for User-Agent generation
"""
import ricecooker

base_agent = f"Ricecooker/{ricecooker.__version__}"
user_agent = f"{base_agent} bot ({user_email or '[email protected]'})"

session.headers.update({'User-Agent': user_agent})


USE_PYPPETEER = False

# HACK ALERT! This is to allow ArchiveDownloader to be used from within link scraping.
Expand Down Expand Up @@ -197,7 +213,7 @@ def read(


def make_request(
url, clear_cookies=False, headers=None, timeout=60, session=None, *args, **kwargs
url, clear_cookies=False, headers=None, timeout=60, session=None, user_email=None, *args, **kwargs
Copy link
Member

Choose a reason for hiding this comment

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

I don't think we need to pass this in, we instead copy the user agent from the globally configured DOWNLOAD_SESSION that should have had its user agent headers set properly. So far this PR is not doing this though, so is missing the main point of this issue.

):
sess = session or DOWNLOAD_SESSION

Expand All @@ -207,6 +223,9 @@ def make_request(
retry_count = 0
max_retries = 5
request_headers = DEFAULT_HEADERS

configure_download_session(sess, user_email)
Copy link
Member

Choose a reason for hiding this comment

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

Note, I think we should be setting this more globally on config.DOWNLOAD_SESSION, not just within the the downloader utility. While it is most acute when we are downloading HTML pages, it is better we do this more broadly.

Once we have authenticated against Studio with the token, we should be able to use the user email from there, rather than requiring it be explicitly passed in.

See here where we receive the username (which is the email address) once we have authenticated with Studio: https://github.com/learningequality/ricecooker/blob/develop/ricecooker/commands.py#L90

Once we have that information in hand, we can do the required DOWNLOAD_SESSION update.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, passing an email manually every time can be tedious. I will work on an approach and make sure that the code is more of Don't Repeat Yourself and improves overall authentication and session management. But, I would like to ask if there any specific requirements or constraints for setting the download session that I need to take care of?

Copy link
Member

Choose a reason for hiding this comment

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

Hi @Divyanshi750 - I'm sorry, I don't understand what isn't clear here - I have outlined which session and needs to be updated, and also shown where in the code this should happen.


if headers:
request_headers = copy.copy(DEFAULT_HEADERS)
request_headers.update(headers)
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"console_scripts": [
"corrections = ricecooker.utils.corrections:correctionsmain",
"jiro = ricecooker.cli:main",
"ricecooker = ricecooker.cli:main",
Copy link
Member

Choose a reason for hiding this comment

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

This doesn't need to be added.

]
},
include_package_data=True,
Expand Down
69 changes: 69 additions & 0 deletions tests/test_downloader.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import os
import unittest
import timeit
import requests
import ricecooker
import pytest

from ricecooker.utils import downloader
from ricecooker.utils.downloader import make_request
from ricecooker.utils.downloader import configure_download_session


class TestArchiver(unittest.TestCase):
Expand Down Expand Up @@ -70,3 +76,66 @@ def test_archive_path_as_relative_url(self):
link_filename, page_filename
)
assert rel_path == "../kolibri_1.2.3.png"


def test_useragent_generation():

session_no_email = requests.Session()
configure_download_session(session_no_email)
expected_no_email = f"Ricecooker/{ricecooker.__version__} bot ([email protected])"
assert session_no_email.headers['User-Agent'] == expected_no_email

session_with_email = requests.Session()
test_email = "[email protected]"
configure_download_session(session_with_email, user_email=test_email)
expected_with_email = f"Ricecooker/{ricecooker.__version__} bot ({test_email})"
assert session_with_email.headers['User-Agent'] == expected_with_email


def test_request_retry_logic():
unreliable_url = "http://non-existent-url.test"

with pytest.raises(requests.exceptions.RequestException):
make_request(
unreliable_url,
user_email="[email protected]",
timeout=1
)


def test_performance_overhead():
Copy link
Member

Choose a reason for hiding this comment

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

What is this test doing?

"""
Measure performance impact of User-Agent header generation
"""


def baseline_request():
make_request("https://example.com")


def custom_email_request():
make_request("https://example.com", user_email="[email protected]")


baseline_time = timeit.timeit(baseline_request, number=100)
custom_email_time = timeit.timeit(custom_email_request, number=100)

assert custom_email_time - baseline_time < 0.01
Copy link
Member

Choose a reason for hiding this comment

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

Why are we making assertions in the module level code? This looks like it was generated by an LLM and unthinkingly pasted in here. Please focus only on testing the code you have added around updating the user agent.



def test_useragent_content_validation():
"""
Comprehensive validation of User-Agent header contents
"""
session = requests.Session()
test_email = "[email protected]"
configure_download_session(session, user_email=test_email)

user_agent = session.headers['User-Agent']

# Validation checks
assert "Ricecooker/" in user_agent
assert ricecooker.__version__ in user_agent
assert test_email in user_agent
assert user_agent.startswith("Ricecooker/")
assert "bot" in user_agent
Loading