Add browser job capture to the job tracker
Deploy with Docker Compose / deploy (push) Successful in 1m31s

A Violentmonkey userscript, served by the site and installed from /cv/jobs,
adds the posting open in the browser (LinkedIn, an ATS, any company page) to
the tracker. Claude reads the title, company and location off the page text.

- Three token-guarded REST routes under /api/jobs/capture (status, extract,
  upsert). They take a bearer token, JOB_CAPTURE_TOKEN, because the auth
  cookies are SameSite=Lax and never sent from another origin. An unset token
  switches the routes off.
- The upsert matches on a canonical posting URL, then (company, job title),
  so a capture and the email pipeline do not make two rows for one job.
- The Claude call is a new internal Python route, /internal/jobs/extract,
  alongside the rowing reader; the client and fence stripping they share move
  to python/app/claude.py.
- New "saved" status ranked below "applied", and a description column holding
  the posting text, shown per row on the tracker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-12 13:33:28 +01:00
co-authored by Claude Opus 5.5
parent 94eaa8e239
commit b8670246a8
28 changed files with 2003 additions and 145 deletions
+2
View File
@@ -38,6 +38,7 @@ var configVars = []ConfigVar{
{"STEAM_API_KEY", "Steam status widget", false},
{"STEAM_ID", "Steam status widget", false},
{"CLAUDE_API_KEY", "Email summarisation", false},
{"JOB_CAPTURE_TOKEN", "Job capture userscript", false},
{"EMAIL_BACKEND", "Email sync (graph/imap)", false},
{"MSGRAPH_CLIENT_ID", "Email sync (Microsoft Graph)", false},
{"MSGRAPH_CLIENT_SECRET", "Email sync (Microsoft Graph)", false},
@@ -81,6 +82,7 @@ func (store *Store) ConfigCheck(ctx *gin.Context) {
"SPOTIFY_CLIENT_SECRET": true,
"MSGRAPH_CLIENT_SECRET": true,
"CLAUDE_API_KEY": true,
"JOB_CAPTURE_TOKEN": true,
"STEAM_API_KEY": true,
"IMAP_PASSWORD": true,
}
+452
View File
@@ -0,0 +1,452 @@
package handlers
import (
"bytes"
"context"
"crypto/subtle"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// Job capture: the three endpoints behind userscripts/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
)
// jobExtractClient bounds the wait on the Python service; see
// rowingReadClient for why two minutes.
var jobExtractClient = &http.Client{Timeout: 2 * time.Minute}
// CaptureTokenMiddleware guards the capture routes with JOB_CAPTURE_TOKEN,
// presented as "Authorization: Bearer <token>".
//
// An unset token turns the routes off (503) rather than leaving them open:
// an empty env var is the stack's failure mode for a forgotten secret (see
// .env.example), and comparing "" to "" would otherwise let everyone in.
func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) {
if store.JobCaptureToken == "" {
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"})
return
}
presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ")
if !ok || subtle.ConstantTimeCompare([]byte(presented), []byte(store.JobCaptureToken)) != 1 {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
ctx.Next()
}
// trackingParams are query parameters that say how the visitor arrived, not
// which posting this is. Anything not listed is kept: ATS boards identify the
// job in the query string often enough (gh_jid, jk, jobId) that dropping
// unknown parameters would merge different postings.
var trackingParams = map[string]bool{
"trk": true, "trackingid": true, "refid": true, "ebp": true,
"gh_src": true, "lever-source": true, "lever-origin": true,
"source": true, "src": true, "ref": true,
"fbclid": true, "gclid": true, "mc_cid": true, "mc_eid": true,
}
// linkedInJobPath matches both forms of a LinkedIn posting path: the bare
// /jobs/view/123 and the public slug form /jobs/view/some-title-at-co-123.
var linkedInJobPath = regexp.MustCompile(`^/jobs/view/(?:.*-)?(\d+)/?$`)
// canonicalJobURL reduces a posting URL to a form that is the same however
// the page was reached, so it can serve as the key that decides whether a
// posting is already tracked. ok is false for anything that is not an
// absolute http(s) URL.
//
// LinkedIn gets its own rule because the same posting appears under several
// paths (search results, collections, the recommended feed), all carrying the
// id in ?currentJobId= rather than in the path.
func canonicalJobURL(raw string) (canonical string, ok bool) {
u, err := url.Parse(strings.TrimSpace(raw))
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return "", false
}
host := strings.ToLower(u.Host)
query := u.Query()
if host == "linkedin.com" || strings.HasSuffix(host, ".linkedin.com") {
id := query.Get("currentJobId")
if m := linkedInJobPath.FindStringSubmatch(u.Path); m != nil {
id = m[1]
}
if id != "" && strings.Trim(id, "0123456789") == "" {
return "https://www.linkedin.com/jobs/view/" + id + "/", true
}
}
for key := range query {
lowered := strings.ToLower(key)
if trackingParams[lowered] || strings.HasPrefix(lowered, "utm_") {
query.Del(key)
}
}
out := url.URL{
Scheme: u.Scheme,
Host: host,
// A trailing slash is not a different posting.
Path: strings.TrimRight(u.Path, "/"),
// Encode sorts by key, so parameter order does not matter either.
RawQuery: query.Encode(),
}
return out.String(), true
}
// 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}
}
// findByURL returns the newest live application stored under this posting's
// URL, or nil. The raw form is tried as well as the canonical one because rows
// typed into the tracker by hand hold whatever was pasted.
func (store *Store) findByURL(canonical, raw string) (*models.JobApplication, error) {
return firstApplication(store.DB.Where("url IN ?", []string{canonical, strings.TrimSpace(raw)}))
}
// firstApplication returns the newest row the query matches, or nil for none.
// Limit(1).Find rather than First: a miss is the ordinary answer here (every
// badge lookup on an untracked posting), and First reports one as
// ErrRecordNotFound, which GORM writes to the log as an error each time.
func firstApplication(query *gorm.DB) (*models.JobApplication, error) {
var apps []models.JobApplication
if err := query.Order("created_at DESC, id DESC").Limit(1).Find(&apps).Error; err != nil {
return nil, err
}
if len(apps) == 0 {
return nil, nil
}
return &apps[0], nil
}
// 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 := canonicalJobURL(raw)
if !ok {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
return
}
app, err := store.findByURL(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"`
}
// postingReadError is a failure the Python service reported in words that are
// safe to show in the capture popup (its 502 detail); the job-capture
// counterpart of displayReadError.
type postingReadError struct{ detail string }
func (e *postingReadError) Error() string { return e.detail }
// extractJobPosting sends a page's text to the Python service and returns the
// fields Claude picked out. It mirrors readRowingDisplay, including which
// replies are relayed and which are only logged.
func (store *Store) extractJobPosting(ctx context.Context, pageURL, title, text string) (ExtractedJobPosting, error) {
var posting ExtractedJobPosting
body, err := json.Marshal(struct {
URL string `json:"url"`
Title string `json:"title"`
Text string `json:"text"`
}{pageURL, title, text})
if err != nil {
return posting, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+jobExtractPath, bytes.NewReader(body))
if err != nil {
return posting, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := jobExtractClient.Do(req)
if err != nil {
return posting, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
var failure struct {
Detail string `json:"detail"`
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
return posting, &postingReadError{detail: failure.Detail}
}
return posting, fmt.Errorf("job extractor returned %d: %s", resp.StatusCode, raw)
}
if err := json.NewDecoder(resp.Body).Decode(&posting); err != nil {
return posting, fmt.Errorf("decoding job extractor response: %w", err)
}
return posting, nil
}
// 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 *postingReadError
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)
}
// captureInput is the body of POST /jobs/capture: the popup's fields.
type captureInput struct {
JobTitle string `json:"jobTitle"`
Company string `json:"company"`
Location string `json:"location"`
URL string `json:"url"`
Status string `json:"status"`
Notes string `json:"notes"`
Description string `json:"description"`
}
func nonEmpty(p *string) bool { return p != nil && strings.TrimSpace(*p) != "" }
// mergeCapture folds a repeat capture into the application it matched and
// reports whether anything changed.
//
// It only ever adds: the status moves forwards or not at all (the same rule
// the email pipeline follows, so re-capturing a posting marked "saved" cannot
// pull an interviewing application back), and a field already holding a value
// is left alone, because the row may have been corrected by hand since. Title
// and company are never touched — they are the key the email pipeline matches
// on.
func mergeCapture(app *models.JobApplication, in captureInput, now time.Time) bool {
changed := false
if status := services.NormalizeStatus(in.Status); services.StatusAdvances(app.Status, status) {
app.Status = status
changed = true
}
// Saved-then-applied is the common path here, and the moment of the
// second capture is the application date.
if app.AppliedAt == nil && app.Status == "applied" {
app.AppliedAt = &now
changed = true
}
fill := func(field **string, value string) {
if value != "" && !nonEmpty(*field) {
*field = &value
changed = true
}
}
fill(&app.Location, in.Location)
fill(&app.URL, in.URL)
fill(&app.Description, in.Description)
// Notes accumulate, as they do when the pipeline updates a row, but a
// repeat capture of the same page must not append the same line twice.
if in.Notes != "" {
switch {
case !nonEmpty(app.Notes):
app.Notes = &in.Notes
changed = true
case !strings.Contains(*app.Notes, in.Notes):
combined := *app.Notes + "\n" + in.Notes
app.Notes = &combined
changed = true
}
}
return changed
}
// JobCapture backs POST /jobs/capture, an upsert.
//
// A posting already in the tracker is updated in place rather than added
// again. That matters beyond tidiness: the email pipeline identifies an
// application by (company, job title), so two rows for one posting means the
// confirmation email advances only one of them.
//
// Match order is the posting URL, then (company, job title) compared the way
// the pipeline compares them. Only live rows match — unlike the pipeline's
// lookup, which also sees deleted rows so that an email cannot resurrect one.
// A capture is a deliberate act, so capturing a posting whose row was deleted
// makes a new row.
func (store *Store) JobCapture(ctx *gin.Context) {
var input captureInput
if !bindCapture(ctx, &input) {
return
}
input.JobTitle = strings.TrimSpace(input.JobTitle)
input.Company = strings.TrimSpace(input.Company)
input.Location = strings.TrimSpace(input.Location)
input.Notes = strings.TrimSpace(input.Notes)
input.Description = truncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
if input.JobTitle == "" || input.Company == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jobTitle and company are required"})
return
}
rawURL := input.URL
if strings.TrimSpace(rawURL) != "" {
canonical, ok := canonicalJobURL(rawURL)
if !ok {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
return
}
input.URL = canonical
} else {
input.URL = ""
}
var existing *models.JobApplication
var err error
if input.URL != "" {
existing, err = store.findByURL(input.URL, rawURL)
}
if err == nil && existing == nil {
existing, err = firstApplication(store.DB.Where(
"LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", input.Company, input.JobTitle))
}
if err != nil {
log.Println("Job capture lookup failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
return
}
now := time.Now()
if existing != nil {
action := "unchanged"
if mergeCapture(existing, input, now) {
if err := store.DB.Save(existing).Error; err != nil {
log.Println("Job capture update failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
return
}
action = "updated"
}
ctx.JSON(http.StatusOK, gin.H{"action": action, "application": capturedJobOf(existing)})
return
}
// A new row is the merge of the capture into an empty application, which
// keeps the two paths agreeing on what an empty field and "applied" mean.
// The empty status counts as unknown, so any status takes over from it.
app := models.JobApplication{JobTitle: input.JobTitle, Company: input.Company}
mergeCapture(&app, input, now)
if err := store.DB.Create(&app).Error; err != nil {
log.Println("Job capture insert failed:", err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
return
}
ctx.JSON(http.StatusCreated, gin.H{"action": "created", "application": capturedJobOf(&app)})
}
+294
View File
@@ -0,0 +1,294 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"adam-french.co.uk/backend/models"
"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)
cases := []struct {
name string
configured string
header string
want int
}{
{"the right token is let through", "s3cret", "Bearer s3cret", http.StatusOK},
{"a wrong token is refused", "s3cret", "Bearer nope", http.StatusUnauthorized},
{"no header is refused", "s3cret", "", http.StatusUnauthorized},
{"the bare token without the scheme is refused", "s3cret", "s3cret", http.StatusUnauthorized},
// The case the middleware exists to get right: an unset token must
// not match the empty credential of an anonymous request.
{"an unset token switches the routes off", "", "", http.StatusServiceUnavailable},
{"an unset token is not matched by an empty bearer", "", "Bearer ", http.StatusServiceUnavailable},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
store := &Store{JobCaptureToken: c.configured}
r := gin.New()
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
req := httptest.NewRequest(http.MethodGet, "/x", nil)
if c.header != "" {
req.Header.Set("Authorization", c.header)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != c.want {
t.Fatalf("status = %d, want %d", rec.Code, c.want)
}
})
}
}
func TestCanonicalJobURL(t *testing.T) {
const linkedIn = "https://www.linkedin.com/jobs/view/4012345678/"
cases := []struct {
name string
in string
want string // "" means rejected
}{
// One LinkedIn posting, reached four ways, must be one key.
{"linkedin direct", "https://www.linkedin.com/jobs/view/4012345678/?trk=public_jobs", linkedIn},
{"linkedin slug form", "https://uk.linkedin.com/jobs/view/backend-engineer-at-acme-4012345678?refId=abc", linkedIn},
{"linkedin search pane", "https://www.linkedin.com/jobs/search/?currentJobId=4012345678&keywords=go", linkedIn},
{"linkedin collections pane", "https://www.linkedin.com/jobs/collections/recommended/?currentJobId=4012345678", linkedIn},
{"linkedin page with no job id is left as a normal URL", "https://www.linkedin.com/jobs/search/?keywords=go", "https://www.linkedin.com/jobs/search?keywords=go"},
{"a non-numeric linkedin id is not trusted", "https://www.linkedin.com/jobs/search/?currentJobId=4/../x", "https://www.linkedin.com/jobs/search?currentJobId=4%2F..%2Fx"},
{"a lookalike host does not get the linkedin rule", "https://notlinkedin.com/jobs/view/42", "https://notlinkedin.com/jobs/view/42"},
{"tracking parameters and the fragment are dropped", "https://jobs.lever.co/acme/abc-123?lever-source=LinkedIn&utm_medium=x#apply", "https://jobs.lever.co/acme/abc-123"},
// gh_jid IS the posting on an embedded Greenhouse board.
{"a parameter that identifies the job is kept", "https://acme.com/careers?gh_jid=77&gh_src=abc", "https://acme.com/careers?gh_jid=77"},
{"parameter order does not matter", "https://x.com/job?b=2&a=1", "https://x.com/job?a=1&b=2"},
{"host case and a trailing slash do not matter", "https://Boards.Greenhouse.io/acme/jobs/55/", "https://boards.greenhouse.io/acme/jobs/55"},
{"a relative path is rejected", "/jobs/view/1", ""},
{"a non-http scheme is rejected", "javascript:alert(1)", ""},
{"empty is rejected", "", ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, ok := canonicalJobURL(c.in)
if ok != (c.want != "") || got != c.want {
t.Fatalf("canonicalJobURL(%q) = %q, %v; want %q", c.in, got, ok, c.want)
}
})
}
}
func strPtr(s string) *string { return &s }
func TestMergeCapture(t *testing.T) {
now := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
earlier := now.Add(-48 * time.Hour)
t.Run("a new row takes every field and an applied date", func(t *testing.T) {
app := models.JobApplication{JobTitle: "Engineer", Company: "Acme"}
in := captureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Notes: "Hybrid", Description: "Full text"}
if !mergeCapture(&app, in, now) {
t.Fatal("expected a change")
}
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
if *app.Location != "London" || *app.URL != "https://x.com/1" || *app.Notes != "Hybrid" || *app.Description != "Full text" {
t.Fatalf("fields not filled: %+v", app)
}
})
t.Run("a saved posting has no applied date", func(t *testing.T) {
app := models.JobApplication{}
mergeCapture(&app, captureInput{Status: "saved"}, now)
if app.Status != "saved" || app.AppliedAt != nil {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
})
t.Run("saved then applied advances and dates the application", func(t *testing.T) {
app := models.JobApplication{Status: "saved"}
if !mergeCapture(&app, captureInput{Status: "applied"}, now) {
t.Fatal("expected a change")
}
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
})
t.Run("a repeat capture cannot move an application backwards", func(t *testing.T) {
app := models.JobApplication{Status: "interviewing", AppliedAt: &earlier}
if mergeCapture(&app, captureInput{Status: "saved"}, now) {
t.Fatal("expected no change")
}
if app.Status != "interviewing" || !app.AppliedAt.Equal(earlier) {
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
}
})
t.Run("fields already set are kept, empty ones are filled", func(t *testing.T) {
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Location: strPtr("Remote"), URL: strPtr("")}
in := captureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Description: "Full text"}
if !mergeCapture(&app, in, now) {
t.Fatal("expected a change")
}
if *app.Location != "Remote" {
t.Fatalf("location overwritten: %q", *app.Location)
}
if *app.URL != "https://x.com/1" || *app.Description != "Full text" {
t.Fatalf("empty fields not filled: url=%q", *app.URL)
}
if !app.AppliedAt.Equal(earlier) {
t.Fatal("an existing applied date must not be replaced")
}
})
t.Run("notes append once", func(t *testing.T) {
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Notes: strPtr("Recruiter: Sam")}
in := captureInput{Status: "applied", Notes: "Hybrid, £70k"}
if !mergeCapture(&app, in, now) || *app.Notes != "Recruiter: Sam\nHybrid, £70k" {
t.Fatalf("notes = %q", *app.Notes)
}
if mergeCapture(&app, in, now) {
t.Fatalf("the same note was appended twice: %q", *app.Notes)
}
})
}
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 postingReadError 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 *postingReadError
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)
}
}
+6 -2
View File
@@ -35,10 +35,14 @@ type Store struct {
EmailSync *services.EmailSyncService
// Base URL of the Python service on the Docker network, no trailing
// slash. Used for the one call that bypasses nginx: reading a rowing
// display photo (see handle_rowing.go).
// slash. Used for the calls that bypass nginx: reading a rowing display
// photo (handle_rowing.go) and a job posting (handle_job_capture.go).
PythonURL string
// Bearer token for the browser capture routes (handle_job_capture.go).
// Empty means those routes are switched off, not open.
JobCaptureToken string
// Cached "recently played" tracks, refreshed at most once a minute by the
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
// mean "never fetched" distinctly from "fetched, empty".