diff --git a/README.md b/README.md index 081e5ed..692d664 100644 --- a/README.md +++ b/README.md @@ -136,12 +136,21 @@ npm run dev ``` Navigate to `http://localhost:3000`. -### 4. Background Workers -Requires `REDIS_URL`. Runs market-data refresh, sprint generation, monthly reports and the nightly OpenClaw preparation; exposes `GET /health` on `PORT` (default 8080). -```bash -npm run worker -``` -In production, deploy it as its own container: `docker build -f Dockerfile.worker -t skillgraph-worker .` +### 4. Scheduled jobs +In production these run on **Vercel Cron** (`skillgraph-web/vercel.json` → `GET /api/cron/`, authenticated with `CRON_SECRET`), no Redis or extra server needed. Times are IST; on the Hobby plan each job runs once a day within its hour. + +| Job | When | What it does | +|-----|------|--------------| +| `market` | daily 01:30 | Loads this week's job postings and their skills, a few roles per run until all are done | +| `billing` | daily 06:00 | Expires lapsed plans, removes abandoned checkouts, sends renewal reminders | +| `openclaw` | daily 06:30 | OpenClaw run for students with the agent switched on | +| `sprints` | daily 07:00 | Creates a sprint for students with new high-urgency gaps | +| `openclaw-dedupe` | daily 08:30 | Marks duplicate OpenClaw applications | +| `reports` | 1st of month 08:00 | Monthly readiness emails (needs SendGrid) | + +Each run stops starting new work after 4½ minutes and the next run continues. To run one by hand: `curl -H "Authorization: Bearer $CRON_SECRET" https:///api/cron/`. + +Alternatively, host the same jobs as a long-running worker (needs `REDIS_URL`, exposes `GET /health` on `PORT`): `npm run worker`, or `docker build -f Dockerfile.worker -t skillgraph-worker .`. Use one or the other, never both. ### 5. Tests ```bash diff --git a/skillgraph-web/.env.example b/skillgraph-web/.env.example index e01d3b8..bf1c9f3 100644 --- a/skillgraph-web/.env.example +++ b/skillgraph-web/.env.example @@ -16,8 +16,8 @@ CLOUDINARY_API_KEY="" CLOUDINARY_API_SECRET="" # ── Scheduled jobs ──────────────────────────────────────────────────────── -# Shared secret sent as the x-cron-secret header by your scheduler. -# Cron endpoints reject every call when this is unset. +# Vercel Cron (vercel.json) sends it as "Authorization: Bearer "; other schedulers +# may send it as the x-cron-secret header. Cron endpoints reject every call when this is unset. CRON_SECRET="" # ── Accounts, email & legal ─────────────────────────────────────────────── @@ -64,8 +64,8 @@ ADZUNA_COUNTRY="in" # Leave empty: every application then waits for the student to submit. ATS_PARTNER_KEYS="" -# ── Background worker service (npm run worker / Dockerfile.worker) ──────── -# Use rediss:// for TLS providers such as Upstash +# ── Optional worker service (npm run worker / Dockerfile.worker) ────────── +# Only if the scheduled jobs run outside Vercel Cron (never both). Use rediss:// for TLS providers REDIS_URL="" SENDGRID_API_KEY="" SENDGRID_FROM_EMAIL="" diff --git a/skillgraph-web/app/api/cron/[job]/route.ts b/skillgraph-web/app/api/cron/[job]/route.ts new file mode 100644 index 0000000..3f1144e --- /dev/null +++ b/skillgraph-web/app/api/cron/[job]/route.ts @@ -0,0 +1,44 @@ +import { NextRequest, NextResponse } from 'next/server' +import { requireCronSecret } from '@/lib/cron' +import { logger } from '@/lib/log' +import { + runBillingMaintenance, + runSprintGenerator, + runOpenClawNightly, + runOpenClawDedupe, + runMonthlyReports, + runMarketRefresh, +} from '@/lib/scheduled' + +// Vercel Hobby functions stop at 300 s; jobs stop starting new work 30 s before that +export const maxDuration = 300 +export const dynamic = 'force-dynamic' +const BUDGET_MS = 270_000 + +const JOBS: Record Promise> = { + billing: () => runBillingMaintenance(), + sprints: deadline => runSprintGenerator(deadline), + openclaw: deadline => runOpenClawNightly(deadline), + 'openclaw-dedupe': () => runOpenClawDedupe(), + reports: deadline => runMonthlyReports(deadline), + market: deadline => runMarketRefresh(deadline), +} + +// GET /api/cron/:job — called by Vercel Cron (schedules in vercel.json) with Authorization: Bearer CRON_SECRET +export async function GET(req: NextRequest, { params }: { params: Promise<{ job: string }> }) { + const denied = requireCronSecret(req) + if (denied) return denied + const { job } = await params + const run = JOBS[job] + if (!run) return NextResponse.json({ error: 'Unknown job' }, { status: 404 }) + + const started = Date.now() + try { + const result = await run(started + BUDGET_MS) + logger.info('cron.completed', { job, ms: Date.now() - started, result }) + return NextResponse.json({ job, ms: Date.now() - started, result }) + } catch (err) { + logger.error('cron.failed', { job, err }) + return NextResponse.json({ job, error: 'Job failed' }, { status: 500 }) + } +} diff --git a/skillgraph-web/app/api/openclaw/integrity/route.ts b/skillgraph-web/app/api/openclaw/integrity/route.ts index 250a9a5..97b143d 100644 --- a/skillgraph-web/app/api/openclaw/integrity/route.ts +++ b/skillgraph-web/app/api/openclaw/integrity/route.ts @@ -1,43 +1,15 @@ import { NextRequest } from 'next/server' -import { prisma } from '@/lib/prisma' import { ok, serverError } from '@/lib/api' import { requireCronSecret } from '@/lib/cron' -import { OPEN_STATUSES } from '@/lib/openclaw/status' +import { runOpenClawDedupe } from '@/lib/scheduled' -// POST /api/openclaw/integrity — daily dedup cron +// POST /api/openclaw/integrity — de-duplication for external schedulers. +// Vercel Cron runs the same job daily as GET /api/cron/openclaw-dedupe (vercel.json). export async function POST(req: NextRequest) { try { const denied = requireCronSecret(req) if (denied) return denied - - // All open applications with their listing's company and role, in one query - const apps = await prisma.openClawApplication.findMany({ - where: { status: { in: [...OPEN_STATUSES] } }, - orderBy: { appliedAt: 'asc' }, // keep the earliest entry, mark later ones as duplicates - select: { id: true, userId: true, listing: { select: { company: true, role: true } } }, - }) - - const seen = new Map() - const toMarkDup: string[] = [] - - for (const app of apps) { - const { listing } = app - const key = `${app.userId}::${listing.company.toLowerCase()}::${listing.role.toLowerCase()}` - if (seen.has(key)) { - toMarkDup.push(app.id) - } else { - seen.set(key, app.id) - } - } - - if (toMarkDup.length > 0) { - await prisma.openClawApplication.updateMany({ - where: { id: { in: toMarkDup } }, - data: { status: 'Duplicate' }, - }) - } - - return ok({ deduped: toMarkDup.length, total: apps.length }) + return ok(await runOpenClawDedupe()) } catch (err) { console.error('[openclaw/integrity]', err) return serverError() diff --git a/skillgraph-web/lib/cron.ts b/skillgraph-web/lib/cron.ts index b7c2442..91335f7 100644 --- a/skillgraph-web/lib/cron.ts +++ b/skillgraph-web/lib/cron.ts @@ -1,8 +1,15 @@ import { timingSafeEqual } from 'crypto' import { NextRequest, NextResponse } from 'next/server' +const matches = (provided: string, expected: string) => { + const a = Buffer.from(provided) + const b = Buffer.from(expected) + return a.length === b.length && timingSafeEqual(a, b) +} + /** - * Verifies the `x-cron-secret` header for scheduled-job endpoints. + * Verifies a scheduled-job call. Accepts Vercel Cron's `Authorization: Bearer ` + * and the `x-cron-secret` header used by external schedulers. * Fails closed: if CRON_SECRET is not configured, every call is rejected — * including in development, since these jobs write to whatever DATABASE_URL points at. * Returns a 401 response to send back, or null when the caller is authorised. @@ -14,10 +21,10 @@ export function requireCronSecret(req: NextRequest): NextResponse | null { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } - const provided = req.headers.get('x-cron-secret') ?? '' - const a = Buffer.from(provided) - const b = Buffer.from(expected) - if (a.length !== b.length || !timingSafeEqual(a, b)) { + const auth = req.headers.get('authorization') ?? '' + const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '' + const header = req.headers.get('x-cron-secret') ?? '' + if (!matches(bearer, expected) && !matches(header, expected)) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) } return null diff --git a/skillgraph-web/lib/openclaw/agent.ts b/skillgraph-web/lib/openclaw/agent.ts index 5fd07d7..154fcd3 100644 --- a/skillgraph-web/lib/openclaw/agent.ts +++ b/skillgraph-web/lib/openclaw/agent.ts @@ -35,7 +35,8 @@ function startOfToday() { return d } -export async function processOpenClawAgent(userId: string): Promise { +/** `deadline` (epoch ms): stop evaluating new jobs after it — scheduled runs have a time limit. */ +export async function processOpenClawAgent(userId: string, opts: { deadline?: number } = {}): Promise { const result: AgentRunResult = { status: 'completed', discovered: 0, @@ -86,6 +87,8 @@ export async function processOpenClawAgent(userId: string): Promise= remaining) break + // Scoring + tailoring one job takes up to ~30 s + if (opts.deadline && opts.deadline - Date.now() < 30_000) break // Filters first: they cost nothing and the student asked for exactly these jobs if (!checkFilters(listing, filters).ok) { diff --git a/skillgraph-web/lib/scheduled.ts b/skillgraph-web/lib/scheduled.ts new file mode 100644 index 0000000..50d194e --- /dev/null +++ b/skillgraph-web/lib/scheduled.ts @@ -0,0 +1,282 @@ +/** + * Scheduled jobs, run by Vercel Cron (app/api/cron/[job]/route.ts) or by the optional + * long-running worker (workers/index.ts). + * + * Vercel functions on the Hobby plan stop after 300 s, so every job takes a deadline and stops + * starting new work after it. Jobs are written to resume: whatever wasn't reached is picked up + * on the next run (each job only selects work that is still outstanding). + */ +import { prisma } from '@/lib/prisma' +import { PROMPTS } from '@/lib/openai' +import { generateJson } from '@/lib/ai' +import { sprintSchema, jdSkillsSchema } from '@/lib/ai/schemas' +import { processOpenClawAgent } from '@/lib/openclaw/agent' +import { OPEN_STATUSES } from '@/lib/openclaw/status' +import { PLANS, type PlanId } from '@/lib/billing/plans' +import { emailConfigured, sendEmail, escapeHtml, appUrl } from '@/lib/email' + +const DAY = 24 * 60 * 60 * 1000 +/** No deadline: the long-running worker. */ +export const NO_DEADLINE = Number.POSITIVE_INFINITY + +const timeLeft = (deadline: number) => deadline - Date.now() + +async function notify(to: string, subject: string, html: string, text: string) { + if (!emailConfigured()) return false + await sendEmail(to, subject, html, text) + return true +} + +// ── Billing maintenance: expire lapsed plans, drop abandoned checkouts, remind before renewal ── +export async function runBillingMaintenance() { + const now = new Date() + const expired = await prisma.subscription.updateMany({ + where: { status: 'active', periodEnd: { lte: now } }, + data: { status: 'expired' }, + }) + const abandoned = await prisma.subscription.deleteMany({ + where: { status: 'pending', createdAt: { lt: new Date(now.getTime() - 7 * DAY) } }, + }) + + // Remind the purchaser once, about 7 days before a period ends (only if no later period is already paid) + const ending = await prisma.subscription.findMany({ + where: { status: 'active', periodEnd: { gt: new Date(now.getTime() + 6 * DAY), lte: new Date(now.getTime() + 7 * DAY) } }, + }) + let reminded = 0 + for (const sub of ending) { + const renewed = await prisma.subscription.findFirst({ + where: { ownerType: sub.ownerType, ownerId: sub.ownerId, plan: sub.plan, status: 'active', periodStart: { gte: sub.periodEnd! } }, + select: { id: true }, + }) + if (renewed) continue + const buyer = await prisma.user.findUnique({ where: { id: sub.purchasedByUserId }, select: { email: true, name: true } }) + if (!buyer) continue + const planName = PLANS[sub.plan as PlanId]?.name ?? sub.plan + const ends = sub.periodEnd!.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata' }) + try { + const sent = await notify( + buyer.email, + `Your SkillGraph ${planName} plan ends on ${ends}`, + `

Hi ${escapeHtml(buyer.name)},

Your ${escapeHtml(planName)} plan ends on ${ends}. Renew to keep your benefits without interruption.

Renew now →

`, + `Hi ${buyer.name}, your ${planName} plan ends on ${ends}. Renew at ${appUrl('/billing')}`, + ) + if (sent) reminded++ + } catch (err) { + console.error(`[billing] reminder failed for subscription ${sub.id}:`, (err as Error).message) + } + } + return { expired: expired.count, abandonedCheckouts: abandoned.count, reminders: reminded } +} + +// ── Sprints: a 7-day sprint for students with new high-urgency gaps and no active sprint ── +export async function runSprintGenerator(deadline: number) { + const candidates = await prisma.skillGap.findMany({ + where: { urgency: 'high', closed: false, sprintGenerated: false }, + distinct: ['userId'], + select: { userId: true }, + }) + let created = 0 + let remaining = 0 + for (const { userId } of candidates) { + if (timeLeft(deadline) < 30_000) { remaining++; continue } + if (await prisma.sprint.findFirst({ where: { userId, status: 'active' }, select: { id: true } })) continue + + const [gaps, user] = await Promise.all([ + prisma.skillGap.findMany({ where: { userId, urgency: 'high', closed: false, sprintGenerated: false }, orderBy: { identifiedAt: 'desc' }, take: 3 }), + prisma.user.findUnique({ where: { id: userId }, select: { email: true, name: true, targetRole: true } }), + ]) + if (!user || gaps.length === 0) continue + + try { + const skillNames = gaps.map(g => g.missingSkill) + const dayTasks = await generateJson({ + feature: 'sprint', + system: PROMPTS.SPRINT_GENERATOR, + prompt: `Create a sprint to learn: ${skillNames.join(', ')}. Role: ${user.targetRole ?? 'Software Engineer'}.`, + schema: sprintSchema, + userId, + maxTokens: 3000, + temperature: 0.3, + }) + const weekStart = new Date() + weekStart.setDate(weekStart.getDate() - weekStart.getDay() + 1) + await prisma.$transaction([ + prisma.sprint.create({ data: { userId, weekStartDate: weekStart, dayTasks, completionPercentage: 0, skillsTargeted: skillNames, status: 'active' } }), + prisma.skillGap.updateMany({ where: { id: { in: gaps.map(g => g.id) } }, data: { sprintGenerated: true } }), + ]) + created++ + await notify( + user.email, + `Your 7-day sprint is ready, ${user.name}`, + `

Hi ${escapeHtml(user.name)},

Your learning sprint for ${escapeHtml(skillNames.join(', '))} is ready.

View your sprint →

`, + `Hi ${user.name}, your learning sprint for ${skillNames.join(', ')} is ready: ${appUrl('/sprint')}`, + ).catch(err => console.warn('[sprints] email failed:', (err as Error).message)) + } catch (err) { + console.error(`[sprints] failed for user ${userId}:`, (err as Error).message) + } + } + return { candidates: candidates.length, created, remaining } +} + +// ── OpenClaw nightly run for every student with the agent switched on ── +export async function runOpenClawNightly(deadline: number) { + const configs = await prisma.openClawConfig.findMany({ where: { isActive: true }, select: { userId: true } }) + // Random order, so a run that hits the deadline doesn't always leave out the same students + const order = configs.map(c => c.userId).sort(() => Math.random() - 0.5) + const outcome = { active: order.length, ran: 0, prepared: 0, submitted: 0, notReached: 0 } + for (const userId of order) { + // An agent run can take ~2 minutes; don't start one that can't finish + if (timeLeft(deadline) < 120_000) { outcome.notReached++; continue } + try { + const result = await processOpenClawAgent(userId, { deadline: deadline - 15_000 }) + outcome.ran++ + outcome.prepared += result.prepared + outcome.submitted += result.submitted + } catch (err) { + console.error(`[openclaw] run failed for user ${userId}:`, (err as Error).message) + } + } + return outcome +} + +// ── OpenClaw de-duplication: keep the earliest open application per student, company and role ── +export async function runOpenClawDedupe() { + const apps = await prisma.openClawApplication.findMany({ + where: { status: { in: [...OPEN_STATUSES] } }, + orderBy: { appliedAt: 'asc' }, + select: { id: true, userId: true, listing: { select: { company: true, role: true } } }, + }) + const seen = new Set() + const duplicates: string[] = [] + for (const app of apps) { + const key = `${app.userId}::${app.listing.company.toLowerCase()}::${app.listing.role.toLowerCase()}` + if (seen.has(key)) duplicates.push(app.id) + else seen.add(key) + } + if (duplicates.length) await prisma.openClawApplication.updateMany({ where: { id: { in: duplicates } }, data: { status: 'Duplicate' } }) + return { deduped: duplicates.length, total: apps.length } +} + +// ── Monthly readiness report (1st of the month) ── +export async function runMonthlyReports(deadline: number) { + if (!emailConfigured()) return { skipped: 'email is not configured' } + const users = await prisma.user.findMany({ + where: { role: 'STUDENT', readinessScore: { not: null } }, + select: { id: true, email: true, name: true, targetRole: true, readinessScore: true, readinessScorePrev: true, sprintsCompleted: true }, + }) + let sent = 0 + let remaining = 0 + for (const user of users) { + if (timeLeft(deadline) < 15_000) { remaining++; continue } + const delta = Math.round((user.readinessScore ?? 0) - (user.readinessScorePrev ?? 0)) + const sign = delta >= 0 ? '+' : '' + try { + await sendEmail( + user.email, + `Your SkillGraph monthly report: ${sign}${delta} points`, + `

Monthly readiness report

Hi ${escapeHtml(user.name)},

+

Your readiness for ${escapeHtml(user.targetRole ?? 'your target role')}:

+
  • Current score: ${Math.round(user.readinessScore ?? 0)}%
  • +
  • Change this month: ${sign}${delta} points
  • +
  • Sprints completed: ${user.sprintsCompleted}
+

See your dashboard →

`, + `Hi ${user.name}, your readiness is ${Math.round(user.readinessScore ?? 0)}% (${sign}${delta} this month). ${appUrl('/dashboard')}`, + ) + await prisma.user.update({ where: { id: user.id }, data: { readinessScorePrev: user.readinessScore } }) + sent++ + } catch (err) { + console.error(`[reports] failed for user ${user.id}:`, (err as Error).message) + } + } + return { students: users.length, sent, remaining } +} + +// ── Market data: job postings and their required skills, refreshed weekly ── +const MARKET_ROLES = [ + 'Software Development Engineer', 'Data Analyst', 'Machine Learning Engineer', + 'DevOps Engineer', 'Full Stack Developer', 'Cloud Architect', + 'Backend Developer', 'Frontend Developer', 'Data Scientist', 'Product Manager', +] +const JOBS_PER_ROLE = 30 +const EXTRACT_CONCURRENCY = 4 + +export function currentDemandWeek(now = new Date()) { + const start = new Date(now.getFullYear(), 0, 1) + return Math.ceil(((now.getTime() - start.getTime()) / 86400000 + start.getDay() + 1) / 7) +} + +async function fetchMarketJobs(role: string) { + const host = process.env.RAPIDAPI_HOST || 'jsearch.p.rapidapi.com' + const params = new URLSearchParams({ query: `${role} India`, page: '1', num_pages: '1', country: 'in' }) + const res = await fetch(`https://${host}/search?${params}`, { + headers: { 'x-rapidapi-key': process.env.RAPIDAPI_KEY!, 'x-rapidapi-host': host }, + signal: AbortSignal.timeout(20_000), + }) + if (!res.ok) throw new Error(`JSearch responded with HTTP ${res.status}`) + const body = (await res.json()) as { data?: { job_title: string; job_description?: string; employer_name: string; job_city?: string }[] } + return (body.data ?? []).slice(0, JOBS_PER_ROLE).map(job => ({ + company: job.employer_name, + location: job.job_city ?? 'India', + description: job.job_description?.slice(0, 2000) ?? '', + })) +} + +async function extractSkills(description: string): Promise { + try { + const skills = await generateJson({ + feature: 'jd_skill_extract', + system: PROMPTS.JD_SKILL_EXTRACTOR, + prompt: `Extract required skills from this job description:\n\n${description}`, + schema: jdSkillsSchema, + userId: null, + maxTokens: 500, + temperature: 0, + }) + return skills.map(s => s.trim()).filter(Boolean) + } catch (err) { + console.warn('[market] skill extraction failed:', (err as Error).message) + return [] + } +} + +/** + * Loads this week's postings role by role, skipping roles already loaded this week, so a run + * that stops at the deadline is completed by the next one. Each role is written in one + * transaction, so a role is either fully loaded or not at all. + */ +export async function runMarketRefresh(deadline: number) { + if (!process.env.RAPIDAPI_KEY) return { skipped: 'RAPIDAPI_KEY is not set' } + const week = currentDemandWeek() + const done = new Set( + (await prisma.jobPosting.findMany({ where: { demandWeek: week, source: 'jsearch' }, distinct: ['role'], select: { role: true } })).map(r => r.role), + ) + const outcome = { week, loaded: [] as string[], alreadyLoaded: done.size, remaining: 0, failed: [] as string[] } + for (const role of MARKET_ROLES) { + if (done.has(role)) continue + // ~30 skill extractions at 4 in parallel: allow about 90 s per role + if (timeLeft(deadline) < 90_000) { outcome.remaining++; continue } + try { + const jobs = await fetchMarketJobs(role) + const skills: string[][] = [] + for (let i = 0; i < jobs.length; i += EXTRACT_CONCURRENCY) { + skills.push(...(await Promise.all(jobs.slice(i, i + EXTRACT_CONCURRENCY).map(j => extractSkills(j.description))))) + } + await prisma.jobPosting.createMany({ + data: jobs.map((job, i) => ({ + company: job.company, + role, + location: job.location, + rawDescription: job.description, + requiredSkills: skills[i] ?? [], + demandWeek: week, + source: 'jsearch', + })), + }) + outcome.loaded.push(`${role} (${jobs.length})`) + } catch (err) { + outcome.failed.push(role) + console.error(`[market] ${role}:`, (err as Error).message) + } + } + return outcome +} diff --git a/skillgraph-web/proxy.ts b/skillgraph-web/proxy.ts index f77b8af..e8e62e4 100644 --- a/skillgraph-web/proxy.ts +++ b/skillgraph-web/proxy.ts @@ -7,8 +7,8 @@ import { checkRateLimit, clientIp } from '@/lib/rateLimit' const PUBLIC_PREFIXES = [ '/login', '/register', '/logout', '/forgot-password', '/reset-password', '/verify-email', '/privacy', '/terms', '/api/auth', '/api/health', '/api/stats', - // Cron target — authenticates via x-cron-secret, not a session - '/api/openclaw/integrity', + // Cron targets — authenticate with CRON_SECRET (lib/cron.ts), not a session + '/api/openclaw/integrity', '/api/cron/', // Payment provider callbacks — authenticated by HMAC signature, not a session '/api/billing/webhook', // OpenClaw browser extension — authenticated by its bearer token (lib/extension.ts) diff --git a/skillgraph-web/tests/cron.test.ts b/skillgraph-web/tests/cron.test.ts new file mode 100644 index 0000000..7bd5750 --- /dev/null +++ b/skillgraph-web/tests/cron.test.ts @@ -0,0 +1,44 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'fs' +import { NextRequest } from 'next/server' +import { requireCronSecret } from '@/lib/cron' +import { currentDemandWeek } from '@/lib/scheduled' + +const req = (headers: Record) => new NextRequest('http://localhost/api/cron/billing', { headers }) + +test('cron calls need CRON_SECRET, from Vercel Cron or an external scheduler', () => { + const previous = process.env.CRON_SECRET + try { + delete process.env.CRON_SECRET + // Fails closed when the secret isn't configured + assert.equal(requireCronSecret(req({ authorization: 'Bearer anything' }))?.status, 401) + + process.env.CRON_SECRET = 's3cret-value' + assert.equal(requireCronSecret(req({ authorization: 'Bearer s3cret-value' })), null) // Vercel Cron + assert.equal(requireCronSecret(req({ 'x-cron-secret': 's3cret-value' })), null) // external scheduler + assert.equal(requireCronSecret(req({ authorization: 'Bearer wrong' }))?.status, 401) + assert.equal(requireCronSecret(req({ authorization: 's3cret-value' }))?.status, 401) // missing "Bearer " + assert.equal(requireCronSecret(req({}))?.status, 401) + } finally { + if (previous === undefined) delete process.env.CRON_SECRET + else process.env.CRON_SECRET = previous + } +}) + +test('every Vercel cron schedule fits the Hobby plan (at most once a day) and targets a known job', () => { + const { crons } = JSON.parse(readFileSync('vercel.json', 'utf8')) as { crons: { path: string; schedule: string }[] } + const route = readFileSync('app/api/cron/[job]/route.ts', 'utf8') + for (const { path, schedule } of crons) { + const [minute, hour] = schedule.split(' ') + assert.match(minute, /^\d+$/, `${path}: minute must be fixed (${schedule})`) + assert.match(hour, /^\d+$/, `${path}: hour must be fixed (${schedule})`) + const job = path.replace('/api/cron/', '') + assert.ok(route.includes(`'${job}'`) || route.includes(` ${job}:`), `${path} is not a job in the cron route`) + } +}) + +test('market data weeks advance weekly', () => { + assert.equal(currentDemandWeek(new Date(2026, 0, 1)), 1) + assert.ok(currentDemandWeek(new Date(2026, 9, 14)) > currentDemandWeek(new Date(2026, 9, 1))) +}) diff --git a/skillgraph-web/vercel.json b/skillgraph-web/vercel.json new file mode 100644 index 0000000..17ee80b --- /dev/null +++ b/skillgraph-web/vercel.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "crons": [ + { "path": "/api/cron/market", "schedule": "0 20 * * *" }, + { "path": "/api/cron/billing", "schedule": "30 0 * * *" }, + { "path": "/api/cron/openclaw", "schedule": "0 1 * * *" }, + { "path": "/api/cron/sprints", "schedule": "30 1 * * *" }, + { "path": "/api/cron/openclaw-dedupe", "schedule": "0 3 * * *" }, + { "path": "/api/cron/reports", "schedule": "30 2 1 * *" } + ] +} diff --git a/skillgraph-web/workers/index.ts b/skillgraph-web/workers/index.ts index f1966ef..54614c9 100644 --- a/skillgraph-web/workers/index.ts +++ b/skillgraph-web/workers/index.ts @@ -1,6 +1,9 @@ /** - * SkillGraph background worker (separate service from the Next.js app — see ADR-001). - * Run with: npm run worker (tsx resolves the project's "@/..." path aliases) + * Optional long-running worker (ADR-001), for hosting the scheduled jobs outside Vercel. + * In production the same jobs run on Vercel Cron (vercel.json → app/api/cron/[job]); run this + * only if you host the jobs elsewhere instead — never both, or each job runs twice. + * + * Run with: npm run worker (tsx resolves the project's "@/..." path aliases). Needs REDIS_URL. */ import dotenv from 'dotenv' // Load .env then override with .env.local (no-ops in containers that inject env vars) @@ -9,14 +12,16 @@ dotenv.config({ path: '.env.local', override: true, quiet: true }) import http from 'http' import Queue from 'bull' -import sgMail from '@sendgrid/mail' -import { runJobScraper } from './jobScraper' import { prisma } from '../lib/prisma' -import { PROMPTS } from '../lib/openai' -import { generateJson } from '../lib/ai' -import { sprintSchema } from '../lib/ai/schemas' -import { processOpenClawAgent } from '../lib/openclaw/agent' -import { PLANS, type PlanId } from '../lib/billing/plans' +import { + NO_DEADLINE, + runBillingMaintenance, + runSprintGenerator, + runOpenClawNightly, + runOpenClawDedupe, + runMonthlyReports, + runMarketRefresh, +} from '../lib/scheduled' const redisUrl = process.env.REDIS_URL if (!redisUrl) { @@ -24,197 +29,40 @@ if (!redisUrl) { process.exit(1) } -const sendgridReady = Boolean(process.env.SENDGRID_API_KEY && process.env.SENDGRID_FROM_EMAIL) -if (sendgridReady) sgMail.setApiKey(process.env.SENDGRID_API_KEY!) - -const escapeHtml = (s: string) => - s.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!) - -async function sendEmail(to: string, subject: string, html: string) { - if (!sendgridReady) return console.warn(`[email] SendGrid not configured — skipped "${subject}" to ${to}`) - await sgMail.send({ to, from: process.env.SENDGRID_FROM_EMAIL!, subject, html }) -} - // rediss:// enables TLS with certificate verification (ioredis default); never disable verification const bullOpts: Queue.QueueOptions = { redis: { maxRetriesPerRequest: null, enableReadyCheck: false }, } -const scraperQueue = new Queue('jobScraper', redisUrl, bullOpts) -const sprintQueue = new Queue('sprints', redisUrl, bullOpts) -const reportQueue = new Queue('monthlyReports', redisUrl, bullOpts) -const openclawQueue = new Queue('openclaw', redisUrl, bullOpts) -const billingQueue = new Queue('billing', redisUrl, bullOpts) -const queues = [scraperQueue, sprintQueue, reportQueue, openclawQueue, billingQueue] - -// ── WORKER 1: Weekly market data (JSearch) ── -scraperQueue.process(async () => { - await runJobScraper() -}) - -// ── WORKER 2: Sprint Generator ── -sprintQueue.process(async () => { - const users = await prisma.skillGap.findMany({ - where: { urgency: 'high', closed: false, sprintGenerated: false }, - distinct: ['userId'], - select: { userId: true }, +// Same jobs and times as vercel.json; no deadline here, since a worker process has no time limit +const JOBS: { name: string; cron: string; run: () => Promise }[] = [ + { name: 'market', cron: '0 20 * * *', run: () => runMarketRefresh(NO_DEADLINE) }, // 01:30 IST + { name: 'billing', cron: '30 0 * * *', run: () => runBillingMaintenance() }, // 06:00 IST + { name: 'openclaw', cron: '0 1 * * *', run: () => runOpenClawNightly(NO_DEADLINE) }, // 06:30 IST + { name: 'sprints', cron: '*/5 * * * *', run: () => runSprintGenerator(NO_DEADLINE) }, // every 5 minutes + { name: 'openclaw-dedupe', cron: '0 3 * * *', run: () => runOpenClawDedupe() }, // 08:30 IST + { name: 'reports', cron: '30 2 1 * *', run: () => runMonthlyReports(NO_DEADLINE) }, // 1st of month 08:00 IST +] + +const queues = JOBS.map(job => { + const queue = new Queue(job.name, redisUrl, bullOpts) + queue.process(async () => { + const result = await job.run() + console.log(`[${job.name}]`, JSON.stringify(result)) }) - - for (const { userId } of users) { - const activeSprint = await prisma.sprint.findFirst({ where: { userId, status: 'active' } }) - if (activeSprint) continue - - const gaps = await prisma.skillGap.findMany({ - where: { userId, urgency: 'high', closed: false, sprintGenerated: false }, - orderBy: { identifiedAt: 'desc' }, - take: 3, - }) - const user = await prisma.user.findUnique({ - where: { id: userId }, - select: { email: true, name: true, targetRole: true }, - }) - if (!user || gaps.length === 0) continue - - try { - const skillNames = gaps.map(g => g.missingSkill) - const dayTasks = await generateJson({ - feature: 'sprint', - system: PROMPTS.SPRINT_GENERATOR, - prompt: `Create a sprint to learn: ${skillNames.join(', ')}. Role: ${user.targetRole ?? 'Software Engineer'}.`, - schema: sprintSchema, - userId, - maxTokens: 3000, - temperature: 0.3, - }) - const weekStart = new Date() - weekStart.setDate(weekStart.getDate() - weekStart.getDay() + 1) - - await prisma.$transaction([ - prisma.sprint.create({ - data: { userId, weekStartDate: weekStart, dayTasks, completionPercentage: 0, skillsTargeted: skillNames, status: 'active' }, - }), - prisma.skillGap.updateMany({ where: { id: { in: gaps.map(g => g.id) } }, data: { sprintGenerated: true } }), - ]) - - await sendEmail( - user.email, - `⚡ Your 7-day sprint is ready, ${user.name}!`, - `

Hi ${escapeHtml(user.name)},

Your personalised learning sprint for ${escapeHtml(skillNames.join(', '))} is ready!

View your sprint →

` - ) - console.log(`[SprintGenerator] Sprint created for user ${userId}`) - } catch (err) { - console.error(`[SprintGenerator] Error for user ${userId}:`, (err as Error).message) - } - } + queue.on('failed', (j, err) => console.error(`[${job.name}] job ${j.id} failed:`, err.message)) + return { job, queue } }) -// ── WORKER 3: Monthly Report ── -reportQueue.process(async () => { - const users = await prisma.user.findMany({ - where: { readinessScore: { not: null } }, - select: { id: true, email: true, name: true, targetRole: true, readinessScore: true, readinessScorePrev: true, sprintsCompleted: true }, - }) - - for (const user of users) { - const delta = (user.readinessScore ?? 0) - (user.readinessScorePrev ?? 0) - const sign = delta >= 0 ? '+' : '' - try { - await sendEmail( - user.email, - `📊 Your SkillGraph Monthly Report — ${sign}${Math.round(delta)}pt this month`, - ` -

Monthly Readiness Report

-

Hi ${escapeHtml(user.name)},

-

Your readiness score for ${escapeHtml(user.targetRole ?? 'your target role')}:

-
    -
  • Current score: ${Math.round(user.readinessScore ?? 0)}%
  • -
  • Change this month: ${sign}${Math.round(delta)}pt
  • -
  • Sprints completed: ${user.sprintsCompleted}
  • -
-

See full dashboard →

- ` - ) - await prisma.user.update({ where: { id: user.id }, data: { readinessScorePrev: user.readinessScore } }) - } catch (err) { - console.error(`[MonthlyReport] Error for user ${user.id}:`, (err as Error).message) - } - } -}) - -// ── WORKER 4: OpenClaw nightly assisted-apply preparation ── -openclawQueue.process(async () => { - const configs = await prisma.openClawConfig.findMany({ where: { isActive: true }, select: { userId: true } }) - console.log(`[OpenClaw] Nightly run for ${configs.length} active student(s)`) - for (const { userId } of configs) { - try { - await processOpenClawAgent(userId) - } catch (err) { - console.error(`[OpenClaw] Run failed for user ${userId}:`, (err as Error).message) - } - } -}) - -// ── WORKER 5: Billing maintenance (expiry, abandoned checkouts, renewal reminders) ── -billingQueue.process(async () => { - const now = new Date() - const expired = await prisma.subscription.updateMany({ - where: { status: 'active', periodEnd: { lte: now } }, - data: { status: 'expired' }, - }) - const abandoned = await prisma.subscription.deleteMany({ - where: { status: 'pending', createdAt: { lt: new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000) } }, - }) - - // Remind the purchaser once, 7 days before a period ends (only if no later period is already paid) - const windowStart = new Date(now.getTime() + 6 * 24 * 60 * 60 * 1000) - const windowEnd = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000) - const ending = await prisma.subscription.findMany({ - where: { status: 'active', periodEnd: { gt: windowStart, lte: windowEnd } }, - }) - let reminded = 0 - for (const sub of ending) { - const renewed = await prisma.subscription.findFirst({ - where: { ownerType: sub.ownerType, ownerId: sub.ownerId, plan: sub.plan, status: 'active', periodStart: { gte: sub.periodEnd! } }, - select: { id: true }, - }) - if (renewed) continue - const buyer = await prisma.user.findUnique({ where: { id: sub.purchasedByUserId }, select: { email: true, name: true } }) - if (!buyer) continue - const plan = PLANS[sub.plan as PlanId] - try { - await sendEmail( - buyer.email, - `Your SkillGraph ${plan?.name ?? 'plan'} ends on ${sub.periodEnd!.toLocaleDateString('en-IN')}`, - `

Hi ${escapeHtml(buyer.name)},

Your ${escapeHtml(plan?.name ?? sub.plan)} plan ends on ${sub.periodEnd!.toLocaleDateString('en-IN')}. Renew to keep your benefits without interruption.

Renew now →

` - ) - reminded++ - } catch (err) { - console.error(`[Billing] reminder failed for subscription ${sub.id}:`, (err as Error).message) - } - } - console.log(`[Billing] expired=${expired.count} abandonedCheckouts=${abandoned.count} reminders=${reminded}`) -}) - -for (const q of queues) { - q.on('failed', (job, err) => console.error(`[${q.name}] job ${job.id} failed:`, err.message)) -} - async function scheduleJobs() { - // Remove stale repeatable schedules so cron changes take effect on deploy - for (const q of queues) { - for (const r of await q.getRepeatableJobs()) await q.removeRepeatableByKey(r.key) + for (const { job, queue } of queues) { + // Remove stale repeatable schedules so cron changes take effect on deploy + for (const r of await queue.getRepeatableJobs()) await queue.removeRepeatableByKey(r.key) + await queue.add({}, { repeat: { cron: job.cron } }) } - - await scraperQueue.add({}, { repeat: { cron: '30 18 * * 6' } }) // Sunday 00:00 IST - await sprintQueue.add({}, { repeat: { cron: '*/5 * * * *' } }) // every 5 minutes - await reportQueue.add({}, { repeat: { cron: '30 2 1 * *' } }) // 1st of month 08:00 IST - await openclawQueue.add({}, { repeat: { cron: '0 1 * * *' } }) // daily 06:30 IST - await billingQueue.add({}, { repeat: { cron: '30 0 * * *' } }) // daily 06:00 IST - // Optional immediate market-data refresh (uses paid API quota) - if (process.env.RUN_SCRAPER_ON_START === 'true') await scraperQueue.add({}) - - console.log('✅ SkillGraph workers started: market data (weekly), sprints (5 min), reports (monthly), OpenClaw (daily), billing (daily)') + if (process.env.RUN_SCRAPER_ON_START === 'true') await queues.find(q => q.job.name === 'market')!.queue.add({}) + console.log(`✅ SkillGraph worker started: ${JOBS.map(j => j.name).join(', ')}`) } // ── Health endpoint for the container platform ── @@ -224,10 +72,7 @@ const server = http.createServer(async (req, res) => { res.writeHead(404).end() return } - const checks = await Promise.allSettled([ - prisma.$queryRaw`SELECT 1`, - scraperQueue.client.ping(), - ]) + const checks = await Promise.allSettled([prisma.$queryRaw`SELECT 1`, queues[0].queue.client.ping()]) const [db, redis] = checks.map(c => (c.status === 'fulfilled' ? 'ok' : 'unreachable')) const healthy = db === 'ok' && redis === 'ok' res.writeHead(healthy ? 200 : 503, { 'Content-Type': 'application/json' }) @@ -237,7 +82,7 @@ const server = http.createServer(async (req, res) => { async function shutdown(signal: string) { console.log(`${signal} received — draining workers`) server.close() - await Promise.allSettled(queues.map(q => q.close())) + await Promise.allSettled(queues.map(q => q.queue.close())) await prisma.$disconnect() process.exit(0) } diff --git a/skillgraph-web/workers/jobScraper.ts b/skillgraph-web/workers/jobScraper.ts index acd5ef0..c15a97a 100644 --- a/skillgraph-web/workers/jobScraper.ts +++ b/skillgraph-web/workers/jobScraper.ts @@ -1,100 +1,7 @@ -import axios from 'axios' -import { prisma } from '../lib/prisma' -import { PROMPTS } from '../lib/openai' -import { generateJson } from '../lib/ai' -import { jdSkillsSchema } from '../lib/ai/schemas' - /** - * Worker 1 — Weekly Job Scraper - * Runs every Sunday at 00:00 IST - * Fetches job postings from RapidAPI JSearch (licensed aggregator), extracts required skills with the LLM, - * and upserts them into the JobPostings table. + * Market-data refresh moved to lib/scheduled.ts (runMarketRefresh), shared by Vercel Cron and the + * worker. Kept as an alias for scripts that still import it. */ +import { runMarketRefresh, NO_DEADLINE } from '../lib/scheduled' -const TARGET_ROLES = [ - 'Software Development Engineer', 'Data Analyst', 'Machine Learning Engineer', - 'DevOps Engineer', 'Full Stack Developer', 'Cloud Architect', - 'Backend Developer', 'Frontend Developer', 'Data Scientist', 'Product Manager', -] - -function getCurrentWeek(): number { - const now = new Date() - const start = new Date(now.getFullYear(), 0, 1) - return Math.ceil(((now.getTime() - start.getTime()) / 86400000 + start.getDay() + 1) / 7) -} - -async function fetchJobsForRole(role: string, page: number = 1): Promise<{ title: string; description: string; company: string; location: string }[]> { - const options = { - method: 'GET', - url: `https://${process.env.RAPIDAPI_HOST}/search`, - params: { query: `${role} India`, page: String(page), num_pages: '1', country: 'in' }, - headers: { - 'x-rapidapi-key': process.env.RAPIDAPI_KEY, - 'x-rapidapi-host': process.env.RAPIDAPI_HOST, - }, - } - const response = await axios.request(options) - return (response.data?.data ?? []).map((job: { job_title: string; job_description: string; employer_name: string; job_city: string }) => ({ - title: job.job_title, - description: job.job_description?.slice(0, 2000) ?? '', - company: job.employer_name, - location: job.job_city ?? 'India', - })) -} - -async function extractSkills(description: string): Promise { - try { - const skills = await generateJson({ - feature: 'jd_skill_extract', - system: PROMPTS.JD_SKILL_EXTRACTOR, - prompt: `Extract required skills from this job description:\n\n${description}`, - schema: jdSkillsSchema, - userId: null, - maxTokens: 500, - temperature: 0, - }) - return skills.map(s => s.trim()).filter(Boolean) - } catch (err) { - console.warn('[JobScraper] skill extraction failed:', (err as Error).message) - return [] - } -} - -export async function runJobScraper() { - const week = getCurrentWeek() - console.log(`[JobScraper] Starting — Week ${week}`) - - let totalInserted = 0 - - for (const role of TARGET_ROLES) { - try { - const jobs = await fetchJobsForRole(role) - console.log(`[JobScraper] ${role}: ${jobs.length} jobs fetched`) - - for (const job of jobs.slice(0, 30)) { // cap at 30 per role to manage API quota - const requiredSkills = await extractSkills(job.description) - - await prisma.jobPosting.create({ - data: { - company: job.company, - role, - location: job.location, - rawDescription: job.description, - requiredSkills, - demandWeek: week, - source: 'jsearch', - }, - }) - totalInserted++ - } - - // Rate limit: 1 second between roles - await new Promise(r => setTimeout(r, 1000)) - } catch (err) { - console.error(`[JobScraper] Error for role ${role}:`, err) - } - } - - console.log(`[JobScraper] Done — ${totalInserted} job postings inserted for week ${week}`) -} - +export const runJobScraper = () => runMarketRefresh(NO_DEADLINE)