fix(news): drop future-dated items at ingest, hide them in /api/news
wiseye.org public-affairs event listings carry pubDate 3-6 days ahead; with ORDER BY timestamp DESC they pinned the top of the feed for a week and made the news list look frozen. - PostgresPipeline drops items whose parsed publish date is >2h in the future, counts future_dated_dropped (stats + one INFO line per run). Unparseable dates keep the old behaviour (kept, timestamped now()). - GET /api/news filters timestamp > now() in the query while still returning timestamp IS NULL rows; limit/offset/domain/since unchanged. - docs/news.md documents the guard. - tests: pipeline drop/keep unit tests, API future-row exclusion + limit.
This commit is contained in:
parent
fdf5969e27
commit
c42d375d6c
5 changed files with 176 additions and 3 deletions
|
|
@ -3,10 +3,49 @@
|
|||
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
|
||||
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import psycopg2
|
||||
import os
|
||||
from scrapy.exceptions import DropItem
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# Feed items dated further ahead than this are event listings (or clock skew
|
||||
# from the source), not news. Dropping them keeps `ORDER BY timestamp DESC`
|
||||
# from pinning the top of /api/news for days. See docs/news.md.
|
||||
FUTURE_TOLERANCE = datetime.timedelta(hours=2)
|
||||
|
||||
|
||||
def _parsed_timestamp(value):
|
||||
"""Return an aware UTC datetime for an item timestamp, or None.
|
||||
|
||||
None means "could not parse" — callers must keep such items, exactly as
|
||||
before this guard existed (undated items currently get now() upstream).
|
||||
"""
|
||||
if isinstance(value, datetime.datetime):
|
||||
ts = value
|
||||
elif isinstance(value, str) and value.strip():
|
||||
try:
|
||||
ts = datetime.datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=datetime.timezone.utc)
|
||||
return ts.astimezone(datetime.timezone.utc)
|
||||
|
||||
|
||||
def is_future_dated(value, now=None, tolerance=FUTURE_TOLERANCE):
|
||||
"""True when a parsed publish timestamp is more than `tolerance` ahead."""
|
||||
ts = _parsed_timestamp(value)
|
||||
if ts is None:
|
||||
return False
|
||||
now = now or datetime.datetime.now(datetime.timezone.utc)
|
||||
return ts > now + tolerance
|
||||
|
||||
|
||||
class PostgresPipeline:
|
||||
|
||||
def __init__(self, db_config):
|
||||
|
|
@ -14,6 +53,8 @@ class PostgresPipeline:
|
|||
self.db_config = db_config
|
||||
# 2. Initialize the set here so it exists when process_item is called
|
||||
self.seen_urls = set()
|
||||
# 3. Future-dated drops, reported once per run in close_spider()
|
||||
self.future_dated_dropped = 0
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
|
|
@ -54,6 +95,12 @@ class PostgresPipeline:
|
|||
|
||||
def process_item(self, item, spider):
|
||||
url = item['url']
|
||||
if is_future_dated(item.get('timestamp')):
|
||||
self.future_dated_dropped += 1
|
||||
stats = getattr(getattr(spider, 'crawler', None), 'stats', None)
|
||||
if stats is not None:
|
||||
stats.inc_value('future_dated_dropped')
|
||||
raise DropItem(f"Future-dated item: {url}")
|
||||
if url in self.seen_urls:
|
||||
raise DropItem(f"Duplicate URL (in-memory): {url}")
|
||||
self.seen_urls.add(url)
|
||||
|
|
@ -82,6 +129,11 @@ class PostgresPipeline:
|
|||
raise
|
||||
|
||||
def close_spider(self, spider):
|
||||
if self.future_dated_dropped:
|
||||
spider.logger.info(
|
||||
"Dropped %d future-dated item(s) (>%s ahead)",
|
||||
self.future_dated_dropped, FUTURE_TOLERANCE,
|
||||
)
|
||||
self.cur.close()
|
||||
self.connection.close()
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue