import { Injectable, Logger, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { In, LessThan, Repository } from 'typeorm'; import { execFile } from 'child_process'; import { promisify } from 'util'; import { createHash, randomUUID } from 'crypto'; import * as path from 'path'; import * as fs from 'fs'; import { UserProfile } from '../users/entities/user-profile.entity'; import { UserGoal } from '../users/entities/user-goal.entity'; import { CampaignCandidate } from '../campaigns/entities/campaign-candidate.entity'; import { User } from '../users/user.entity'; import { QueryGeneratorService, GeneratedQueries } from './query-generator.service'; import { ScrapedJob } from './entities/scraped-job.entity'; import { Course } from './entities/course.entity'; import { UserCourse } from './entities/user-course.entity'; import { ScrapedQuery } from './entities/scraped-query.entity'; import { CachedJobQuery } from './entities/cached-job-query.entity'; import { ScrapeRun, PlatformResult } from './entities/scrape-run.entity'; import { normalizeJob, normalizeCourse, NormalizedJob, NormalizedCourse } from './normalize'; import { scoreJob, scoreCourse, RankingProfile, buildRankingProfile } from './ranking'; import { computeStarRating } from './course-rating'; import { LinkVerifierService } from './link-verifier.service'; const execFileAsync = promisify(execFile); const COURSE_PLATFORMS = ['edx', 'youtube']; // Whole-board remote sources (Himalayas/Remotive/Jobicy/Arbeitnow/RemoteOK) and // the per-company ATS aggregator (Greenhouse+Lever) all conform to the same CLI // contract as adzuna/jsearch (--queries/--output/--mode) and emit the same // normalized-raw fields, so they slot straight into the existing ingest path and // every UI filter applies to them unchanged. const JOB_PLATFORMS = [ 'rozee', 'adzuna', 'jsearch', 'himalayas', 'remotive', 'jobicy', 'arbeitnow', 'remoteok', 'ats', 'workingnomads', 'weworkremotely', ]; // TOTAL feed cap per scrape, across EVERY source (adzuna/jsearch/rozee AND the // remote boards). Only the highest match-scored jobs are kept, so with the // Anywhere ranking boost the feed leans toward reachable remote roles. Previously // only the remote sources were capped and Adzuna was uncapped — which flooded the // feed (301 Adzuna jobs) and burnt Adzuna quota keeping jobs that get dropped. const FEED_CAP_ONBOARD = 50; // a new person onboarding / new profile const FEED_CAP_SEARCH = 20; // manual "search jobs" button (custom search) const FEED_CAP_REFRESH = 10; // nightly cron + login refresh (the fresh delta) type ScoredJob = NormalizedJob & { userId: string; matchScore: number }; // Scrapers that accept --filters and push them into a board API. rozee and the // whole-board remote sources have no such API params (they filter role-relevance // locally; all field filters run at read-time), so they keep the plain arg list. const FILTER_AWARE_PLATFORMS = ['adzuna', 'jsearch']; // Courses don't churn like job postings — a query scraped within this window is // reused (its pooled courses are linked to the new user) with no subprocess. const COURSE_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000; /** * Job results are cached for hours, not weeks. Long enough that a burst of * users with the same generated queries costs one set of API calls instead of * N; short enough that nobody is shown a vacancy that has already been filled. * * Deliberately shorter than the 24h gap between nightly refreshes, so a user's * own run never serves them yesterday's cached copy of their own feed. */ const JOB_CACHE_TTL_MS = 12 * 60 * 60 * 1000; /** * How stale a returning user's feed may be before a login triggers a refresh. * Also the floor on how often that path can fire, so polling the app cannot * spend job-board quota. */ const FEED_STALE_AFTER_MS = 24 * 60 * 60 * 1000; export interface ScraperRunResult { userId: string; runId: string; status: 'success' | 'partial' | 'failed'; jobs_found: number; jobs_from_cache: number; courses_found: number; courses_from_cache: number; platforms_scraped: string[]; errors: string[]; } /** * The filter set the user has on screen, pushed down into the job-board APIs so * the boards do the narrowing. Previously these existed only as a Postgres * WHERE clause over an already-scraped pool, which meant filtering for anything * the profile-based scrape hadn't happened to collect returned nothing. * * Whatever a board can't express natively is folded into the query text or left * to the existing Postgres pass (see job_filters.py). */ export interface ScrapeFilters { country?: string; location?: string; job_type?: string; experience_level?: string; category?: string; salary_min?: number; salary_max?: number; // Eligibility: not a board-API param, but honoured at ingest for a custom // search so "Search the web" with an Anywhere/Country-restricted filter only // adds jobs of that kind, instead of dumping mixed results the read filter hides. geo_restriction?: string; } const FILTER_KEYS: (keyof ScrapeFilters)[] = [ 'country', 'location', 'job_type', 'experience_level', 'category', 'salary_min', 'salary_max', 'geo_restriction', ]; /** * Does a normalized job satisfy the user's on-screen filters? Mirrors the * read-time SQL in jobs.service (substring match on the display fields, numeric * salary), and is applied at INGEST for a custom search so the search targets the * filters across ALL sources — including the remote boards, which have no API * filter params. Country/location are intentionally skipped: country is * auto-filled from the profile and would wrongly exclude remote jobs (which carry * no country), and the read path still applies an explicit country filter. */ export function jobMatchesFilters(j: NormalizedJob, f: ScrapeFilters): boolean { const has = (field: string, val?: string) => !val || (field || '').toLowerCase().includes(val.toLowerCase()); if (!has(j.jobType, f.job_type)) return false; if (!has(j.experienceLevel, f.experience_level)) return false; if (!has(j.category, f.category)) return false; if (!has(j.geoRestriction, f.geo_restriction)) return false; if (f.salary_min && !(j.salaryMinValue !== null && j.salaryMinValue >= f.salary_min)) return false; if (f.salary_max && !(j.salaryMaxValue !== null && j.salaryMaxValue <= f.salary_max)) return false; return true; } /** Drop empty/unknown keys so `--filters {}` means "unfiltered" all the way down. */ export function cleanFilters(filters?: ScrapeFilters | null): ScrapeFilters { if (!filters) return {}; const out: ScrapeFilters = {}; for (const key of FILTER_KEYS) { const value = filters[key]; if (value !== undefined && value !== null && value !== '') (out as any)[key] = value; } return out; } /** * A country picked in the UI always wins; the profile's location is only a * fallback for triggers that carry no filters at all (nightly refresh, cached * -query reuse). Applied centrally because those two paths both used to omit it * and silently searched JSearch's hardcoded `pk` default for every user. */ export function withProfileCountry( filters: ScrapeFilters, profileLocation?: string | null, ): ScrapeFilters { if (filters.country) return filters; return cleanFilters({ ...filters, country: profileLocation || undefined }); } export interface CustomSearchJob { jobId: string; /** Owner of the search — polling is refused for anyone else. */ userId: string; status: 'running' | 'done' | 'failed'; result?: ScraperRunResult; error?: string; query: string; filters: ScrapeFilters; startedAt: number; } const CUSTOM_SEARCH_TTL_MS = 60 * 60 * 1000; // keep finished jobs pollable for 1h function normalizeQueryText(q: string): string { return (q || '').toLowerCase().replace(/\s+/g, ' ').trim(); } @Injectable() export class ScraperService { private readonly logger = new Logger(ScraperService.name); private readonly scrapersDir = path.join(__dirname, '../../../src/scrapers'); private readonly dataDir = path.join(__dirname, '../../../src/data'); private readonly venvPython = (process.env.SCRAPER_PYTHON_PATH || '').trim() || (process.platform === 'win32' ? path.join(__dirname, '../../../src/scrapers/venv/Scripts/python.exe') : path.join(__dirname, '../../../src/scrapers/venv/bin/python3')); constructor( @InjectRepository(User) private userRepository: Repository, @InjectRepository(UserProfile) private userProfileRepository: Repository, @InjectRepository(UserGoal) private userGoalRepository: Repository, @InjectRepository(CampaignCandidate) private campaignCandidateRepository: Repository, @InjectRepository(ScrapedJob) private jobRepository: Repository, @InjectRepository(Course) private courseRepository: Repository, @InjectRepository(UserCourse) private userCourseRepository: Repository, @InjectRepository(ScrapedQuery) private scrapedQueryRepository: Repository, @InjectRepository(CachedJobQuery) private cachedJobQueryRepository: Repository, @InjectRepository(ScrapeRun) private runRepository: Repository, private readonly queryGenerator: QueryGeneratorService, private readonly linkVerifier: LinkVerifierService, ) {} /** * Register this user's live apply URLs for liveness verification, then hand off * to the async worker. Fire-and-forget on purpose: link checking must never * slow a scrape or block the response. `markPending` only inserts URLs we don't * already track, so re-runs are cheap and never reset a known verdict. */ private enqueueLinkChecks(userId: string): void { void (async () => { try { const rows = await this.jobRepository.find({ where: { userId, expired: false }, select: ['applyUrl'], }); await this.linkVerifier.markPending(rows.map(r => r.applyUrl)); } catch (e) { this.logger.warn(`enqueueLinkChecks failed for ${userId}: ${e}`); } })(); } // In-flight and recently-finished custom searches, polled by the frontend. // Single-instance deployment (HF Space) → in-memory is sufficient; the final // ScrapeRun is still persisted, so history survives a restart even if the // transient job status does not. private readonly customSearches = new Map(); // ─── Kick off a custom search in the background, return a pollable job id ──── startCustomSearch( userId: string, query: string, type: 'jobs' | 'courses' | 'both' = 'both', filters?: ScrapeFilters, ): CustomSearchJob { this.pruneCustomSearches(); const jobId = randomUUID(); const clean = cleanFilters(filters); const job: CustomSearchJob = { jobId, userId, status: 'running', query, filters: clean, startedAt: Date.now(), }; this.customSearches.set(jobId, job); // Deliberately not awaited — the HTTP request returns immediately. this.runCustomSearch(userId, query, type, clean) .then(result => this.customSearches.set(jobId, { ...job, status: 'done', result })) .catch(err => this.customSearches.set(jobId, { ...job, status: 'failed', error: err instanceof Error ? err.message : String(err), })); return job; } /** * Look up a custom search. `userId` scopes the read to the owner — an * unknown job and someone else's job are deliberately indistinguishable so * job ids can't be probed. */ getCustomSearchStatus(jobId: string, userId: string): CustomSearchJob | null { const job = this.customSearches.get(jobId); if (!job || job.userId !== userId) return null; return job; } private pruneCustomSearches() { const cutoff = Date.now() - CUSTOM_SEARCH_TTL_MS; for (const [id, job] of this.customSearches) { if (job.status !== 'running' && job.startedAt < cutoff) this.customSearches.delete(id); } } /** * The skills this user's own applications proved they were missing. * * Every campaign application is scored against the role's stated * requirements, and the rubric already records which of them the CV did not * evidence. That answer is sitting on the candidate row, computed without a * model, and until now nothing read it back. * * Ordered by how many separate roles asked for the skill, so a gap that cost * someone four applications outranks one that appeared once. That ordering is * the whole value: "three of the jobs you applied for wanted Kubernetes" is a * reason to learn something, in a way that a generic recommendation is not. */ private async roleSkillGapsFor(userId: string): Promise { try { const rows = await this.campaignCandidateRepository.find({ where: { userId } }); const demand = new Map(); for (const row of rows) { const missing = (row.fit as { missing?: unknown } | null)?.missing; if (!Array.isArray(missing)) continue; for (const raw of missing) { if (typeof raw !== 'string') continue; const skill = raw.toLowerCase().trim(); if (skill.length < 2 || skill.length > 40) continue; demand.set(skill, (demand.get(skill) ?? 0) + 1); } } return [...demand.entries()] .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) .slice(0, 10) .map(([skill]) => skill); } catch (e) { // A feed that ranks slightly worse is a far better outcome than a scrape // that does not run. this.logger.warn(`Could not read skill gaps for ${userId}: ${(e as Error).message}`); return []; } } async runForUser(userId: string): Promise { const user = await this.userRepository.findOne({ where: { id: userId } }); if (!user) throw new NotFoundException('User not found'); const profile = await this.userProfileRepository.findOne({ where: { userId } }); if (!profile) throw new NotFoundException('User has not completed onboarding'); const goals = await this.userGoalRepository.find({ where: { userId, isActive: true }, order: { priority: 'ASC' }, }); // What the roles this person actually applied to asked for and their CV did // not show. Deterministic, already computed by the rubric at application // time, and far better grounded than a model's guess at what somebody in // their position is probably missing. const roleSkillGaps = await this.roleSkillGapsFor(userId); const fullProfile = { goals: goals.map(g => g.goalType), roleSkillGaps, careerStage: profile.careerStage, experienceLevel: profile.experienceLevel, yearsOfExperience: profile.yearsOfExperience, currentRole: profile.currentRole, targetRole: profile.targetRole, currentIndustry: profile.currentIndustry, targetIndustry: profile.targetIndustry, location: profile.location, openToRemote: profile.openToRemote, willingToRelocate: profile.willingToRelocate, skills: profile.skills, interests: profile.interests, }; // Reuse recently generated queries ONLY while the profile is unchanged — // compared by content hash, so any settings edit forces regeneration. const profileHash = createHash('sha1').update(JSON.stringify(fullProfile)).digest('hex'); const lastSaved = await this.getLatestSavedRun(userId); const ageMs = lastSaved ? Date.now() - new Date(lastSaved.createdAt).getTime() : Infinity; if (lastSaved && lastSaved.profileHash === profileHash && ageMs < 7 * 24 * 60 * 60 * 1000) { const reusable = lastSaved.generatedQueries as GeneratedQueries; // Re-apply current platform rules — saved queries may predate rule changes this.queryGenerator.enforcePlatformRules(reusable, fullProfile); this.logger.log(`Reusing saved queries for user ${userId} (profile unchanged, no Groq call)`); return this.executeScrape(userId, reusable, 'onboarding', profileHash); } this.logger.log(`Generating queries for user ${userId}${lastSaved ? ' (profile changed or queries stale)' : ''}`); const queries = await this.queryGenerator.generateQueries(fullProfile); this.logger.log(`Queries: ${JSON.stringify(queries)}`); // Country comes from the profile inside executeScrape, so every trigger // (manual, cached-query reuse, nightly refresh) gets it consistently. return this.executeScrape(userId, queries, 'onboarding', profileHash); } /** * Refresh a returning user's feed if it has gone stale. * * This is what makes it safe for the nightly cron to ignore inactive users. A * quiet user costs nothing while they are away and still opens the app to * fresh jobs, because their scrape happens on the way back in rather than * every night on the chance they return. * * Fire-and-forget: login must not block on a scrape. Rate-limited by the age * of the last run, so repeatedly logging in cannot spend quota. */ async ensureFreshFeed(userId: string): Promise { try { const lastRun = await this.runRepository.findOne({ where: { userId }, order: { createdAt: 'DESC' }, }); // Never scraped: onboarding owns the first run, not this path. if (!lastRun) return; const ageMs = Date.now() - new Date(lastRun.createdAt).getTime(); if (ageMs < FEED_STALE_AFTER_MS) return; const lastSaved = await this.getLatestSavedRun(userId); if (!lastSaved) return; this.logger.log( `Feed for ${userId} is ${Math.round(ageMs / 3_600_000)}h old: refreshing on return`, ); // Saved queries only: a returning user is never a reason to call Groq. void this.executeScrape( userId, lastSaved.generatedQueries as GeneratedQueries, 'scheduled_refresh', lastSaved.profileHash, ).catch(e => this.logger.error(`Return refresh failed for ${userId}: ${e}`)); } catch (e) { // Never let feed housekeeping break a login. this.logger.warn(`ensureFreshFeed failed for ${userId}: ${e}`); } } /** * Recompute match scores for a user's live jobs and courses against their * current profile. * * Scores are computed at ingest and frozen on the row, which is what keeps the * read path a plain indexed sort. The cost is that editing your profile used * to change nothing you could see: existing rows kept the old ranking until * they expired, up to two weeks later, so the app looked like it had ignored * the change. Rescoring is pure CPU — `scoreJob` is string matching, no API * call — so the fix is simply to redo it on demand. */ async rescoreUser(userId: string): Promise<{ jobs: number; courses: number }> { const profile = await this.userProfileRepository.findOne({ where: { userId } }); if (!profile) return { jobs: 0, courses: 0 }; // skill_gaps live on the saved query set, and course scoring leans on them. const lastSaved = await this.getLatestSavedRun(userId); const skillGaps = (lastSaved?.generatedQueries as GeneratedQueries | undefined)?.skill_gaps; const rankingProfile = buildRankingProfile(profile, skillGaps); const jobs = await this.rescoreJobs(userId, rankingProfile); const courses = await this.rescoreCourses(userId, rankingProfile); this.logger.log(`Rescored for ${userId}: ${jobs} jobs, ${courses} courses updated`); return { jobs, courses }; } private async rescoreJobs(userId: string, rankingProfile: RankingProfile | null): Promise { const rows = await this.jobRepository.find({ where: { userId, expired: false } }); let updated = 0; for (const row of rows) { // scoreJob reads the normalized shape; the entity is a superset of it. const next = scoreJob(row as unknown as NormalizedJob, rankingProfile); if (next !== row.matchScore) { await this.jobRepository.update({ id: row.id }, { matchScore: next }); updated++; } } return updated; } private async rescoreCourses(userId: string, rankingProfile: RankingProfile | null): Promise { const links = await this.userCourseRepository.find({ where: { userId } }); if (links.length === 0) return 0; const courses = await this.courseRepository.find({ where: { id: In(links.map(l => l.courseId)) }, }); const byId = new Map(courses.map(c => [c.id, c])); let updated = 0; for (const link of links) { const course = byId.get(link.courseId); if (!course) continue; const next = Math.round( scoreCourse(course as unknown as NormalizedCourse, rankingProfile, link.sourceQuery), ); if (next !== link.matchScore) { await this.userCourseRepository.update({ id: link.id }, { matchScore: next }); updated++; } } return updated; } // ─── Latest run that carries a saved query set (onboarding or refresh) ─────── async getLatestSavedRun(userId: string): Promise { const lastRun = await this.runRepository.findOne({ where: [ { userId, trigger: 'onboarding' }, { userId, trigger: 'scheduled_refresh' }, ], order: { createdAt: 'DESC' }, }); if (!lastRun?.generatedQueries) return null; const q = lastRun.generatedQueries as GeneratedQueries; if (!Array.isArray(q.job_queries) || !Array.isArray(q.course_queries)) return null; if (q.job_queries.length === 0 && q.course_queries.length === 0) return null; return lastRun; } // ─── Run custom search query (user-typed) ──────────────────────────────────── async runCustomSearch( userId: string, query: string, type: 'jobs' | 'courses' | 'both' = 'both', filters?: ScrapeFilters, ): Promise { const user = await this.userRepository.findOne({ where: { id: userId } }); if (!user) throw new NotFoundException('User not found'); const clean = cleanFilters(filters); const resolved = await this.resolveSearchQuery(userId, query, clean); this.logger.log( `Custom search for user ${userId}: "${resolved}" ` + `(raw: "${query}", type: ${type}, filters: ${JSON.stringify(clean)})`, ); const queries: GeneratedQueries = { job_queries: type !== 'courses' ? [{ query: resolved, platforms: ['adzuna', 'jsearch', 'himalayas', 'remotive', 'jobicy', 'arbeitnow', 'remoteok', 'ats', 'workingnomads', 'weworkremotely'] }] : [], course_queries: type !== 'jobs' ? [{ query: resolved, platforms: ['edx', 'youtube'] }] : [], }; return this.executeScrape(userId, queries, 'custom_search', null, clean); } /** * Decide what to actually search for when the user filtered without typing. * * The job boards need a role, not a placeholder — searching Adzuna for the * literal word "jobs" matches 189k unrelated postings, which is no more useful * than zero. Fall back to the category filter, then to the role on the user's * profile, so "Entry Level + United States" with an empty box searches for * what that person actually does. */ private async resolveSearchQuery( userId: string, query: string, filters: ScrapeFilters, ): Promise { const typed = (query || '').trim(); if (typed && typed.toLowerCase() !== 'jobs') return typed; if (filters.category) return filters.category; const profile = await this.userProfileRepository.findOne({ where: { userId } }); const role = profile?.targetRole || profile?.currentRole; if (role) return role; // No profile and nothing typed — a broad-but-real role beats a placeholder. return typed || 'software engineer'; } // ─── Core: run scrapers, ingest results, link courses per-user, record run ─── async executeScrape( userId: string, queries: GeneratedQueries, trigger: 'onboarding' | 'custom_search' | 'scheduled_refresh', profileHash: string | null = null, filters: ScrapeFilters = {}, ): Promise { const startedAt = Date.now(); // Profile drives BOTH job scoring and course scoring/linking. // (loaded below, then also used to fill in a missing country filter) const profile = await this.userProfileRepository.findOne({ where: { userId } }); const rankingProfile = buildRankingProfile(profile, queries.skill_gaps); const effectiveFilters = withProfileCountry(filters, profile?.location); // Split course queries: cache-fresh ones are linked directly (no scrape), // stale/unseen ones go to the Python scrapers. const courseGrouped = this.groupByPlatform(queries.course_queries, COURSE_PLATFORMS); const { toScrape: courseToScrape, cachedHits } = await this.partitionCourseQueriesByCache(courseGrouped); // Same idea for jobs: a platform whose whole query set was scraped recently // (by anyone) is replayed from cache instead of costing another API call. const jobGrouped = this.groupByPlatform(queries.job_queries, JOB_PLATFORMS); const { toScrape: jobToScrape, cachedPayloads } = await this.partitionJobQueriesByCache(jobGrouped, effectiveFilters); // Each scraper writes to its own temp file to avoid race conditions const tempDir = path.join(this.dataDir, 'tmp', `${userId}_${startedAt}`); fs.mkdirSync(tempDir, { recursive: true }); const platformResults: PlatformResult[] = []; try { const courseHasWork = Object.values(courseToScrape).some(list => list.length > 0); const jobHasWork = Object.values(jobToScrape).some(list => list.length > 0); const [jobPlatformResults, coursePlatformResults] = await Promise.all([ // Job filters are meaningless to the course scrapers — only the job side // gets them. jobHasWork ? this.runScrapers(jobToScrape, tempDir, 300_000, effectiveFilters) : Promise.resolve([]), courseHasWork ? this.runScrapers(courseToScrape, tempDir, 180_000) : Promise.resolve([]), ]); platformResults.push(...jobPlatformResults, ...coursePlatformResults); // For a custom search, only ingest jobs matching the user's on-screen // filters so "Search the web" targets what they asked for across EVERY // source (the remote boards can't filter at their API). Uses the user's own // filters, not the country-augmented ones. Other triggers ingest everything. const userFilters = cleanFilters(filters); const keep = trigger === 'custom_search' && Object.keys(userFilters).length > 0 ? (j: NormalizedJob) => jobMatchesFilters(j, userFilters) : undefined; // Collect scored candidates from every source (fresh + cached), then keep // only the top FEED_CAP by match score — one TOTAL cap across all sources. const freshCandidates = await this.ingestJobTempFiles(userId, tempDir, platformResults, rankingProfile, keep); // Freshly scraped job results go into the cache for whoever asks next. await this.updateJobQueryCache(jobToScrape, effectiveFilters, tempDir); // Cache hits: same normalized jobs, scored for THIS user. const cachedCandidates = await this.ingestCachedJobs(userId, cachedPayloads, rankingProfile, platformResults, keep); const feedCap = trigger === 'scheduled_refresh' ? FEED_CAP_REFRESH : trigger === 'custom_search' ? FEED_CAP_SEARCH : FEED_CAP_ONBOARD; const jobsIngested = await this.ingestCapped([...freshCandidates, ...cachedCandidates], feedCap); const jobsFromCache = 0; // cache hits now flow through the same total cap const { coursesLinked: freshlyLinked, scrapedByQuery } = await this.ingestScrapedCourses(userId, tempDir, platformResults, rankingProfile); // Record every stale query we scraped in the cache (even 0-result ones, so // a dead query isn't re-scraped for the TTL window). await this.updateQueryCache(courseToScrape, scrapedByQuery); // Cache hits: link already-pooled courses to this user with fresh scores. const coursesFromCache = await this.linkCachedCourses(userId, cachedHits, rankingProfile); const coursesIngested = freshlyLinked + coursesFromCache; const totalJobs = jobsIngested + jobsFromCache; const errors = platformResults.filter(p => p.status === 'failed').map(p => `${p.platform}: ${p.error}`); const status: ScrapeRun['status'] = errors.length > 0 && totalJobs === 0 && coursesIngested === 0 ? 'failed' : errors.length > 0 ? 'partial' : 'success'; const run = await this.runRepository.save(this.runRepository.create({ userId, trigger, queries: [ ...queries.job_queries.map(q => q.query), ...queries.course_queries.map(q => q.query), ], // Persist the full query set (incl. skill_gaps) so scheduled refreshes // skip Groq entirely and still rank courses on the same gaps. generatedQueries: trigger !== 'custom_search' ? (queries as unknown as object) : null, profileHash: trigger !== 'custom_search' ? profileHash : null, platformResults, status, jobsFound: totalJobs, coursesFound: coursesIngested, durationMs: Date.now() - startedAt, })); this.logger.log( `Scrape run ${run.id} (${trigger}) for ${userId}: ${status}: +${totalJobs} jobs ` + `(${jobsFromCache} from cache), +${coursesIngested} courses ` + `(${coursesFromCache} from cache, 0 tokens)`, ); // Queue this user's apply URLs for liveness checking (async, non-blocking). this.enqueueLinkChecks(userId); return { userId, runId: run.id, status, jobs_found: totalJobs, jobs_from_cache: jobsFromCache, courses_found: coursesIngested, courses_from_cache: coursesFromCache, platforms_scraped: platformResults.filter(p => p.status === 'success').map(p => p.platform), errors, }; } finally { fs.rmSync(tempDir, { recursive: true, force: true }); } } private groupByPlatform( queryList: { query: string; platforms: string[] }[], allowedPlatforms: string[], ): Record { const grouped: Record = {}; for (const p of allowedPlatforms) grouped[p] = []; for (const q of queryList) { for (const platform of q.platforms) { if (grouped[platform] && !grouped[platform].includes(q.query)) { grouped[platform].push(q.query); } } } return grouped; } // ─── Cache partitioning: fresh queries link pooled courses, stale ones scrape ─ private async partitionCourseQueriesByCache( grouped: Record, ): Promise<{ toScrape: Record; cachedHits: { platform: string; query: string; courseUrls: string[] }[]; }> { const toScrape: Record = {}; const cachedHits: { platform: string; query: string; courseUrls: string[] }[] = []; const freshAfter = new Date(Date.now() - COURSE_CACHE_TTL_MS); for (const [platform, queryList] of Object.entries(grouped)) { toScrape[platform] = []; for (const query of queryList) { const normalized = normalizeQueryText(query); const cached = await this.scrapedQueryRepository.findOne({ where: { platform, normalizedQuery: normalized }, }); if (cached && cached.lastScrapedAt > freshAfter && cached.courseUrls.length > 0) { cachedHits.push({ platform, query, courseUrls: cached.courseUrls }); } else { toScrape[platform].push(query); } } } return { toScrape, cachedHits }; } /** * Cache key for a platform's job scrape. * * Keyed on the whole query SET, not individual queries, because the scrapers * merge every query's results into one file per platform and only Adzuna tags * a row with the query that found it — so there is no way to attribute a * result back to a single query for the other boards. Two users share an entry * when their generated queries and filters match exactly, which is common * between similar profiles and is exactly the case worth saving. * * (Making this per-query would mean teaching every scraper to tag its output * with the source query. Worth doing later; it would raise the hit rate a lot.) */ private jobCacheKey(queries: string[], filters: ScrapeFilters): string { const normalizedQueries = queries.map(normalizeQueryText).sort().join('|'); // Filters are pushed down into the boards, so the same words with a // different country are a genuinely different result set. const filterDigest = createHash('sha1') .update(JSON.stringify( Object.keys(filters).sort().map(k => [k, (filters as any)[k]]), )) .digest('hex') .slice(0, 12); return `${normalizedQueries}::${filterDigest}`; } // ─── Cache partitioning for jobs: fresh sets replay, stale ones scrape ─────── private async partitionJobQueriesByCache( grouped: Record, filters: ScrapeFilters, ): Promise<{ toScrape: Record; cachedPayloads: { platform: string; jobs: unknown[] }[]; }> { const toScrape: Record = {}; const cachedPayloads: { platform: string; jobs: unknown[] }[] = []; const freshAfter = new Date(Date.now() - JOB_CACHE_TTL_MS); for (const [platform, queryList] of Object.entries(grouped)) { toScrape[platform] = []; if (queryList.length === 0) continue; const cacheKey = this.jobCacheKey(queryList, filters); try { const cached = await this.cachedJobQueryRepository.findOne({ where: { platform, cacheKey }, }); if (cached && cached.lastScrapedAt > freshAfter && cached.resultCount > 0) { this.logger.log( `[CACHE HIT] ${platform}: ${cached.resultCount} jobs for "${cached.queryText}" ` + `(0 API calls)`, ); cachedPayloads.push({ platform, jobs: cached.payload || [] }); continue; } } catch (e) { // A cache read failure must never stop a scrape — fall through and scrape. this.logger.warn(`Job cache lookup failed for ${platform}: ${e}`); } toScrape[platform] = queryList; } return { toScrape, cachedPayloads }; } /** * Write freshly scraped job results into the cache. Reads the same temp files * the ingest pass just consumed, so the cached payload is byte-identical to * what a live scrape would have produced. */ private async updateJobQueryCache( scraped: Record, filters: ScrapeFilters, tempDir: string, ): Promise { for (const [platform, queryList] of Object.entries(scraped)) { if (queryList.length === 0) continue; const tempFile = path.join(tempDir, `${platform}.json`); if (!fs.existsSync(tempFile)) continue; try { const data = JSON.parse(fs.readFileSync(tempFile, 'utf-8')); const jobs: unknown[] = Array.isArray(data.jobs) ? data.jobs : []; // Don't cache an empty result — a scraper that silently failed would // otherwise poison the entry for every user for the whole TTL. if (jobs.length === 0) continue; const cacheKey = this.jobCacheKey(queryList, filters); const existing = await this.cachedJobQueryRepository.findOne({ where: { platform, cacheKey }, }); if (existing) { existing.payload = jobs; existing.resultCount = jobs.length; existing.queryText = queryList.join(', ').slice(0, 200); existing.lastScrapedAt = new Date(); await this.cachedJobQueryRepository.save(existing); } else { await this.cachedJobQueryRepository.save( this.cachedJobQueryRepository.create({ platform, cacheKey, queryText: queryList.join(', ').slice(0, 200), payload: jobs, resultCount: jobs.length, }), ); } } catch (e) { this.logger.warn(`Failed to update job cache for ${platform}: ${e}`); } } } /** * Replay cached job payloads into this user's rows. Same normalization as a * live scrape, but scored against THIS user's profile — the cache stores board * results, never anyone's match score. */ private async ingestCachedJobs( userId: string, cachedPayloads: { platform: string; jobs: unknown[] }[], rankingProfile: RankingProfile | null, platformResults: PlatformResult[], keep?: (j: NormalizedJob) => boolean, ): Promise { const candidates: ScoredJob[] = []; for (const { platform, jobs: rawJobs } of cachedPayloads) { try { const normalized: NormalizedJob[] = rawJobs .map((raw: any) => normalizeJob(raw, raw.source || platform)) .filter((j: any): j is NonNullable => j !== null); (keep ? normalized.filter(keep) : normalized).forEach(j => candidates.push({ ...j, userId, matchScore: scoreJob(j, rankingProfile) })); // Surfaced in run history so a cached run isn't mistaken for a dead one. platformResults.push({ platform: `${platform} (cached)`, status: 'success', itemsFound: normalized.length, }); } catch (e) { this.logger.warn(`Failed to ingest cached jobs for ${platform}: ${e}`); } } return candidates; } /** Drop cache entries past their TTL. Called by the daily maintenance cron. */ async purgeExpiredJobQueryCache(): Promise { const res = await this.cachedJobQueryRepository.delete({ lastScrapedAt: LessThan(new Date(Date.now() - JOB_CACHE_TTL_MS)), }); return res.affected ?? 0; } // ─── Run scrapers in parallel via execFile (args array — no shell, no injection) ─ private async runScrapers( platformQueries: Record, tempDir: string, timeout: number, filters: ScrapeFilters = {}, ): Promise { // Only adzuna/jsearch read --filters; passing it to a scraper that doesn't // declare the arg would make argparse exit non-zero and fail the platform. const filtersArg = Object.keys(filters).length > 0 ? JSON.stringify(filters) : null; const tasks = Object.entries(platformQueries) .filter(([, queryList]) => queryList.length > 0) .map(async ([platform, queryList]): Promise => { const scraperFile = this.getScraperFile(platform); if (!scraperFile) return null; const tempFile = path.join(tempDir, `${platform}.json`); try { this.logger.log(`[PARALLEL] Starting ${platform} scraper (${queryList.length} queries)`); const args = [scraperFile, '--queries', queryList.join(','), '--output', tempFile, '--mode', 'append']; if (filtersArg && FILTER_AWARE_PLATFORMS.includes(platform)) { args.push('--filters', filtersArg); } const { stdout } = await execFileAsync( this.venvPython, args, { timeout, maxBuffer: 10 * 1024 * 1024 }, ); this.logger.log(`[PARALLEL] ${platform} scraper done`); const outputTail = (stdout || '').slice(-600); return { platform, status: 'success', itemsFound: 0, outputTail }; // itemsFound filled during ingestion } catch (error) { const msg = error instanceof Error ? error.message : String(error); this.logger.error(`${platform} failed: ${msg}`); return { platform, status: 'failed', itemsFound: 0, error: msg }; } }); return (await Promise.all(tasks)).filter((r): r is PlatformResult => r !== null); } // ─── Read job temp files → scored candidates (no upsert; the caller caps) ──── // Every source's jobs become candidates; the TOTAL feed cap in executeScrape // then keeps the top N across all of them. private async ingestJobTempFiles( userId: string, tempDir: string, platformResults: PlatformResult[], rankingProfile: RankingProfile | null, keep?: (j: NormalizedJob) => boolean, ): Promise { const candidates: ScoredJob[] = []; const files = fs.existsSync(tempDir) ? fs.readdirSync(tempDir).filter(f => f.endsWith('.json')) : []; for (const file of files) { const platform = path.basename(file, '.json'); try { const data = JSON.parse(fs.readFileSync(path.join(tempDir, file), 'utf-8')); const normalized: NormalizedJob[] = (Array.isArray(data.jobs) ? data.jobs : []) .map((raw: any) => normalizeJob(raw, raw.source || platform)) .filter((j: any): j is NonNullable => j !== null); // Report how many the platform actually found (pre-filter), so a platform // whose results are all filtered out isn't mistaken for a dead scraper. const pr = platformResults.find(p => p.platform === platform); if (pr) pr.itemsFound = normalized.length; // Custom-search filter: keep only jobs matching the user's on-screen filters. (keep ? normalized.filter(keep) : normalized).forEach(j => candidates.push({ ...j, userId, matchScore: scoreJob(j, rankingProfile) })); } catch (e) { this.logger.warn(`Failed to ingest job temp file ${file}: ${e}`); } } return candidates; } // ─── Cap candidates to the top `cap` by score and upsert them ──────────────── private async ingestCapped(candidates: ScoredJob[], cap: number): Promise { if (candidates.length === 0) return 0; // De-dupe by applyUrl keeping the highest score (a job can surface on several // boards), then keep only the best `cap`. const byUrl = new Map(); for (const j of candidates) { const existing = byUrl.get(j.applyUrl); if (!existing || j.matchScore > existing.matchScore) byUrl.set(j.applyUrl, j); } const top = [...byUrl.values()].sort((a, b) => b.matchScore - a.matchScore).slice(0, cap); if (top.length === 0) return 0; const res = await this.jobRepository.upsert(top, { conflictPaths: ['userId', 'applyUrl'], skipUpdateIfNoValuesChanged: true, }); return res.identifiers.filter(Boolean).length; } // ─── Ingest freshly-scraped courses: upsert global pool, link to user ──────── private async ingestScrapedCourses( userId: string, tempDir: string, platformResults: PlatformResult[], rankingProfile: RankingProfile | null, ): Promise<{ coursesLinked: number; scrapedByQuery: Map> }> { // key: `${platform}::${normalizedQuery}` → set of course URLs it produced const scrapedByQuery = new Map>(); const allRawCourses: any[] = []; const files = fs.existsSync(tempDir) ? fs.readdirSync(tempDir).filter(f => f.endsWith('.json')) : []; for (const file of files) { const platform = path.basename(file, '.json'); if (!COURSE_PLATFORMS.includes(platform)) continue; try { const data = JSON.parse(fs.readFileSync(path.join(tempDir, file), 'utf-8')); const rawCourses = Array.isArray(data.courses) ? data.courses : []; for (const raw of rawCourses) allRawCourses.push(raw); const pr = platformResults.find(p => p.platform === platform); if (pr) pr.itemsFound = rawCourses.length; } catch (e) { this.logger.warn(`Failed to read course temp file ${file}: ${e}`); } } // Normalize + record which query surfaced each course (for cache), then pool. // `sourceQueries` stays index-aligned with `normalized` (both skip nulls). const normalized: NormalizedCourse[] = []; const sourceQueries: string[] = []; for (const raw of allRawCourses) { const n = normalizeCourse(raw); if (!n) continue; const sq = String(raw.source_query || ''); normalized.push(n); sourceQueries.push(sq); const key = `${n.source}::${normalizeQueryText(sq)}`; if (!scrapedByQuery.has(key)) scrapedByQuery.set(key, new Set()); scrapedByQuery.get(key)!.add(n.courseUrl); } const coursesLinked = await this.poolAndLink( userId, normalized, rankingProfile, sourceQueries, ); this.flagSilentFailures(platformResults); return { coursesLinked, scrapedByQuery }; } // Upsert normalized courses into the global pool, then link each to the user // with a per-user match score and the query that surfaced it. `sourceQueries` // is index-aligned with `courses`. private async poolAndLink( userId: string, courses: NormalizedCourse[], rankingProfile: RankingProfile | null, sourceQueries: string[], ): Promise { if (courses.length === 0) return 0; // De-dupe by URL within this batch (same course can come from two queries). const byUrl = new Map(); const queryByUrl = new Map(); for (let i = 0; i < courses.length; i++) { const c = courses[i]; if (!byUrl.has(c.courseUrl)) byUrl.set(c.courseUrl, c); const sq = sourceQueries[i]; if (sq && !queryByUrl.has(c.courseUrl)) queryByUrl.set(c.courseUrl, sq); } const uniqueCourses = [...byUrl.values()]; // 1. Upsert into global pool with a derived star rating. await this.courseRepository.upsert( uniqueCourses.map(c => ({ courseUrl: c.courseUrl, title: c.title, instructor: c.instructor, platform: c.platform, platformLogo: c.platformLogo, category: c.category, level: c.level, duration: c.duration, price: c.price, rating: c.rating, language: c.language, description: c.description, thumbnail: c.thumbnail, scrapedAt: c.scrapedAt, source: c.source, totalVideos: c.totalVideos, totalDurationMinutes: c.totalDurationMinutes, avgVideoMinutes: c.avgVideoMinutes, viewCount: String(c.viewCount), likeCount: String(c.likeCount), lastUpdatedAt: c.lastUpdatedAt, starRating: computeStarRating(c).toFixed(1), })), { conflictPaths: ['courseUrl'], skipUpdateIfNoValuesChanged: true }, ); // 2. Resolve pooled ids (upsert identifiers are unreliable for existing rows). const pooled = await this.courseRepository.find({ where: { courseUrl: In(uniqueCourses.map(c => c.courseUrl)) }, select: ['id', 'courseUrl'], }); const idByUrl = new Map(pooled.map(p => [p.courseUrl, p.id])); // 3. Link each pooled course to the user. const links = uniqueCourses .map(c => { const courseId = idByUrl.get(c.courseUrl); if (!courseId) return null; const sourceQuery = queryByUrl.get(c.courseUrl) || ''; return { userId, courseId, matchScore: Math.round(scoreCourse(c, rankingProfile, sourceQuery)), sourceQuery, }; }) .filter((l): l is NonNullable => l !== null); if (links.length === 0) return 0; await this.userCourseRepository.upsert(links, { conflictPaths: ['userId', 'courseId'], skipUpdateIfNoValuesChanged: true, }); return links.length; } // ─── Cache hit: link already-pooled courses to a new user (0 scrape, 0 tokens) ─ private async linkCachedCourses( userId: string, cachedHits: { platform: string; query: string; courseUrls: string[] }[], rankingProfile: RankingProfile | null, ): Promise { if (cachedHits.length === 0) return 0; // Map each URL to the query that cached it (first wins). const queryByUrl = new Map(); const allUrls = new Set(); for (const hit of cachedHits) { for (const url of hit.courseUrls) { allUrls.add(url); if (!queryByUrl.has(url)) queryByUrl.set(url, hit.query); } } const pooled = await this.courseRepository.find({ where: { courseUrl: In([...allUrls]) }, }); if (pooled.length === 0) return 0; const links = pooled.map(c => { const sourceQuery = queryByUrl.get(c.courseUrl) || ''; // Reconstruct the minimal shape scoreCourse needs from the pooled row. const scored = scoreCourse( { title: c.title, description: c.description, category: c.category, level: c.level } as NormalizedCourse, rankingProfile, sourceQuery, ); return { userId, courseId: c.id, matchScore: Math.round(scored), sourceQuery }; }); await this.userCourseRepository.upsert(links, { conflictPaths: ['userId', 'courseId'], skipUpdateIfNoValuesChanged: true, }); this.logger.log(`Linked ${links.length} cached courses to ${userId} (${cachedHits.length} query hits, 0 tokens)`); return links.length; } // ─── Record scraped queries in the cache with their result URLs ────────────── private async updateQueryCache( scraped: Record, scrapedByQuery: Map>, ): Promise { for (const [platform, queryList] of Object.entries(scraped)) { for (const query of queryList) { const normalized = normalizeQueryText(query); const urls = [...(scrapedByQuery.get(`${platform}::${normalized}`) || [])]; try { const existing = await this.scrapedQueryRepository.findOne({ where: { platform, normalizedQuery: normalized }, }); if (existing) { existing.courseUrls = urls; existing.resultCount = urls.length; existing.lastScrapedAt = new Date(); await this.scrapedQueryRepository.save(existing); } else { await this.scrapedQueryRepository.save( this.scrapedQueryRepository.create({ platform, normalizedQuery: normalized, courseUrls: urls, resultCount: urls.length, }), ); } } catch (e) { this.logger.warn(`Failed to update query cache for ${platform}/${normalized}: ${e}`); } } } } // A platform that "succeeded" but produced nothing is the classic silent // failure (blocked site, missing browser, changed markup) — surface its output. private flagSilentFailures(platformResults: PlatformResult[]) { for (const pr of platformResults) { if (pr.status === 'success' && pr.itemsFound === 0) { this.logger.warn( `${pr.platform} succeeded but returned 0 items. Scraper output tail:\n${pr.outputTail || '(no output)'}`, ); } else { delete pr.outputTail; // don't persist noise for healthy platforms } } } // ─── Get Scraper File Path ─────────────────────────────────────────────────── private getScraperFile(platform: string): string | null { const map: Record = { rozee: path.join(this.scrapersDir, 'rozee.scraper.py'), adzuna: path.join(this.scrapersDir, 'adzuna.scraper.py'), jsearch: path.join(this.scrapersDir, 'jsearch.scraper.py'), himalayas: path.join(this.scrapersDir, 'himalayas.scraper.py'), remotive: path.join(this.scrapersDir, 'remotive.scraper.py'), jobicy: path.join(this.scrapersDir, 'jobicy.scraper.py'), arbeitnow: path.join(this.scrapersDir, 'arbeitnow.scraper.py'), remoteok: path.join(this.scrapersDir, 'remoteok.scraper.py'), ats: path.join(this.scrapersDir, 'ats.scraper.py'), workingnomads: path.join(this.scrapersDir, 'workingnomads.scraper.py'), weworkremotely: path.join(this.scrapersDir, 'weworkremotely.scraper.py'), edx: path.join(this.scrapersDir, 'edX_scraper.py'), youtube: path.join(this.scrapersDir, 'youtube_courses.scraper.py'), }; return map[platform] || null; } // ─── One-time migration: import old per-user JSON files into the DB ───────── async migrateLegacyFiles(): Promise<{ migratedUsers: number; jobs: number; courses: number }> { const userDataDir = path.join(this.dataDir, 'users'); if (!fs.existsSync(userDataDir)) return { migratedUsers: 0, jobs: 0, courses: 0 }; let migratedUsers = 0, jobs = 0, courses = 0; const files = fs.readdirSync(userDataDir).filter(f => f.endsWith('.json')); for (const file of files) { const userId = path.basename(file, '.json'); try { const data = JSON.parse(fs.readFileSync(path.join(userDataDir, file), 'utf-8')); const normalizedJobs = (Array.isArray(data.jobs) ? data.jobs : []) .map((raw: any) => normalizeJob(raw, raw.source || 'unknown')) .filter((j: any): j is NonNullable => j !== null); if (normalizedJobs.length > 0) { await this.jobRepository.upsert( normalizedJobs.map((j: NonNullable>) => ({ ...j, userId })), { conflictPaths: ['userId', 'applyUrl'], skipUpdateIfNoValuesChanged: true }, ); jobs += normalizedJobs.length; } const normalizedCourses = (Array.isArray(data.courses) ? data.courses : []) .map((raw: any) => normalizeCourse(raw)) .filter((c: any): c is NonNullable => c !== null); if (normalizedCourses.length > 0) { // Import legacy courses straight into the global pool + user links. // Legacy files carry no source query, so pass empty aligned strings. await this.poolAndLink(userId, normalizedCourses, null, normalizedCourses.map(() => '')); courses += normalizedCourses.length; } migratedUsers++; this.logger.log(`Migrated legacy file for user ${userId}: ${normalizedJobs.length} jobs, ${normalizedCourses.length} courses`); } catch (e) { this.logger.warn(`Failed to migrate legacy file ${file}: ${e}`); } } return { migratedUsers, jobs, courses }; } // ─── Visibility: scrape run history ────────────────────────────────────────── async getRunHistory(userId: string, limit = 20): Promise { return this.runRepository.find({ where: { userId }, order: { createdAt: 'DESC' }, take: limit, }); } }