Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Carry the crawl time as aware UTC through the URL database and queue

claude[bot]9c127117cadc
diff --git a/docs/plans/issue-371-enable-dtz-rule.md b/docs/plans/issue-371-enable-dtz-rule.md
index 6f661d4..8881c2c 100644
--- a/docs/plans/issue-371-enable-dtz-rule.md
+++ b/docs/plans/issue-371-enable-dtz-rule.md
@@ -69,7 +69,7 @@ command-line form does *not* (Python escapes a `-W` message, so the regex never
`filterwarnings` gate alone
- `ruff check --select DTZ` count is 65 → 61
-## PR 2: Carry the crawl time as aware UTC through the URL database and queue
+## PR 2: Carry the crawl time as aware UTC through the URL database and queue (Done)
**Estimated added lines:** ~120 (20 sites across 5 files)
**Files:** mwmbl/crawler/urls.py, mwmbl/redis_url_queue.py, mwmbl/indexer/update_urls.py,
test/test_url_database.py, test/test_crawl_functional.py
diff --git a/mwmbl/crawler/urls.py b/mwmbl/crawler/urls.py
index 4ef6b3f..adcad8b 100644
--- a/mwmbl/crawler/urls.py
+++ b/mwmbl/crawler/urls.py
@@ -61,15 +61,17 @@ class URLDatabase:
self.urls = {}
def __enter__(self):
- month_date = datetime.utcnow()
+ month_date = datetime.now(timezone.utc)
for i in range(3):
# Start from current month and go back two months
- month_date = datetime(month_date.year, month_date.month, 1)
+ month_date = datetime(month_date.year, month_date.month, 1, tzinfo=timezone.utc)
urls_path = settings.URLS_BLOOM_FILTER_PATH.format(month=month_date.month, year=month_date.year)
month_date = self._construct_bloom_filter(i, month_date, urls_path)
- self._construct_bloom_filter(3, datetime(2024, 1, 1), settings.URLS_BLOOM_FILTER_FALLBACK_PATH)
+ self._construct_bloom_filter(
+ 3, datetime(2024, 1, 1, tzinfo=timezone.utc), settings.URLS_BLOOM_FILTER_FALLBACK_PATH
+ )
logger.info(f"Initialised URL crawled DB with dates {self.urls.keys()}")
return self
@@ -112,11 +114,10 @@ class URLDatabase:
# before this batch), so queue_urls treats it as never-crawled and hands
# it out again. The bloom filters only record the month, which is too
# coarse to use here: on the 31st, the start of the month is already 30
- # days ago, which is exactly the re-queue threshold. Crawl timestamps
- # are timezone-aware, while last_crawled is naive UTC everywhere else
- # (the bloom filter dates, and the comparison in queue_urls), so convert
- # it here.
- found_date = url.timestamp.astimezone(timezone.utc).replace(tzinfo=None)
+ # days ago, which is exactly the re-queue threshold. The crawl timestamp
+ # is aware UTC, and so is everything else last_crawled is compared
+ # against (the bloom filter dates, and the clock in queue_urls).
+ found_date = url.timestamp
new_urls.append(FoundURL(url.url, url.user_id_hash, url.status, url.timestamp, found_date))
return new_urls
diff --git a/mwmbl/indexer/update_urls.py b/mwmbl/indexer/update_urls.py
index 932fad8..d62a86d 100644
--- a/mwmbl/indexer/update_urls.py
+++ b/mwmbl/indexer/update_urls.py
@@ -41,11 +41,11 @@ def run(batch_cache: BatchCache, new_item_queue: RedisURLQueue, num_batches: int
def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: RedisURLQueue):
- start = datetime.utcnow()
+ start = datetime.now(timezone.utc)
# Take the approved domains from the queue rather than the database: the standalone
# crawler is the live caller of this, and it fetches them over HTTP.
blacklist_provider = get_default_blacklist_provider(new_item_queue.get_curated_domains_function)
- blacklist_retrieval_time = datetime.utcnow() - start
+ blacklist_retrieval_time = datetime.now(timezone.utc) - start
logger.info(
f"Recording URLs in database for {len(batches)} batches, blacklist provider ready "
f"in {blacklist_retrieval_time.total_seconds()} seconds"
@@ -94,7 +94,7 @@ def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: Re
for source_domain, target_domains in domain_links.items():
domain_link_db.update_domain_links(source_domain, target_domains)
- end = datetime.utcnow()
+ end = datetime.now(timezone.utc)
logger.info(f"Recorded URLs in database in {end - start}")
@@ -117,7 +117,7 @@ def add_hn_links(new_item_queue: RedisURLQueue):
f"https://news.ycombinator.com/item?id={item_id}"
for item_id in range(max_item, max_item - num_items_to_add, -1)
]
- found_urls = [FoundURL(url, "hn", URLStatus.NEW, datetime.now()) for url in urls]
+ found_urls = [FoundURL(url, "hn", URLStatus.NEW, datetime.now(timezone.utc)) for url in urls]
_add_found_urls_to_db_and_queue(found_urls, new_item_queue)
hn_count = new_item_queue.get_domain_count("news.ycombinator.com")
max_item -= num_items_to_add
@@ -166,7 +166,7 @@ if __name__ == "__main__":
redis: Redis = Redis.from_url("redis://127.0.0.1:6379", decode_responses=True)
batch_cache = BatchCache(Path(settings.DATA_PATH) / settings.BATCH_DIR_NAME)
url_queue = RedisURLQueue(redis, lambda: set())
- start_time = datetime.now()
+ start_time = datetime.now(timezone.utc)
run(batch_cache, url_queue, num_batches=500)
- end_time = datetime.now()
+ end_time = datetime.now(timezone.utc)
logger.info(f"Finished updating URLs in {end_time - start_time}")
diff --git a/mwmbl/redis_url_queue.py b/mwmbl/redis_url_queue.py
index d4c7bd9..e5b9122 100644
--- a/mwmbl/redis_url_queue.py
+++ b/mwmbl/redis_url_queue.py
@@ -1,7 +1,7 @@
import json
import math
from collections import defaultdict
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
from logging import getLogger
from random import Random
from typing import Callable
@@ -69,7 +69,7 @@ class RedisURLQueue:
with DomainLinkDatabase() as link_db:
for url in found_urls:
time_since_crawled = (
- datetime.utcnow() - url.last_crawled if url.last_crawled is not None else MAX_TIME_DELTA
+ datetime.now(timezone.utc) - url.last_crawled if url.last_crawled is not None else MAX_TIME_DELTA
)
# Skip URLs crawled in the last month
diff --git a/test/test_crawl_functional.py b/test/test_crawl_functional.py
index b5f91e9..84de41d 100644
--- a/test/test_crawl_functional.py
+++ b/test/test_crawl_functional.py
@@ -3,7 +3,7 @@ import os
import tempfile
import time
from collections import Counter
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -81,21 +81,21 @@ def sample_found_urls():
url="https://example.com/page1",
user_id_hash="test_user_hash",
status=URLStatus.NEW,
- timestamp=datetime.utcnow(),
- last_crawled=datetime.utcnow() - timedelta(days=60),
+ timestamp=datetime.now(timezone.utc),
+ last_crawled=datetime.now(timezone.utc) - timedelta(days=60),
),
FoundURL(
url="https://example.com/page2",
user_id_hash="test_user_hash",
status=URLStatus.NEW,
- timestamp=datetime.utcnow(),
- last_crawled=datetime.utcnow() - timedelta(days=90),
+ timestamp=datetime.now(timezone.utc),
+ last_crawled=datetime.now(timezone.utc) - timedelta(days=90),
),
FoundURL(
url="https://test.com/article",
user_id_hash="test_user_hash",
status=URLStatus.NEW,
- timestamp=datetime.utcnow(),
+ timestamp=datetime.now(timezone.utc),
last_crawled=None,
),
]
diff --git a/test/test_crawler_ci_options.py b/test/test_crawler_ci_options.py
index fc92de4..ba26823 100644
--- a/test/test_crawler_ci_options.py
+++ b/test/test_crawler_ci_options.py
@@ -5,7 +5,7 @@ and unable to write into the production index. These cover the three knobs that
plus the one-shot mode that turns the run into an exit code.
"""
-from datetime import datetime
+from datetime import datetime, timezone
from random import Random
from unittest.mock import MagicMock, patch
@@ -39,7 +39,7 @@ def found_url(url: str) -> FoundURL:
url=url,
user_id_hash="test_user_hash",
status=URLStatus.NEW,
- timestamp=datetime.utcnow(),
+ timestamp=datetime.now(timezone.utc),
last_crawled=None,
)
diff --git a/test/test_url_database.py b/test/test_url_database.py
index 26e987e..12fd50c 100644
--- a/test/test_url_database.py
+++ b/test/test_url_database.py
@@ -37,7 +37,7 @@ def clean_bloom_filters():
def test_crawled_url_marked_as_recently_crawled(clean_bloom_filters):
"""A first-time crawled URL should come back with last_crawled set to the crawl time."""
- crawled_at = datetime.utcnow()
+ crawled_at = datetime.now(timezone.utc)
found = FoundURL(
url="https://example.com/page",
user_id_hash="user",
@@ -54,7 +54,7 @@ def test_crawled_url_marked_as_recently_crawled(clean_bloom_filters):
def test_robots_denied_url_marked_as_recently_crawled(clean_bloom_filters):
"""A robots-denied URL must also be marked crawled so it isn't re-attempted."""
- crawled_at = datetime.utcnow()
+ crawled_at = datetime.now(timezone.utc)
found = FoundURL(
url="https://example.com/blocked",
user_id_hash="user",
@@ -75,14 +75,14 @@ def test_crawled_url_is_not_requeued(clean_bloom_filters):
url="https://crawled.example/page",
user_id_hash="user",
status=URLStatus.CRAWLED,
- timestamp=datetime.utcnow(),
+ timestamp=datetime.now(timezone.utc),
last_crawled=None,
)
new_link = FoundURL(
url="https://discovered.example/page",
user_id_hash="user",
status=URLStatus.NEW,
- timestamp=datetime.utcnow(),
+ timestamp=datetime.now(timezone.utc),
last_crawled=None,
)
@@ -101,7 +101,7 @@ def test_crawl_date_is_the_crawl_time_not_the_start_of_the_month(clean_bloom_fil
"""The bloom filters only record the month a URL was crawled in. Reporting the start
of that month as the crawl date makes a URL crawled on the 31st look 30 days old -
exactly the age at which queue_urls hands it out again."""
- crawled_at = datetime(2026, 8, 31, 12, 0, 0)
+ crawled_at = datetime(2026, 8, 31, 12, 0, 0, tzinfo=timezone.utc)
found = FoundURL(
url="https://end-of-month.example/page",
user_id_hash="user",
@@ -115,9 +115,9 @@ def test_crawl_date_is_the_crawl_time_not_the_start_of_the_month(clean_bloom_fil
assert new_urls[0].last_crawled == crawled_at
-def test_crawl_date_from_a_real_batch_timestamp_is_naive(clean_bloom_filters):
- """Batch timestamps are timezone-aware, but last_crawled is compared against a naive
- datetime.utcnow() in queue_urls, which raises if the two are mixed."""
+def test_crawl_date_from_a_real_batch_timestamp_is_aware(clean_bloom_filters):
+ """Batch timestamps are timezone-aware, and so is the clock queue_urls subtracts
+ last_crawled from: mixing an aware and a naive datetime raises."""
crawled_at = get_datetime_from_timestamp(datetime.now(timezone.utc).timestamp())
found = FoundURL(
url="https://aware.example/page",
@@ -129,8 +129,8 @@ def test_crawl_date_from_a_real_batch_timestamp_is_naive(clean_bloom_filters):
with URLDatabase() as url_db:
new_urls = url_db.update_found_urls([found])
- assert new_urls[0].last_crawled.tzinfo is None
- assert new_urls[0].last_crawled == crawled_at.replace(tzinfo=None)
+ assert new_urls[0].last_crawled.tzinfo == timezone.utc
+ assert new_urls[0].last_crawled == crawled_at
redis = fakeredis.FakeRedis(decode_responses=True)
url_queue = RedisURLQueue(redis, lambda: set(), StaticBlacklistProvider(set()))