Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 15 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<job>`, 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://<host>/api/cron/<job>`.

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
Expand Down
8 changes: 4 additions & 4 deletions skillgraph-web/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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 <CRON_SECRET>"; 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 ───────────────────────────────────────────────
Expand Down Expand Up @@ -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=""
Expand Down
44 changes: 44 additions & 0 deletions skillgraph-web/app/api/cron/[job]/route.ts
Original file line number Diff line number Diff line change
@@ -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<string, (deadline: number) => Promise<unknown>> = {
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 })
}
}
36 changes: 4 additions & 32 deletions skillgraph-web/app/api/openclaw/integrity/route.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>()
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()
Expand Down
17 changes: 12 additions & 5 deletions skillgraph-web/lib/cron.ts
Original file line number Diff line number Diff line change
@@ -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 <CRON_SECRET>`
* 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.
Expand All @@ -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
Expand Down
5 changes: 4 additions & 1 deletion skillgraph-web/lib/openclaw/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ function startOfToday() {
return d
}

export async function processOpenClawAgent(userId: string): Promise<AgentRunResult> {
/** `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<AgentRunResult> {
const result: AgentRunResult = {
status: 'completed',
discovered: 0,
Expand Down Expand Up @@ -86,6 +87,8 @@ export async function processOpenClawAgent(userId: string): Promise<AgentRunResu

for (const listing of listings) {
if (result.prepared + result.submitted >= 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) {
Expand Down
Loading
Loading