Delete the old job code now that the tracker runs on its own
Test and deploy / test (push) Successful in 1m9s
Test and deploy / deploy (push) Successful in 1m33s

The job tracker has run from its own image at /jobs/ since 931b02c, so its
old copy here goes: the GraphQL schema, resolvers and models for
applications, references, sources, leads and the search profile; the
capture and email handlers and services; the Python posting reader, lead
scorer and email classifier; the Vue pages, stores and the capture-token
card on the Environment tab; and the userscript (nginx already redirects
its old URL to /jobs/).

The six old tables stay in the stp database: AutoMigrate never drops
anything, and dropping them is a manual step. The env variables stay in
the registry, where they already belong to the jobs service.

Docs (CLAUDE.md, DEPLOYMENT.md and the three READMEs) now describe the
site without the tracker, and DEPLOYMENT.md lists the jobs service and
./jobs-data.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 17:35:18 +01:00
co-authored by Claude Opus 5.5
parent 931b02c9e4
commit 99fe175ebf
72 changed files with 123 additions and 16046 deletions
-61
View File
@@ -1,61 +0,0 @@
package handlers
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
// REST endpoints for the job-application email pipeline: a manual
// admin-triggered sync, and the OAuth redirect target (which has to be REST
// because Microsoft redirects a browser to it).
// TriggerEmailSync backs the admin-only POST /email/sync and runs one sync
// synchronously, so the response reflects the result. If the scheduler is
// mid-sync the service refuses via TryLock and this returns 500.
func (store *Store) TriggerEmailSync(ctx *gin.Context) {
// A nil HTTPClient is the service's readiness flag — see
// services.EmailSyncService.
if store.EmailSync == nil || store.EmailSync.HTTPClient == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured or not authenticated"})
return
}
err := store.EmailSync.SyncEmails(ctx.Request.Context())
if err != nil {
log.Printf("[EmailSync] Manual sync error: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "sync failed", "details": err.Error()})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "sync completed"})
}
// CompleteEmailAuth handles Microsoft's OAuth redirect to
// GET /email/callback and stores the resulting token.
//
// The route is unauthenticated (Microsoft's redirect carries no site cookie),
// which is safe only because the code is worthless without the app's client
// secret. Note that completing auth here does not start the scheduler, which
// only checks readiness at start-up — a restart is needed for that.
func (store *Store) CompleteEmailAuth(ctx *gin.Context) {
if store.EmailSync == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured"})
return
}
code := ctx.Query("code")
if code == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "missing authorization code"})
return
}
if err := store.EmailSync.CompleteAuth(ctx.Request.Context(), code); err != nil {
log.Printf("[EmailSync] Auth completion error: %v", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "authentication failed"})
return
}
ctx.JSON(http.StatusOK, gin.H{"message": "email authentication successful"})
}
-251
View File
@@ -1,251 +0,0 @@
package handlers
import (
"context"
"errors"
"log"
"net/http"
"strings"
"time"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
)
// Job capture: the three endpoints behind vue/public/job-capture.user.js,
// which adds the posting open in the browser to the job tracker.
//
// These are REST, and token-authenticated, because the caller is a userscript
// running on someone else's origin (linkedin.com, an ATS). The auth cookies
// are SameSite=Lax and never accompany such a request, so the GraphQL
// mutations, which rely on them, are out of reach from there.
//
// The token is deliberately narrow: it opens these routes and nothing else,
// so a token leaked from the browser can add rows to the tracker and spend
// Claude calls, but cannot read the tracker, edit other data or log in.
//
// As with rowing, the Claude call lives in the Python service
// (python/app/jobs.py) and everything touching the database stays here.
const (
// jobExtractPath is internal in the same way as rowingReadPath: nginx
// refuses /py/internal/ and the route refuses anything nginx forwarded.
jobExtractPath = "/internal/jobs/extract"
// maxCaptureBody bounds a capture request. A long posting is tens of
// kilobytes of text; the userscript trims the page to maxPageRunes before
// sending, so anything near this limit is not a job page.
maxCaptureBody = 512 << 10
// maxPageRunes caps both the text sent to Claude and the description
// stored. It mirrors MAX_TEXT_CHARS in python/app/jobs.py, which rejects
// anything longer, so the cut has to happen on this side.
maxPageRunes = 40_000
)
// CaptureTokenMiddleware guards the capture routes with the token generated
// in the admin panel (services.CaptureToken), presented as
// "Authorization: Bearer <token>".
//
// Until a token has been generated the routes are off (503) rather than
// open; "no token" must never be satisfied by a request that sends none.
func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) {
if store.CaptureToken == nil {
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"})
return
}
if set, _ := store.CaptureToken.Status(); !set {
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "no capture token has been generated"})
return
}
presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ")
if !ok || !store.CaptureToken.Verify(presented) {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
ctx.Next()
}
// The three handlers below manage that token from the admin panel. They sit
// in the cookie-authenticated admin group, not behind the token: the token
// must not be able to replace itself.
func captureTokenStatus(token *services.CaptureToken) gin.H {
set, createdAt := token.Status()
if !set {
return gin.H{"set": false}
}
return gin.H{"set": true, "createdAt": createdAt}
}
// GetCaptureToken backs GET /admin/capture-token: whether a token exists and
// when it was made. The token itself is not recoverable — only its hash is
// stored.
func (store *Store) GetCaptureToken(ctx *gin.Context) {
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
}
// GenerateCaptureToken backs POST /admin/capture-token. It replaces any
// existing token, so the userscript must be reconfigured with the new one,
// and its response is the only time the token is ever sent anywhere.
func (store *Store) GenerateCaptureToken(ctx *gin.Context) {
token, createdAt, err := store.CaptureToken.Generate()
if err != nil {
log.Println("Generating capture token failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to store the token"})
return
}
// The response carries a credential; keep it out of any cache.
ctx.Header("Cache-Control", "no-store")
ctx.JSON(http.StatusOK, gin.H{"token": token, "createdAt": createdAt})
}
// RevokeCaptureToken backs DELETE /admin/capture-token, switching the capture
// routes off until a new token is generated.
func (store *Store) RevokeCaptureToken(ctx *gin.Context) {
if err := store.CaptureToken.Revoke(); err != nil {
log.Println("Revoking capture token failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to revoke the token"})
return
}
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
}
// capturedJob is the slice of an application the userscript needs back: enough
// to show "already tracked as …" and no more. The token is not meant to be
// able to read the tracker, so notes and the description stay out of it.
type capturedJob struct {
ID uint `json:"id"`
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Status string `json:"status"`
}
func capturedJobOf(app *models.JobApplication) *capturedJob {
return &capturedJob{ID: app.ID, JobTitle: app.JobTitle, Company: app.Company, Status: app.Status}
}
// JobCaptureStatus backs GET /jobs/capture/status?url=. It is what lets the
// userscript show a posting's tracked status instead of an "add" button.
func (store *Store) JobCaptureStatus(ctx *gin.Context) {
raw := ctx.Query("url")
canonical, ok := services.CanonicalJobURL(raw)
if !ok {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
return
}
app, err := services.FindApplicationByURL(store.DB, canonical, raw)
if err != nil {
log.Println("Job capture status lookup failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
return
}
if app == nil {
ctx.JSON(http.StatusOK, gin.H{"found": false})
return
}
ctx.JSON(http.StatusOK, gin.H{"found": true, "application": capturedJobOf(app)})
}
// ExtractedJobPosting is the JSON contract for what Claude reads off a job
// page: the body of the Python service's reply (JobPosting in
// python/app/jobs.py). Empty strings and nulls mean "not found on the page".
type ExtractedJobPosting struct {
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Location *string `json:"location"`
Notes *string `json:"notes"`
}
// extractJobPosting sends a page's text to the Python service and returns the
// fields Claude picked out. Like readRowingDisplay it is a thin wrapper over
// services.CallPython, which decides which replies are relayed (a
// *services.PythonError) and which are only logged.
func (store *Store) extractJobPosting(ctx context.Context, pageURL, title, text string) (ExtractedJobPosting, error) {
return services.CallPython[ExtractedJobPosting](ctx, store.PythonURL, jobExtractPath, struct {
URL string `json:"url"`
Title string `json:"title"`
Text string `json:"text"`
}{pageURL, title, text})
}
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
// is still valid UTF-8 for Postgres and for JSON.
func truncateRunes(s string, max int) string {
runes := []rune(s)
if len(runes) <= max {
return s
}
return string(runes[:max])
}
// bindCapture decodes a size-limited JSON body, answering 400 itself when it
// cannot.
func bindCapture(ctx *gin.Context, into any) bool {
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxCaptureBody)
if err := ctx.ShouldBindJSON(into); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return false
}
return true
}
// JobCaptureExtract backs POST /jobs/capture/extract: page text in, the
// popup's pre-filled fields out. Nothing is stored; saving is a separate
// request made once the fields have been checked by eye.
func (store *Store) JobCaptureExtract(ctx *gin.Context) {
var input struct {
URL string `json:"url"`
Title string `json:"title"`
Text string `json:"text"`
}
if !bindCapture(ctx, &input) {
return
}
text := strings.TrimSpace(input.Text)
if text == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "text is required"})
return
}
posting, err := store.extractJobPosting(ctx.Request.Context(),
truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes))
if err != nil {
log.Println("Job extract failed:", err)
var readErr *services.PythonError
if errors.As(err, &readErr) {
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.Detail})
return
}
ctx.JSON(http.StatusBadGateway, gin.H{"error": "failed to read the page"})
return
}
ctx.JSON(http.StatusOK, posting)
}
// JobCapture backs POST /jobs/capture, an upsert: a posting already in the
// tracker is updated in place rather than added again. The matching and
// merging rules are services.UpsertJobApplication's; this handler owns the
// request body and the status codes.
func (store *Store) JobCapture(ctx *gin.Context) {
var input services.JobCaptureInput
if !bindCapture(ctx, &input) {
return
}
input.Description = truncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
app, action, err := services.UpsertJobApplication(store.DB, input, time.Now())
var invalid *services.JobInputError
switch {
case errors.As(err, &invalid):
ctx.JSON(http.StatusBadRequest, gin.H{"error": invalid.Error()})
case err != nil:
log.Println("Job capture failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
case action == "created":
ctx.JSON(http.StatusCreated, gin.H{"action": action, "application": capturedJobOf(app)})
default:
ctx.JSON(http.StatusOK, gin.H{"action": action, "application": capturedJobOf(app)})
}
}
-264
View File
@@ -1,264 +0,0 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
)
// The capture handlers themselves need a database, and the only driver in
// go.mod is postgres, so what is covered here is everything around the
// queries: the token gate, the URL key that decides whether a posting is
// already tracked, the merge rule for a repeat capture, and the call to the
// Python service.
func TestCaptureTokenMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode)
serve := func(store *Store, header string) int {
r := gin.New()
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
req := httptest.NewRequest(http.MethodGet, "/x", nil)
if header != "" {
req.Header.Set("Authorization", header)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
return rec.Code
}
newToken := func() *services.CaptureToken {
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
return tok
}
// The case the middleware exists to get right: with no token generated,
// a request presenting nothing (or an empty bearer) must not get in.
t.Run("no token generated switches the routes off", func(t *testing.T) {
store := &Store{CaptureToken: newToken()}
for _, header := range []string{"", "Bearer ", "Bearer anything"} {
if got := serve(store, header); got != http.StatusServiceUnavailable {
t.Fatalf("header %q: status = %d, want 503", header, got)
}
}
})
t.Run("a store built without the token service is off too", func(t *testing.T) {
if got := serve(&Store{}, "Bearer x"); got != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", got)
}
})
store := &Store{CaptureToken: newToken()}
token, _, err := store.CaptureToken.Generate()
if err != nil {
t.Fatalf("Generate: %v", err)
}
cases := []struct {
name string
header string
want int
}{
{"the generated token is let through", "Bearer " + token, http.StatusOK},
{"a wrong token is refused", "Bearer nope", http.StatusUnauthorized},
{"no header is refused", "", http.StatusUnauthorized},
{"the bare token without the scheme is refused", token, http.StatusUnauthorized},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := serve(store, c.header); got != c.want {
t.Fatalf("status = %d, want %d", got, c.want)
}
})
}
}
// The admin endpoints, driven without the admin middleware (covered
// elsewhere): generate shows the token once, status never does, and a second
// generate or a revoke stops the first token working.
func TestCaptureTokenAdminEndpoints(t *testing.T) {
gin.SetMode(gin.TestMode)
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
store := &Store{CaptureToken: tok}
r := gin.New()
r.GET("/t", store.GetCaptureToken)
r.POST("/t", store.GenerateCaptureToken)
r.DELETE("/t", store.RevokeCaptureToken)
call := func(method string) (map[string]any, *httptest.ResponseRecorder) {
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(method, "/t", nil))
if rec.Code != http.StatusOK {
t.Fatalf("%s: status = %d, body = %s", method, rec.Code, rec.Body)
}
var out map[string]any
json.Unmarshal(rec.Body.Bytes(), &out)
return out, rec
}
if out, _ := call(http.MethodGet); out["set"] != false {
t.Fatalf("fresh status = %v", out)
}
out, rec := call(http.MethodPost)
first, _ := out["token"].(string)
if !tok.Verify(first) {
t.Fatalf("generated token %q does not verify", first)
}
if rec.Header().Get("Cache-Control") != "no-store" {
t.Fatal("the response carrying the token must not be cacheable")
}
out, _ = call(http.MethodGet)
if out["set"] != true || out["createdAt"] == nil {
t.Fatalf("status after generate = %v", out)
}
if _, leaked := out["token"]; leaked {
t.Fatal("status must never return the token")
}
call(http.MethodPost)
if tok.Verify(first) {
t.Fatal("regenerating must invalidate the previous token")
}
if out, _ := call(http.MethodDelete); out["set"] != false {
t.Fatalf("status after revoke = %v", out)
}
}
func TestTruncateRunes(t *testing.T) {
if got := truncateRunes("££££", 2); got != "££" {
t.Fatalf("got %q; the cut must fall on a rune boundary", got)
}
if got := truncateRunes("short", 10); got != "short" {
t.Fatalf("got %q", got)
}
}
func jobExtractor(t *testing.T, handler http.HandlerFunc) *Store {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
return &Store{PythonURL: srv.URL}
}
func TestExtractJobPostingRequestAndReply(t *testing.T) {
var got map[string]string
var path string
var forwarded bool
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
// As with the rowing reader, either header makes the Python route
// answer 404.
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
t.Errorf("decoding request: %v", err)
}
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": "London", "notes": null}`))
})
posting, err := store.extractJobPosting(context.Background(), "https://x.com/1", "Engineer | Acme", "page text")
if err != nil {
t.Fatalf("extractJobPosting: %v", err)
}
if posting.JobTitle != "Engineer" || posting.Company != "Acme" || posting.Location == nil || *posting.Location != "London" || posting.Notes != nil {
t.Fatalf("got %+v", posting)
}
if path != jobExtractPath {
t.Fatalf("path = %q, want %q", path, jobExtractPath)
}
if forwarded {
t.Fatal("request carried a proxy header the Python route rejects")
}
if got["url"] != "https://x.com/1" || got["title"] != "Engineer | Acme" || got["text"] != "page text" {
t.Fatalf("request body = %+v", got)
}
}
func TestExtractJobPostingErrors(t *testing.T) {
cases := []struct {
name string
status int
body string
wantDetail string // non-empty: a services.PythonError with this message
}{
{"extractor failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse the posting"}`, "failed to parse the posting"},
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
{"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
{"malformed success body", http.StatusOK, `not json`, ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(c.status)
w.Write([]byte(c.body))
})
_, err := store.extractJobPosting(context.Background(), "https://x.com/1", "t", "text")
if err == nil {
t.Fatal("expected an error")
}
var readErr *services.PythonError
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
t.Fatalf("relayed = %v, err = %v", relayed, err)
}
if readErr != nil && readErr.Detail != c.wantDetail {
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
}
})
}
}
// The extract handler runs without a database, so it can be driven whole: the
// page text must be cut to the limit the Python side enforces before it is
// forwarded, or a long page would come back as an opaque 422.
func TestJobCaptureExtractTruncatesAndRelays(t *testing.T) {
gin.SetMode(gin.TestMode)
var forwardedLen int
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
var body map[string]string
json.NewDecoder(r.Body).Decode(&body)
forwardedLen = len([]rune(body["text"]))
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": null, "notes": null}`))
})
r := gin.New()
r.POST("/extract", store.JobCaptureExtract)
post := func(body string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/extract", strings.NewReader(body)))
return rec
}
long, _ := json.Marshal(map[string]string{"url": "https://x.com/1", "title": "t", "text": strings.Repeat("é", maxPageRunes+500)})
rec := post(string(long))
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body)
}
if forwardedLen != maxPageRunes {
t.Fatalf("forwarded %d runes, want %d", forwardedLen, maxPageRunes)
}
var out ExtractedJobPosting
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.Company != "Acme" {
t.Fatalf("body = %s (%v)", rec.Body, err)
}
if rec := post(`{"url": "https://x.com/1", "text": " "}`); rec.Code != http.StatusBadRequest {
t.Fatalf("blank text: status = %d", rec.Code)
}
if rec := post(`not json`); rec.Code != http.StatusBadRequest {
t.Fatalf("bad body: status = %d", rec.Code)
}
}
+1 -13
View File
@@ -32,24 +32,12 @@ type Store struct {
Auth *services.Auth
Notes *services.Notes
LoginLimiter *services.RateLimiter
EmailSync *services.EmailSyncService
// JobLeads is the lead fetcher (services/job_leads.go). The GraphQL
// resolvers use it to start a run and report on one.
JobLeads *services.JobLeadService
// Base URL of the Python service on the Docker network, no trailing
// slash. Used for the calls that bypass nginx, all through
// services.CallPython: reading a rowing display photo (handle_rowing.go)
// and a job posting (handle_job_capture.go). The email pipeline and the
// lead pipeline make the other two such calls and hold their own copies
// of this value.
// services.CallPython: reading a rowing display photo (handle_rowing.go).
PythonURL string
// Bearer token for the browser capture routes (handle_job_capture.go),
// generated from the admin panel. Nil, or holding no token, means those
// routes are switched off, not open.
CaptureToken *services.CaptureToken
// Registry of .env variables and the request/status hand-off with the
// host that applies changes to them (handle_env.go).
Env *services.EnvManager