22Scheduler — Background scraper loop with sentiment-aware, tool-level aggregation pipeline.
33
44Flow:
5- 1. Fetch raw data from all sources (GitHub repo stats, HN, DevTo, Reddit, RSS News)
6- 2. Run batch sentiment analysis on all content via Groq LLM
7- 3. Count sentiment-weighted mentions per tool
8- 4. Fetch GitHub stats per tool (targeted, 1 API call each)
9- 5. Calculate weighted scores, growth stages, and decision intelligence
10- 6. Upsert Tool records in database
11- 7. Insert daily ToolSnapshot for time-series tracking
12- 8. Aggregate tool scores per domain
5+ 1. Validate GitHub token + check rate budget
6+ 2. Fetch raw data from all sources (GitHub repo stats, HN, DevTo, Reddit, RSS News)
7+ 3. Run batch sentiment analysis on all content via Groq LLM
8+ 4. Count sentiment-weighted mentions per tool
9+ 5. Fetch GitHub stats per tool (shared client, adaptive delays)
10+ 6. Calculate weighted scores, growth stages, and decision intelligence
11+ 7. Upsert Tool records in database
12+ 8. Insert daily ToolSnapshot for time-series tracking
13+ 9. Aggregate tool scores per domain
14+
15+ Phase 1 improvements:
16+ - Shared httpx.AsyncClient for all GitHub calls (connection pooling)
17+ - Adaptive delay between calls based on X-RateLimit-Remaining
18+ - Token validation at start of each cycle
19+ - Rate budget logging
20+
21+ Phase 4 improvements:
22+ - Fixed github_stars_delta calculation
23+ - Accumulative mention_count in daily snapshots
24+ - 7-day rolling average for growth_pct calculation
1325"""
1426
1527import asyncio
1628import logging
29+ import time
30+ import httpx
1731from datetime import datetime , timezone , timedelta , date
1832from sqlalchemy .orm import Session
33+ from sqlalchemy import func
1934from app .db .session import SessionLocal
2035from app .models .all_models import Tool , ToolSnapshot , Domain
2136from app .services .scraper import (
2237 fetch_github_repo_stats , fetch_hackernews , fetch_devto ,
2338 fetch_reddit , fetch_tech_news , batch_sentiment_analysis ,
39+ validate_github_token , _adaptive_delay , _rate_remaining , _rate_limit ,
2440)
2541from app .services .scoring import (
2642 count_weighted_mentions , calculate_tool_score , calculate_all_tool_scores ,
2743 classify_growth_stage , generate_tool_summary , TOOL_REGISTRY ,
2844 classify_trend , generate_recommendation , classify_learning_priority ,
45+ classify_text_to_tools ,
2946)
3047
3148logger = logging .getLogger (__name__ )
@@ -64,27 +81,24 @@ async def run_scraper_loop():
6481
6582async def perform_full_scrape ():
6683 """
67- Full scraping pipeline:
68- 1. Fetch community sources in parallel
69- 2. Sentiment analysis via Groq LLM
70- 3. Count sentiment-weighted mentions per tool
71- 4. Fetch GitHub stats per tool
72- 5. Calculate scores, growth, decision intelligence
73- 6. Save to DB + create daily snapshot
74- 7. Aggregate domain scores
84+ Full scraping pipeline with Phase 1 + Phase 4 hardening.
7585 """
76- import time
7786 _start = time .time ()
7887 scrape_status ["is_running" ] = True
7988 scrape_status ["start_time" ] = datetime .now (timezone .utc ).isoformat ()
80- scrape_status ["current_step" ] = "1/7 — Fetching community sources "
81- scrape_status ["errors" ] = [] # reset errors for this run
89+ scrape_status ["current_step" ] = "0/8 — Validating GitHub token "
90+ scrape_status ["errors" ] = []
8291
8392 db : Session = SessionLocal ()
8493
94+ # Shared HTTP client for all GitHub calls (Phase 1.3 — connection pooling)
95+ github_client = httpx .AsyncClient (timeout = 15.0 )
96+
8597 try :
86- # ━━━ STEP 0: Sync TOOL_REGISTRY with DB ━━━
87- logger .info ("Step 0: Syncing TOOL_REGISTRY with database..." )
98+ # ━━━ STEP 0: Validate GitHub token + sync registry ━━━
99+ logger .info ("Step 0: Validating GitHub token and syncing tool registry..." )
100+ await validate_github_token (github_client )
101+
88102 for slug , data in TOOL_REGISTRY .items ():
89103 tool = db .query (Tool ).filter_by (slug = slug ).first ()
90104 if not tool :
@@ -93,6 +107,7 @@ async def perform_full_scrape():
93107 db .commit ()
94108
95109 # ━━━ STEP 1: Fetch all community sources ━━━
110+ scrape_status ["current_step" ] = "1/8 — Fetching community sources"
96111 logger .info ("Step 1: Fetching from community sources..." )
97112
98113 hn_stories , devto_articles , reddit_posts , news_articles = await asyncio .gather (
@@ -115,13 +130,13 @@ async def perform_full_scrape():
115130 )
116131
117132 # ━━━ STEP 2: Sentiment Analysis ━━━
118- scrape_status ["current_step" ] = "2/7 — Running sentiment analysis"
133+ scrape_status ["current_step" ] = "2/8 — Running sentiment analysis"
119134 logger .info ("Step 2: Running sentiment analysis via Groq LLM..." )
120135
121136 all_content = hn_stories + devto_articles + reddit_posts + news_articles
122137 all_content = await batch_sentiment_analysis (all_content )
123138
124- # Split back into sources (they were concatenated in order)
139+ # Split back into sources
125140 hn_end = len (hn_stories )
126141 devto_end = hn_end + len (devto_articles )
127142 reddit_end = devto_end + len (reddit_posts )
@@ -145,6 +160,7 @@ async def perform_full_scrape():
145160 }
146161
147162 # ━━━ STEP 3: Count sentiment-weighted mentions per tool ━━━
163+ scrape_status ["current_step" ] = "3/8 — Counting mentions"
148164 logger .info ("Step 3: Counting sentiment-weighted mentions per tool..." )
149165
150166 all_tools = db .query (Tool ).filter (Tool .slug .in_ (TOOL_REGISTRY .keys ())).all ()
@@ -155,32 +171,38 @@ async def perform_full_scrape():
155171 reddit_weighted = count_weighted_mentions (reddit_posts , "reddit" , all_slugs )
156172 news_weighted = count_weighted_mentions (news_articles , "news" , all_slugs )
157173
158- # ━━━ STEP 4: Fetch GitHub stats per tool ━━━
159- logger .info ("Step 4: Fetching GitHub repo stats per tool..." )
174+ # ━━━ STEP 4: Fetch GitHub stats (Phase 1 — shared client + adaptive delay) ━━━
175+ scrape_status ["current_step" ] = "4/8 — Fetching GitHub stats"
176+ logger .info ("Step 4: Fetching GitHub repo stats (shared client, adaptive delays)..." )
160177
161178 github_stats : dict [str , dict ] = {}
162179 for tool in all_tools :
163180 if tool .github_repo :
164- stats = await fetch_github_repo_stats (tool .github_repo )
181+ stats = await fetch_github_repo_stats (tool .github_repo , client = github_client )
165182 if stats :
166183 github_stats [tool .slug ] = stats
167- await asyncio .sleep (0.5 )
184+
185+ # Adaptive delay (Phase 1.2)
186+ delay = _adaptive_delay ()
187+ await asyncio .sleep (delay )
168188
169189 scrape_status ["sources" ]["github_repos" ] = len (github_stats )
170- logger .info (f"GitHub: Fetched stats for { len (github_stats )} / { len (all_tools )} repos" )
190+ logger .info (
191+ f"GitHub: Fetched stats for { len (github_stats )} /{ len (all_tools )} repos "
192+ f"(rate remaining: { _rate_remaining } /{ _rate_limit } )"
193+ )
171194
172195 # ━━━ STEP 5: Calculate scores + Decision Intelligence ━━━
196+ scrape_status ["current_step" ] = "5/8 — Computing scores"
173197 logger .info ("Step 5: Computing scores, growth, and decision intelligence..." )
174198
175199 today = date .today ()
176200 tools_updated = 0
177201
178- # 5a. Count raw sentiment (positive/negative) per tool for UI badges
202+ # 5a. Count raw sentiment per tool
179203 tool_sentiment_pos : dict [str , int ] = {t .slug : 0 for t in all_tools }
180204 tool_sentiment_neg : dict [str , int ] = {t .slug : 0 for t in all_tools }
181205
182- from app .services .scoring import classify_text_to_tools
183-
184206 for item in all_content :
185207 sentiment = item .get ("sentiment" , "neutral" )
186208 title = item .get ("title" , "" )
@@ -223,10 +245,12 @@ async def perform_full_scrape():
223245 "mention_count" : hn_count + devto_count + reddit_count + news_count ,
224246 })
225247
226- # 5c. Calculate ALL scores at once (percentile-based — this fixes score compression )
248+ # 5c. Calculate ALL scores at once (percentile-based)
227249 all_scores = calculate_all_tool_scores (tool_signals )
228250
229- # 5d. Apply scores, sentiment, and decision intelligence to each tool
251+ # 5d. Apply scores, sentiment, and decision intelligence
252+ scrape_status ["current_step" ] = "6/8 — Updating tool records"
253+
230254 for i , tool in enumerate (all_tools ):
231255 slug = tool .slug
232256 gh = github_stats .get (slug , {})
@@ -240,10 +264,15 @@ async def perform_full_scrape():
240264 reddit_count = signals ["reddit_count" ]
241265 news_count = signals ["news_count" ]
242266
243- # growth (7-day rolling average for smoothness)
244- old_score = tool .score if tool .score else 0.0
245- if old_score > 0 :
246- growth_pct = round (((new_score - old_score ) / old_score ) * 100 , 1 )
267+ # Phase 4.3: 7-day rolling average growth calculation
268+ seven_days_ago = datetime .now (timezone .utc ) - timedelta (days = 7 )
269+ avg_result = db .query (func .avg (ToolSnapshot .score )).filter (
270+ ToolSnapshot .tool_id == tool .id ,
271+ ToolSnapshot .recorded_at >= seven_days_ago ,
272+ ).scalar ()
273+
274+ if avg_result and avg_result > 0 :
275+ growth_pct = round (((new_score - float (avg_result )) / float (avg_result )) * 100 , 1 )
247276 else :
248277 growth_pct = 0.0
249278
@@ -253,7 +282,7 @@ async def perform_full_scrape():
253282 learning_priority = classify_learning_priority (trend_stage )
254283 stage = classify_growth_stage (new_score )
255284
256- # Sentiment label for frontend
285+ # Sentiment label
257286 pos = tool_sentiment_pos .get (slug , 0 )
258287 neg = tool_sentiment_neg .get (slug , 0 )
259288 if pos + neg == 0 :
@@ -265,14 +294,15 @@ async def perform_full_scrape():
265294 else :
266295 sentiment_label = "mixed"
267296
268- # Sentiment score logic (from Groq)
269- # We calculate a score from -1.0 to 1.0 based on pos/neg counts.
270297 sentiment_score = 0.0
271298 if pos + neg > 0 :
272299 sentiment_score = float ((pos - neg ) / (pos + neg ))
273300
301+ # Phase 4.1: Calculate stars delta BEFORE updating tool.stars
302+ stars_delta = new_stars - (tool .stars or 0 ) if tool .stars else 0
303+
274304 # Update tool record
275- tool .github_stars = new_stars # Updated column
305+ tool .github_stars = new_stars
276306 tool .stars = new_stars
277307 tool .forks = new_forks
278308 tool .open_issues = gh .get ("open_issues" , tool .open_issues )
@@ -294,7 +324,7 @@ async def perform_full_scrape():
294324 tool .sentiment_score = sentiment_score
295325 tool .last_updated = datetime .now (timezone .utc )
296326
297- # ━━━ STEP 6 : Insert daily snapshot (upsert) ━━━
327+ # ━━━ STEP 7 : Insert daily snapshot ━━━
298328 total_mentions = hn_count + devto_count + reddit_count + news_count
299329
300330 existing_snapshot = db .query (ToolSnapshot ).filter (
@@ -304,17 +334,19 @@ async def perform_full_scrape():
304334
305335 if existing_snapshot :
306336 existing_snapshot .score = new_score
307- existing_snapshot .github_stars_delta = new_stars - existing_snapshot .github_stars_delta # Simplified tracking
308- existing_snapshot .mention_count = total_mentions
337+ # Phase 4.1: Store actual stars delta, not self-referencing subtraction
338+ existing_snapshot .github_stars_delta = stars_delta
339+ # Phase 4.2: Accumulate mentions throughout the day
340+ existing_snapshot .mention_count = (existing_snapshot .mention_count or 0 ) + total_mentions
309341 existing_snapshot .sentiment_score = sentiment_score
310342 else :
311343 snapshot = ToolSnapshot (
312344 tool_id = tool .id ,
313345 recorded_at = datetime .now (timezone .utc ),
314346 score = new_score ,
315- github_stars_delta = 0 ,
347+ github_stars_delta = stars_delta ,
316348 mention_count = total_mentions ,
317- sentiment_score = sentiment_score
349+ sentiment_score = sentiment_score ,
318350 )
319351 db .add (snapshot )
320352
@@ -328,8 +360,9 @@ async def perform_full_scrape():
328360 f"sentiment={ sentiment_label } (+{ pos } /-{ neg } )"
329361 )
330362
331- # ━━━ STEP 7: Aggregate domain scores ━━━
332- logger .info ("Step 7: Aggregating domain-level scores..." )
363+ # ━━━ STEP 8: Aggregate domain scores ━━━
364+ scrape_status ["current_step" ] = "7/8 — Aggregating domains"
365+ logger .info ("Step 8: Aggregating domain-level scores..." )
333366
334367 domains = db .query (Domain ).all ()
335368 for domain in domains :
@@ -354,7 +387,7 @@ async def perform_full_scrape():
354387 logger .info (f" { domain .name } : avg_score={ domain .score } stage={ domain .stage } " )
355388
356389 scrape_status ["tools_updated" ] = tools_updated
357- scrape_status ["current_step" ] = "7/7 — Saving to database"
390+ scrape_status ["current_step" ] = "8/8 — Saving to database"
358391 db .commit ()
359392 logger .info (f"All { tools_updated } tools updated and saved successfully!" )
360393
@@ -364,6 +397,7 @@ async def perform_full_scrape():
364397 scrape_status ["errors" ].append ({"time" : datetime .now (timezone .utc ).isoformat (), "error" : str (e )})
365398 finally :
366399 db .close ()
400+ await github_client .aclose ()
367401 scrape_status ["is_running" ] = False
368402 scrape_status ["current_step" ] = None
369403 scrape_status ["duration_seconds" ] = round (time .time () - _start , 1 )
0 commit comments