Split the job tracker out of web_server into its own app
Test and publish / test (push) Successful in 6m39s
Test and publish / publish (push) Failing after 0s

The applications tracker, leads inbox, email pipeline and capture userscript
move here from web_server's backend, Python service and Vue app, as one Go
binary that serves its own Vue SPA under /jobs/.

- The Go services, resolvers and tests move over almost unchanged.
- The three Claude calls are ported from Python to Go (internal/claude),
  with the same prompts, per-model request shaping and error messages.
- There is no login: internal/auth asks the site backend's
  /auth/validate-admin with the visitor's cookies, and relays refreshed
  cookies back.
- A Settings page replaces the admin-panel capture token card and adds the
  Microsoft sign-in link and a manual email sync.
- The userscript is 2.0.0, at /jobs/, and migrates a saved API base.
- Dockerfile, a standalone compose with Postgres, Makefile, and a Gitea CI
  workflow that tests and publishes the image.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-14 16:24:16 +01:00
co-authored by Claude Opus 5.5
commit 67cb8137f9
88 changed files with 22715 additions and 0 deletions
+134
View File
@@ -0,0 +1,134 @@
package services
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sync"
"time"
)
// CaptureTokenFile is the token's file name inside the data directory, beside
// the Graph session, in the volume docker-compose mounts so that it survives
// a rebuild.
const CaptureTokenFile = "job_capture_token.json"
// CaptureToken holds the bearer token the job capture userscript presents
// (handlers/handle_job_capture.go). The token is minted from the admin panel
// rather than set in .env, so it can be replaced without a redeploy when the
// browser profile holding it is lost.
//
// Only a SHA-256 of the token is kept, in memory and on disk: the token is
// shown once, when generated, and cannot be read back afterwards. A plain
// hash is enough because the token is 32 random bytes, not a password — there
// is nothing to brute-force.
//
// There is at most one token. Generating replaces it, which is also how a
// leaked one is rotated.
type CaptureToken struct {
path string
mu sync.RWMutex
hash []byte
createdAt time.Time
}
type captureTokenFile struct {
SHA256 string `json:"sha256"`
CreatedAt time.Time `json:"created_at"`
}
// InitCaptureToken loads the token file if there is one. A missing file is
// the normal first-run state and means "no token": the capture routes stay
// off until one is generated. A file that cannot be read or parsed is
// reported, and likewise leaves the routes off rather than open.
func InitCaptureToken(path string) (*CaptureToken, error) {
t := &CaptureToken{path: path}
raw, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return t, nil
}
if err != nil {
return t, fmt.Errorf("reading capture token: %w", err)
}
var stored captureTokenFile
if err := json.Unmarshal(raw, &stored); err != nil {
return t, fmt.Errorf("parsing capture token: %w", err)
}
hash, err := hex.DecodeString(stored.SHA256)
if err != nil || len(hash) != sha256.Size {
return t, fmt.Errorf("capture token file holds no valid hash")
}
t.hash, t.createdAt = hash, stored.CreatedAt
return t, nil
}
// Generate mints a new token, replacing any existing one, and returns it.
// This is the only moment the token itself exists on the server.
//
// The file is written before the in-memory hash is swapped, so a failed write
// leaves the old token working instead of handing out one that would stop
// working at the next restart.
func (t *CaptureToken) Generate() (string, time.Time, error) {
raw := make([]byte, 32)
if _, err := rand.Read(raw); err != nil {
return "", time.Time{}, err
}
token := hex.EncodeToString(raw)
sum := sha256.Sum256([]byte(token))
now := time.Now().UTC()
data, err := json.MarshalIndent(captureTokenFile{SHA256: hex.EncodeToString(sum[:]), CreatedAt: now}, "", " ")
if err != nil {
return "", time.Time{}, err
}
if err := os.MkdirAll(filepath.Dir(t.path), 0755); err != nil {
return "", time.Time{}, fmt.Errorf("creating token directory: %w", err)
}
if err := os.WriteFile(t.path, data, 0600); err != nil {
return "", time.Time{}, fmt.Errorf("writing capture token: %w", err)
}
t.mu.Lock()
t.hash, t.createdAt = sum[:], now
t.mu.Unlock()
return token, now, nil
}
// Revoke deletes the token, switching the capture routes off.
func (t *CaptureToken) Revoke() error {
if err := os.Remove(t.path); err != nil && !errors.Is(err, fs.ErrNotExist) {
return fmt.Errorf("removing capture token: %w", err)
}
t.mu.Lock()
t.hash, t.createdAt = nil, time.Time{}
t.mu.Unlock()
return nil
}
// Status reports whether a token exists and when it was generated.
func (t *CaptureToken) Status() (set bool, createdAt time.Time) {
t.mu.RLock()
defer t.mu.RUnlock()
return t.hash != nil, t.createdAt
}
// Verify reports whether presented is the current token. With no token it is
// false for every input, the empty string included.
func (t *CaptureToken) Verify(presented string) bool {
t.mu.RLock()
defer t.mu.RUnlock()
if t.hash == nil {
return false
}
sum := sha256.Sum256([]byte(presented))
return subtle.ConstantTimeCompare(sum[:], t.hash) == 1
}
+126
View File
@@ -0,0 +1,126 @@
package services
import (
"os"
"path/filepath"
"strings"
"testing"
)
func newCaptureToken(t *testing.T) (*CaptureToken, string) {
t.Helper()
// A nested path: the token directory may not exist on a fresh checkout.
path := filepath.Join(t.TempDir(), "token", "job_capture_token.json")
tok, err := InitCaptureToken(path)
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
return tok, path
}
func TestCaptureTokenStartsUnsetAndRejectsEverything(t *testing.T) {
tok, _ := newCaptureToken(t)
if set, _ := tok.Status(); set {
t.Fatal("a fresh store reports a token")
}
// The empty string is the credential of a request with no token at all.
for _, presented := range []string{"", "anything"} {
if tok.Verify(presented) {
t.Fatalf("Verify(%q) passed with no token generated", presented)
}
}
}
func TestCaptureTokenGenerateVerifyAndRotate(t *testing.T) {
tok, path := newCaptureToken(t)
first, createdAt, err := tok.Generate()
if err != nil {
t.Fatalf("Generate: %v", err)
}
if len(first) != 64 {
t.Fatalf("token is %d chars, want 64 hex chars (32 bytes)", len(first))
}
if set, at := tok.Status(); !set || !at.Equal(createdAt) {
t.Fatalf("Status = %v, %v", set, at)
}
if !tok.Verify(first) || tok.Verify(first+"x") || tok.Verify("") {
t.Fatal("Verify does not accept exactly the generated token")
}
// The file must be useless to someone who reads it, and private anyway.
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("reading token file: %v", err)
}
if strings.Contains(string(raw), first) {
t.Fatal("the token itself was written to disk")
}
if info, _ := os.Stat(path); info.Mode().Perm() != 0o600 {
t.Fatalf("token file mode = %v, want 0600", info.Mode().Perm())
}
second, _, err := tok.Generate()
if err != nil {
t.Fatalf("Generate: %v", err)
}
if tok.Verify(first) || !tok.Verify(second) {
t.Fatal("generating again must replace the old token")
}
}
func TestCaptureTokenSurvivesRestart(t *testing.T) {
tok, path := newCaptureToken(t)
token, createdAt, _ := tok.Generate()
reloaded, err := InitCaptureToken(path)
if err != nil {
t.Fatalf("InitCaptureToken: %v", err)
}
if !reloaded.Verify(token) {
t.Fatal("token no longer verifies after a reload")
}
if _, at := reloaded.Status(); !at.Equal(createdAt) {
t.Fatalf("createdAt = %v, want %v", at, createdAt)
}
}
func TestCaptureTokenRevoke(t *testing.T) {
tok, path := newCaptureToken(t)
token, _, _ := tok.Generate()
if err := tok.Revoke(); err != nil {
t.Fatalf("Revoke: %v", err)
}
if tok.Verify(token) {
t.Fatal("token still verifies after Revoke")
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatal("token file still exists, so the token would return on restart")
}
if err := tok.Revoke(); err != nil {
t.Fatalf("revoking with nothing to revoke: %v", err)
}
}
// A damaged file must leave the routes off, never open and never fatal.
func TestCaptureTokenCorruptFile(t *testing.T) {
for name, content := range map[string]string{
"not json": "{",
"not a hash": `{"sha256": "zz"}`,
"short hash": `{"sha256": "abcd"}`,
"empty object": `{}`,
} {
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "t.json")
os.WriteFile(path, []byte(content), 0o600)
tok, err := InitCaptureToken(path)
if err == nil {
t.Fatal("expected an error")
}
if tok == nil || tok.Verify("") {
t.Fatal("a corrupt file must yield a usable store that rejects everything")
}
})
}
}
+44
View File
@@ -0,0 +1,44 @@
package services
import (
"adam-french.co.uk/job-tracker/internal/models"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
// migrateDatabase brings the schema up to date. There are no migration
// files: GORM's AutoMigrate is the only schema source, so it will add tables,
// columns and indexes but never drop or rename anything. Removing a field
// from a model therefore leaves the column behind, and a renamed field
// appears as a brand-new column with no data. Any model added to models.go
// must also be listed here or its table will never be created.
//
// The tables were created by the main site's backend before the tracker
// became its own app, and were copied across with pg_dump, so on a migrated
// database this finds nothing to do.
func migrateDatabase(db *gorm.DB) error {
return db.AutoMigrate(
&models.JobApplication{},
&models.JobAppReference{},
&models.ProcessedEmail{},
&models.JobSource{},
&models.JobLead{},
&models.JobSearchProfile{},
)
}
// InitDatabase connects to Postgres at dsn and runs the auto-migration. dsn
// is DATABASE_URL, in either of the forms pgx accepts
// (postgres://user:pass@host:port/db?sslmode=disable, or key=value pairs).
// sslmode=disable is fine only because Postgres is reachable exclusively on
// the private Docker network.
func InitDatabase(dsn string) (*gorm.DB, error) {
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
if err := migrateDatabase(db); err != nil {
return nil, err
}
return db, nil
}
+182
View File
@@ -0,0 +1,182 @@
package services
import (
"context"
"errors"
"fmt"
"slices"
"sort"
"strings"
"testing"
"unicode/utf8"
"adam-french.co.uk/job-tracker/internal/claude"
)
// The classify step of the email pipeline: the message handed to Claude, and
// what processEmail does with each kind of answer. A fake classifier stands
// in for internal/claude, whose own tests cover the request and the parsing.
//
// processEmail is driven only as far as it can go without a database. That
// covers every failure (they all return before the first query) and the two
// "nothing to do" answers; an email that is about a job goes on to look the
// application up, which needs Postgres and is not exercised here.
// fakeClassifier answers every email with analysis and err, recording the
// messages it was given.
type fakeClassifier struct {
analysis EmailAnalysis
err error
messages []string
}
func (f *fakeClassifier) ClassifyEmail(ctx context.Context, message string) (EmailAnalysis, error) {
f.messages = append(f.messages, message)
if err := ctx.Err(); err != nil {
return EmailAnalysis{}, err
}
return f.analysis, f.err
}
func classifierStub(analysis EmailAnalysis, err error) (*EmailSyncService, *fakeClassifier) {
f := &fakeClassifier{analysis: analysis, err: err}
return &EmailSyncService{Classifier: f}, f
}
func testEmail() graphMessage {
email := graphMessage{
ID: "msg-1",
Subject: "Your application to Acme",
ReceivedDateTime: "2026-03-15T10:30:00Z",
Body: graphBody{ContentType: "html", Content: "<p>Thanks&nbsp;for applying</p>"},
}
email.From.EmailAddress = graphEmailAddress{Name: "Acme Hiring", Address: "[email protected]"}
return email
}
func TestClassifyEmailMessage(t *testing.T) {
want := EmailAnalysis{IsJobEmail: true, Action: "create", Company: "Acme", JobTitle: "Engineer", Status: "applied"}
s, f := classifierStub(want, nil)
analysis, err := s.classifyEmail(context.Background(), testEmail())
if err != nil || analysis != want {
t.Fatalf("classifyEmail = %+v, %v", analysis, err)
}
// The whole contract: the headers, a blank line and the cleaned body,
// which go to Claude unchanged.
msg := "Subject: Your application to Acme\nFrom: Acme Hiring <[email protected]>\nDate: 2026-03-15T10:30:00Z\n\nThanks for applying"
if !slices.Equal(f.messages, []string{msg}) {
t.Fatalf("messages = %q\nwant [%q]", f.messages, msg)
}
}
// The classifier prompt lists the statuses Claude may answer; they must be
// the tracker's vocabulary less "saved", which no email announces.
func TestClassifierStatusesMatchStatusOrder(t *testing.T) {
var want []string
for status := range statusOrder {
if status != "saved" {
want = append(want, status)
}
}
got := slices.Clone(claude.EmailStatuses)
sort.Strings(want)
sort.Strings(got)
if !slices.Equal(got, want) {
t.Fatalf("claude.EmailStatuses = %v\nstatusOrder less saved = %v", got, want)
}
}
func TestProcessEmailWithoutAJob(t *testing.T) {
cases := []struct {
name string
analysis EmailAnalysis
}{
{"not a job email", EmailAnalysis{}},
// (company, job title) is the only key an application has, so an
// answer missing either cannot be matched or created.
{"a job email with no company", EmailAnalysis{IsJobEmail: true, Action: "create", JobTitle: "Engineer", Status: "applied"}},
{"a job email with no title", EmailAnalysis{IsJobEmail: true, Action: "create", Company: "Acme", Status: "applied"}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s, _ := classifierStub(c.analysis, nil)
action, jobAppID, err := s.processEmail(context.Background(), testEmail())
if err != nil || action != "skipped" || jobAppID != nil {
t.Fatalf("processEmail = (%q, %v, %v), want (skipped, nil, nil)", action, jobAppID, err)
}
})
}
}
// Every way the classifier can fail must come back from processEmail as an
// error with no action: that is what makes SyncEmails record the email as
// Action "error" with one more attempt used, to be retried next sync.
func TestProcessEmailClassifierFailures(t *testing.T) {
cases := []struct {
name string
err error
}{
{"Claude failed", &claude.ReadError{Msg: "failed to classify the email"}},
{"Claude's reply was unparseable", &claude.ReadError{Msg: "failed to parse the email classification"}},
{"no API key", claude.ErrNotConfigured},
{"something else", fmt.Errorf("unexpected")},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
s, _ := classifierStub(EmailAnalysis{}, c.err)
action, jobAppID, err := s.processEmail(context.Background(), testEmail())
if err == nil {
t.Fatal("expected an error")
}
if action != "" || jobAppID != nil {
t.Fatalf("processEmail = (%q, %v) alongside an error", action, jobAppID)
}
// Not a cancellation: SyncEmails skips those without recording
// anything, which would leave a real failure retried for ever.
if errors.Is(err, context.Canceled) {
t.Fatalf("err = %v reads as a cancelled sync", err)
}
if !errors.Is(err, c.err) {
t.Fatalf("err = %v does not wrap %v", err, c.err)
}
})
}
}
// The other half of the rule above: a sync abandoned mid-call (the admin
// closed the tab) must be recognisable, so the email's attempts do not advance.
func TestProcessEmailCancelled(t *testing.T) {
s, _ := classifierStub(EmailAnalysis{}, nil)
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, _, err := s.processEmail(ctx, testEmail()); !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want it to wrap context.Canceled", err)
}
}
func TestClassifierMessageIsCapped(t *testing.T) {
// An ordinary email is nowhere near the cap and is not touched.
if got := classifierMessage(testEmail()); !strings.HasSuffix(got, "\n\nThanks for applying") {
t.Fatalf("message = %q", got)
}
// cleanEmailBody bounds the body, so only the headers can push a message
// over. Multi-byte runes: the cap counts characters, and the cut must not split one.
long := testEmail()
long.Subject = strings.Repeat("é", maxClassifyRunes+50)
got := classifierMessage(long)
if n := utf8.RuneCountInString(got); n != maxClassifyRunes {
t.Fatalf("message is %d runes, want %d", n, maxClassifyRunes)
}
if !utf8.ValidString(got) {
t.Fatal("the cut split a rune")
}
// More bytes than the cap but fewer runes: within the limit, so intact.
wide := testEmail()
wide.Subject = strings.Repeat("é", maxClassifyRunes/2+10)
if got := classifierMessage(wide); !strings.HasSuffix(got, "\n\nThanks for applying") {
t.Fatal("a message under the rune cap was cut")
}
}
+420
View File
@@ -0,0 +1,420 @@
package services
import (
"bufio"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"fmt"
"io"
"log"
"mime"
"mime/multipart"
"net"
"net/mail"
"strings"
"sync/atomic"
"time"
)
// This file is a hand-rolled IMAP client, used as an alternative mail source
// to Microsoft Graph. It exists because the Graph path needs an Azure app
// registration and admin consent, while IMAP needs only an app password.
//
// It implements the bare minimum of RFC 3501 — LOGIN, SELECT, SEARCH, FETCH,
// LOGOUT — by matching on string prefixes rather than parsing IMAP's grammar
// properly. It works against Outlook and similar servers with the response
// shapes seen in practice; it is not a general-purpose IMAP client.
// IMAPConfig holds the mailbox credentials. Password is an app password, not
// an account password.
type IMAPConfig struct {
Host string
Port string
Email string
Password string
}
// imapClient is a minimal, lenient IMAP client that tolerates
// Outlook's non-standard response formatting.
type imapClient struct {
conn net.Conn
reader *bufio.Reader
// tag numbers the commands. IMAP allows several in flight at once
// identified by tag; this client never does that, so the atomic is
// belt-and-braces rather than load-bearing.
tag atomic.Int64
}
// imapDial opens an implicit-TLS IMAP connection (port 993 style, TLS from the
// first byte — there is no STARTTLS support here) and consumes the server
// greeting, which arrives unsolicited before any command.
func imapDial(addr string) (*imapClient, error) {
conn, err := tls.Dial("tcp", addr, nil)
if err != nil {
return nil, err
}
c := &imapClient{
conn: conn,
reader: bufio.NewReader(conn),
}
// Read server greeting
if _, err := c.readLine(); err != nil {
conn.Close()
return nil, fmt.Errorf("reading greeting: %w", err)
}
return c, nil
}
// Close drops the TCP connection. Callers normally send LOGOUT first.
func (c *imapClient) Close() error {
return c.conn.Close()
}
// nextTag returns the next command tag, e.g. "A0001". The width is cosmetic:
// past 9999 the tags simply get longer, and they stay unique.
func (c *imapClient) nextTag() string {
return fmt.Sprintf("A%04d", c.tag.Add(1))
}
// readLine reads one CRLF-terminated protocol line with the terminator
// stripped. There is no read deadline anywhere in this client, so an
// unresponsive server can block a sync until the TCP connection itself fails.
func (c *imapClient) readLine() (string, error) {
line, err := c.reader.ReadString('\n')
return strings.TrimRight(line, "\r\n"), err
}
// sendCommand sends a tagged command and reads lines until the line beginning
// with that tag, which is the server's final status for the command.
// Everything before it is an untagged ("* ...") response and is returned.
//
// This must not be used for FETCH: it reads line by line and would mistake the
// bytes of a literal for protocol lines. Use sendFetch instead.
func (c *imapClient) sendCommand(cmd string) (untagged []string, status string, err error) {
tag := c.nextTag()
_, err = fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
if err != nil {
return nil, "", err
}
for {
line, err := c.readLine()
if err != nil {
return untagged, "", err
}
if strings.HasPrefix(line, tag+" ") {
return untagged, line, nil
}
untagged = append(untagged, line)
}
}
// sendCommandOK sends a command and returns an error if the response is not OK.
func (c *imapClient) sendCommandOK(cmd string) ([]string, error) {
untagged, status, err := c.sendCommand(cmd)
if err != nil {
return untagged, err
}
// Status line is "<tag> OK ..." on success, "<tag> NO ..." or
// "<tag> BAD ..." otherwise; only the second field matters.
parts := strings.SplitN(status, " ", 3)
if len(parts) < 2 || parts[1] != "OK" {
return untagged, fmt.Errorf("command %q failed: %s", cmd, status)
}
return untagged, nil
}
// readLiteral reads exactly size bytes of an IMAP literal, i.e. the payload
// announced by a trailing "{N}" on the preceding line. It must read by byte
// count rather than by line because the payload is arbitrary binary data that
// will itself contain CRLFs.
func (c *imapClient) readLiteral(size int) (string, error) {
buf := make([]byte, size)
_, err := io.ReadFull(c.reader, buf)
if err != nil {
return "", err
}
return string(buf), nil
}
// fetchPart is one FETCH response line plus the literal payload that followed
// it, if any. Pairing them in the type removes the need for callers to walk an
// interleaved slice and manually skip every second entry — the previous shape,
// where a literal was simply the next element and a caller that forgot to
// advance would parse message bytes as a protocol line.
type fetchPart struct {
Line string
// Literal is the payload that followed Line, valid only when HasLiteral.
Literal string
HasLiteral bool
}
// sendFetch sends a FETCH and collects its response, handling literals.
//
// The literal is detected with LastIndex("{") plus a "}" suffix rather than a
// real parse, so a line whose text merely ends in braces could be misread —
// tolerable because only FETCH responses reach this code.
func (c *imapClient) sendFetch(cmd string) ([]fetchPart, error) {
tag := c.nextTag()
_, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
if err != nil {
return nil, err
}
var parts []fetchPart
for {
line, err := c.readLine()
if err != nil {
return parts, err
}
// Check for literal marker {N} at end of line
if idx := strings.LastIndex(line, "{"); idx >= 0 && strings.HasSuffix(line, "}") {
sizeStr := line[idx+1 : len(line)-1]
var size int
if _, err := fmt.Sscanf(sizeStr, "%d", &size); err == nil && size > 0 {
literal, err := c.readLiteral(size)
if err != nil {
return parts, fmt.Errorf("reading literal of %d bytes: %w", size, err)
}
parts = append(parts, fetchPart{Line: line, Literal: literal, HasLiteral: true})
continue
}
}
if strings.HasPrefix(line, tag+" ") {
// Check for OK
fields := strings.SplitN(line, " ", 3)
if len(fields) >= 2 && fields[1] != "OK" {
return parts, fmt.Errorf("FETCH failed: %s", line)
}
return parts, nil
}
parts = append(parts, fetchPart{Line: line})
}
}
// fetchEmailsIMAP connects to an IMAP server and retrieves emails since the given time.
func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, error) {
addr := fmt.Sprintf("%s:%s", s.Config.IMAP.Host, s.Config.IMAP.Port)
c, err := imapDial(addr)
if err != nil {
return nil, fmt.Errorf("IMAP connect: %w", err)
}
defer c.Close()
// %q wraps the password in double quotes and backslash-escapes any quote
// or backslash inside it, which happens to be exactly IMAP's quoted-string
// syntax. The username is NOT quoted: an address needs no escaping.
// Note this sends the password in a LOGIN command, so it is only safe
// because the connection is TLS from the first byte.
quotedPass := fmt.Sprintf("%q", s.Config.IMAP.Password)
if _, err := c.sendCommandOK(fmt.Sprintf("LOGIN %s %s", s.Config.IMAP.Email, quotedPass)); err != nil {
return nil, fmt.Errorf("IMAP login: %w", err)
}
if _, err := c.sendCommandOK("SELECT INBOX"); err != nil {
return nil, fmt.Errorf("IMAP select INBOX: %w", err)
}
// SEARCH SINCE has day granularity only — the time of day is not
// expressible — so this always over-fetches back to midnight of `since`.
// Harmless: SyncEmails deduplicates by message id. The date must be in
// IMAP's dd-Mon-yyyy form, hence this exact layout string.
dateStr := since.UTC().Format("02-Jan-2006")
untagged, err := c.sendCommandOK(fmt.Sprintf("SEARCH SINCE %s", dateStr))
if err != nil {
return nil, fmt.Errorf("IMAP search: %w", err)
}
// Parse sequence numbers from "* SEARCH 1 2 3 ...". parts[2:] skips the
// "*" and "SEARCH" tokens; a bare "* SEARCH" (no matches) has len 2 and
// is skipped by the length test.
var seqNums []string
for _, line := range untagged {
if strings.HasPrefix(line, "* SEARCH") {
parts := strings.Fields(line)
if len(parts) > 2 {
seqNums = append(seqNums, parts[2:]...)
}
}
}
if len(seqNums) == 0 {
log.Printf("[EmailSync/IMAP] No messages found since %s", dateStr)
c.sendCommand("LOGOUT")
return nil, nil
}
log.Printf("[EmailSync/IMAP] Found %d messages since %s", len(seqNums), dateStr)
// Every matching message is fetched in one command with a comma-separated
// sequence set, and each full body is held in memory. A mailbox with a
// very busy day could make this large — there is no batching.
seqSet := strings.Join(seqNums, ",")
fetchParts, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
if err != nil {
return nil, fmt.Errorf("IMAP fetch: %w", err)
}
// Each body arrives as a "... BODY[] {N}" line carrying its literal, so
// the pairing is now part of the value rather than something this loop has
// to reconstruct by skipping entries. A message that fails to parse is
// logged and skipped rather than failing the whole sync.
var messages []graphMessage
for _, part := range fetchParts {
if part.HasLiteral && strings.Contains(part.Line, "BODY[]") {
gm, err := parseRawEmail(part.Literal)
if err != nil {
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
continue
}
messages = append(messages, gm)
}
}
// LOGOUT errors are ignored: the emails are already in hand and the
// deferred Close will drop the connection regardless.
c.sendCommand("LOGOUT")
return messages, nil
}
// parseRawEmail parses a raw RFC822 message into the same graphMessage struct
// the Graph API path produces, so everything downstream is source-agnostic.
// An unparseable Date falls back to now, and a missing From leaves both name
// and address empty rather than failing.
func parseRawEmail(raw string) (graphMessage, error) {
msg, err := mail.ReadMessage(strings.NewReader(raw))
if err != nil {
return graphMessage{}, fmt.Errorf("parsing message: %w", err)
}
header := msg.Header
// Parse From
var fromName, fromAddr string
if fromList, err := header.AddressList("From"); err == nil && len(fromList) > 0 {
fromName = fromList[0].Name
fromAddr = fromList[0].Address
}
// Parse Date
dateStr := header.Get("Date")
parsedDate, err := mail.ParseDate(dateStr)
if err != nil {
parsedDate = time.Now()
}
// Extract body text
bodyContent := extractTextBody(msg.Header, msg.Body)
// Dedup is keyed on GraphMessageID: a missing Message-ID header would
// yield "", which collides every headerless message onto one shared row
// (the first one processed, forever). Synthesise an id from stable
// message traits instead — hashing because From/Date/Subject/size are not
// unique alone but their combination is stable across retries.
msgID := header.Get("Message-ID")
if msgID == "" {
hash := sha256.Sum256([]byte(fromAddr + "|" + dateStr + "|" + header.Get("Subject") + "|" + bodyContent))
msgID = "synth-" + hex.EncodeToString(hash[:8])
}
return graphMessage{
ID: msgID,
Subject: decodeHeader(header.Get("Subject")),
ReceivedDateTime: parsedDate.Format(time.RFC3339),
From: graphFrom{
EmailAddress: graphEmailAddress{
Name: fromName,
Address: fromAddr,
},
},
Body: graphBody{
ContentType: "text",
Content: bodyContent,
},
}, nil
}
// extractTextBody pulls readable content out of a message body, preferring
// text/plain and falling back to text/html.
//
// It recurses into nested multipart parts by re-wrapping the part's bytes in a
// synthetic mail.Header carrying just its Content-Type — a shortcut that works
// because this function only ever reads Content-Type.
//
// Quoted-printable and base64 transfer encodings are NOT decoded, so a
// base64-encoded body reaches Claude as base64. Read errors on a part are
// swallowed and the part is skipped.
func extractTextBody(header mail.Header, body io.Reader) string {
contentType := header.Get("Content-Type")
if contentType == "" {
contentType = "text/plain"
}
mediaType, params, err := mime.ParseMediaType(contentType)
if err != nil {
// Try reading as plain text
b, _ := io.ReadAll(body)
return string(b)
}
if strings.HasPrefix(mediaType, "multipart/") {
boundary := params["boundary"]
if boundary == "" {
b, _ := io.ReadAll(body)
return string(b)
}
mr := multipart.NewReader(body, boundary)
var textContent, htmlContent string
for {
part, err := mr.NextPart()
if err != nil {
break
}
partType := part.Header.Get("Content-Type")
partMedia, _, _ := mime.ParseMediaType(partType)
b, err := io.ReadAll(part)
if err != nil {
continue
}
switch partMedia {
case "text/plain":
textContent = string(b)
case "text/html":
htmlContent = string(b)
case "multipart/alternative", "multipart/related", "multipart/mixed":
// Recursively handle nested multipart
nested := extractTextBody(
mail.Header{"Content-Type": {partType}},
strings.NewReader(string(b)),
)
if nested != "" && textContent == "" {
textContent = nested
}
}
}
if textContent != "" {
return textContent
}
return htmlContent
}
b, _ := io.ReadAll(body)
return string(b)
}
// decodeHeader decodes RFC 2047 encoded-words (the "=?UTF-8?Q?...?=" form
// used for non-ASCII subjects), returning the input unchanged if it is not
// encoded or cannot be decoded.
func decodeHeader(s string) string {
dec := new(mime.WordDecoder)
decoded, err := dec.DecodeHeader(s)
if err != nil {
return s
}
return decoded
}
+97
View File
@@ -0,0 +1,97 @@
package services
import "testing"
// These tests cover the status progression rule only — StatusAdvances, the
// predicate extracted out of updateJobApplication. The rest of
// updateJobApplication (note appending, the DB.Save, the returned counters)
// needs a live *gorm.DB and the only driver in go.mod is postgres, so it is
// deliberately not exercised here. Nothing in this file touches the classifier
// or the Graph API either; see email_classify_test.go for the former.
func TestStatusAdvances(t *testing.T) {
cases := []struct {
name string
current string
next string
want bool
}{
{"one step forward is the normal case", "applied", "screening", true},
{"skipping intermediate stages still advances", "applied", "offer", true},
{"adjacent step backwards is refused", "interviewing", "assessment", false},
{"a long way backwards is refused", "offer", "applied", false},
{"same status is not progression, so a duplicate email is a no-op", "screening", "screening", false},
// rejected and withdrawn sit at the top of statusOrder: once an
// application lands there, no later email may move it.
{"rejected cannot fall back to interviewing", "rejected", "interviewing", false},
{"rejected cannot fall back to offer", "rejected", "offer", false},
{"rejected cannot repeat", "rejected", "rejected", false},
{"withdrawn cannot fall back to offer", "withdrawn", "offer", false},
{"withdrawn cannot fall back to rejected", "withdrawn", "rejected", false},
{"withdrawn cannot repeat", "withdrawn", "withdrawn", false},
// The one ordering asymmetry between the two terminals: withdrawn
// ranks above rejected, so this single pair is allowed.
{"rejected may still become withdrawn because withdrawn ranks higher", "rejected", "withdrawn", true},
// saved is a browser capture that has not been applied to yet.
{"a saved posting advances once the application is confirmed", "saved", "applied", true},
{"an applied row cannot fall back to saved", "applied", "saved", false},
{"an unknown new status is never applied", "applied", "hired", false},
{"an empty new status is never applied", "applied", "", false},
{"an unknown new status cannot escape a terminal state either", "rejected", "ghosted", false},
{"a recognised status takes over from an unknown current status", "ghosted", "applied", true},
{"a recognised status takes over from an empty current status", "", "offer", true},
{"unknown to unknown stays put", "ghosted", "hired", false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := StatusAdvances(c.current, c.next); got != c.want {
t.Errorf("StatusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want)
}
})
}
}
// Guards the claim the other tests rest on: rejected and withdrawn really are
// the top of the ranking, so adding a stage below them cannot silently make
// them non-terminal.
func TestTerminalStatusesRankHighest(t *testing.T) {
for status, order := range statusOrder {
if status == "rejected" || status == "withdrawn" {
continue
}
if order >= statusOrder["rejected"] {
t.Errorf("%q ranks %d, at or above rejected (%d)", status, order, statusOrder["rejected"])
}
}
}
// NormalizeStatus is the guard that keeps Claude's occasional casing drift
// ("Interview", "on hold") out of the status column: an unrecognised value
// stored verbatim makes StatusAdvances treat the row's current status as
// unknown, which switches the forward-only rule off for that row entirely.
func TestNormalizeStatus(t *testing.T) {
cases := []struct {
name string
in string
want string
}{
{"a tracked status passes through", "interviewing", "interviewing"},
{"saved is tracked, so a capture keeps it", "saved", "saved"},
{"casing drift is lowered, not rejected", "Interviewing", "interviewing"},
{"surrounding whitespace is trimmed", " offer ", "offer"},
{"an untracked status falls back to the pipeline default", "on hold", "applied"},
{"the UI's old Title Case value is recognised once lowered", "Rejected", "rejected"},
{"a value the UI once allowed but the pipeline never had is rejected", "Interview", "applied"},
{"empty falls back rather than storing a blank status", "", "applied"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := NormalizeStatus(c.in); got != c.want {
t.Errorf("NormalizeStatus(%q) = %q, want %q", c.in, got, c.want)
}
})
}
}
+977
View File
@@ -0,0 +1,977 @@
package services
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"adam-french.co.uk/job-tracker/internal/claude"
"adam-french.co.uk/job-tracker/internal/models"
"golang.org/x/oauth2"
"gorm.io/gorm"
)
// This file is the job-application email pipeline. On a timer it fetches
// recent mail (via Microsoft Graph or plain IMAP), keeps the ones that look
// recruitment-related, asks Claude to turn each into structured data, and
// creates or advances a models.JobApplication row. Every email it has looked
// at is recorded as a models.ProcessedEmail so it is never handled twice.
//
// The Claude call itself is not made here: the prompt and the parsing of the
// model's reply live in internal/claude (email.go), reached through the
// Classifier field. Everything that needs the mailbox or the database —
// fetching, the pre-filter, dedup and retry accounting, matching an email to
// an application, the forward-only status rule — stays in this file.
// MSGraphTokenFile is the saved OAuth session's file name inside the data
// directory, which is a Docker volume so the refresh token survives restarts.
const MSGraphTokenFile = "msgraph_token.json"
// EmailSyncConfig configures the pipeline. Backend picks the mail source;
// anything other than "graph" or "imap" leaves the service permanently idle.
type EmailSyncConfig struct {
Backend string // "graph" or "imap"
ClientID string
ClientSecret string
TenantID string
RedirectURI string
IMAP *IMAPConfig
SyncInterval time.Duration
Enabled bool
// TokenPath is where the Graph OAuth session is saved
// (DATA_DIR/MSGraphTokenFile).
TokenPath string
}
// EmailSyncService owns the sync pipeline.
type EmailSyncService struct {
Config *EmailSyncConfig
OAuthConfig *oauth2.Config
// HTTPClient doubles as the readiness flag: nil means "not configured or
// not yet authenticated", and both the scheduler and the manual-trigger
// handler refuse to run while it is nil. On the Graph backend it is a
// real token-injecting client; on the IMAP backend it is set to
// http.DefaultClient purely so this check passes (IMAP never uses it).
HTTPClient *http.Client
DB *gorm.DB
// Classifier makes the Claude call (normally a *claude.Client; the tests
// substitute a fake).
Classifier EmailClassifier
// mu is used with TryLock, not Lock: it makes a sync a no-op while
// another one is running rather than queueing behind it, so the manual
// admin trigger cannot pile up on top of the scheduled run.
mu sync.Mutex
}
// Microsoft Graph API response types
// Microsoft Graph API response types. The IMAP backend parses raw RFC822
// messages into these same structs (see parseRawEmail) so that everything
// downstream of fetchEmails is backend-agnostic.
// graphMessagesResponse is one page of /me/messages; NextLink is Graph's
// cursor for the next page and is empty on the last one.
type graphMessagesResponse struct {
Value []graphMessage `json:"value"`
NextLink string `json:"@odata.nextLink"`
}
// graphMessage is a single email.
type graphMessage struct {
ID string `json:"id"`
Subject string `json:"subject"`
ReceivedDateTime string `json:"receivedDateTime"`
From graphFrom `json:"from"`
Body graphBody `json:"body"`
BodyPreview string `json:"bodyPreview"`
}
// graphFrom wraps the sender, which Graph nests one level deep.
type graphFrom struct {
EmailAddress graphEmailAddress `json:"emailAddress"`
}
// graphEmailAddress is a display name plus address.
type graphEmailAddress struct {
Name string `json:"name"`
Address string `json:"address"`
}
// graphBody is the message body; ContentType is "html" or "text".
type graphBody struct {
ContentType string `json:"contentType"`
Content string `json:"content"`
}
// Classifier response type
// EmailAnalysis is Claude's verdict on one email (see internal/claude). Only
// IsJobEmail can be relied on; the other fields may be zero.
type EmailAnalysis = claude.EmailAnalysis
// Email filtering config
// Cheap pre-filter, applied before any classifier call so that the bulk of a
// mailbox never costs an API request. It is intentionally over-inclusive:
// false positives are cheap (Claude rejects them), false negatives are not
// (the email is never looked at again once its window has passed).
// subjectKeywords match case-insensitively anywhere in the subject line.
var subjectKeywords = []string{
"application", "interview", "offer", "rejected", "assessment",
"applied", "candidate", "position", "role", "hiring",
"thank you for applying", "we regret", "move forward",
"next steps", "coding challenge", "take-home",
}
// senderDomains are applicant-tracking systems; mail from any of them is
// considered job-related whatever the subject says.
var senderDomains = []string{
"greenhouse.io", "lever.co", "workday.com", "myworkday.com",
"ashbyhq.com", "smartrecruiters.com", "icims.com",
"jobvite.com", "taleo.net", "breezy.hr", "recruitee.com",
"applytojob.com", "jazz.co", "dover.com",
}
// Status progression order
// statusOrder ranks the application lifecycle so updates can only move an
// application forwards (see updateJobApplication). A status missing from this
// map is treated as unknown and never applied. Note that "rejected" and
// "withdrawn" sit at the top, so once an application reaches them nothing can
// move it back.
//
// "saved" is the one status no email can produce: it marks a posting captured
// from the browser but not applied to yet (handlers/handle_job_capture.go).
// It ranks lowest so that the "thanks for applying" email advances the row.
//
// This map is the vocabulary. It is written down in four other places, which
// must list the same statuses: `enum JobStatus` in
// graph/schema/job_application.graphql (enforced —
// TestJobStatusEnumMatchesStatusOrder fails on any difference), the
// classifier prompt in internal/claude/email.go (all but "saved"; also
// enforced, by TestClassifierStatusesMatchStatusOrder), the tracker page and
// the capture userscript.
var statusOrder = map[string]int{
"saved": 0,
"applied": 1,
"screening": 2,
"assessment": 3,
"interviewing": 4,
"offer": 5,
"rejected": 6,
"withdrawn": 7,
}
// Token persistence
// SaveMSGraphToken persists an OAuth token to disk with 0600 permissions.
// Like the Spotify equivalent it copies into a local struct so the on-disk
// shape does not depend on the oauth2 package's own JSON tags.
func SaveMSGraphToken(path string, tok *oauth2.Token) error {
data := struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
Expiry time.Time `json:"expiry"`
}{
AccessToken: tok.AccessToken,
RefreshToken: tok.RefreshToken,
TokenType: tok.TokenType,
Expiry: tok.Expiry,
}
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return fmt.Errorf("creating token directory: %w", err)
}
jsonBytes, err := json.MarshalIndent(data, "", " ")
if err != nil {
return err
}
return os.WriteFile(path, jsonBytes, 0600)
}
// LoadMSGraphToken reads a token written by SaveMSGraphToken. A missing file
// is reported as an error and means "not yet authenticated".
func LoadMSGraphToken(path string) (*oauth2.Token, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var saved struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
Expiry time.Time `json:"expiry"`
}
if err := json.Unmarshal(data, &saved); err != nil {
return nil, err
}
return &oauth2.Token{
AccessToken: saved.AccessToken,
RefreshToken: saved.RefreshToken,
TokenType: saved.TokenType,
Expiry: saved.Expiry,
}, nil
}
// persistingTokenSource wraps an oauth2.TokenSource to save refreshed tokens to disk.
type persistingTokenSource struct {
base oauth2.TokenSource
path string
lastToken *oauth2.Token
}
// Token returns a valid token, refreshing through the wrapped source when
// needed and writing any new token back to disk.
//
// Without this wrapper the oauth2 client would refresh happily in memory but
// the file on disk would keep the original refresh token; Microsoft rotates
// refresh tokens, so after the original expired the service would have to be
// re-authorised by hand on the next restart.
//
// There is no mutex here even though oauth2's client may call Token from
// several goroutines. In practice syncs are serialised by EmailSyncService.mu
// so concurrent calls do not arise; the worst case if they ever did is a
// duplicate write of the same token.
func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
tok, err := p.base.Token()
if err != nil {
return nil, err
}
// Save only when the token actually changed (i.e. was refreshed)
if p.lastToken == nil || tok.AccessToken != p.lastToken.AccessToken {
p.lastToken = tok
if saveErr := SaveMSGraphToken(p.path, tok); saveErr != nil {
log.Printf("[EmailSync] Warning: failed to persist refreshed token: %v", saveErr)
}
}
return tok, nil
}
// InitEmailSync builds the service and, for the Graph backend, restores a
// saved OAuth session. It never fails: a misconfigured or unauthenticated
// service is returned with a nil HTTPClient, which leaves the pipeline idle
// while the rest of the backend starts normally. For Graph, the authorisation
// URL is printed to the container log for a one-off manual sign-in that
// lands on GET /email/callback.
//
// classifier is not probed: a missing API key shows up as each email failing
// and being retried.
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, classifier EmailClassifier) *EmailSyncService {
svc := &EmailSyncService{
Config: config,
DB: db,
Classifier: classifier,
}
switch config.Backend {
case "imap":
if config.IMAP == nil || config.IMAP.Email == "" {
log.Println("[EmailSync] IMAP backend selected but not configured")
return svc
}
// IMAP connects per-sync, no persistent client needed.
// Mark as ready by setting a non-nil HTTPClient (used as readiness flag).
svc.HTTPClient = http.DefaultClient
log.Printf("[EmailSync] Configured with IMAP backend (%s)", config.IMAP.Host)
case "graph":
oauthConfig := &oauth2.Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
Endpoint: oauth2.Endpoint{
AuthURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/authorize", config.TenantID),
TokenURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/token", config.TenantID),
},
RedirectURL: config.RedirectURI,
Scopes: []string{"https://graph.microsoft.com/Mail.Read", "offline_access"},
}
svc.OAuthConfig = oauthConfig
token, err := LoadMSGraphToken(config.TokenPath)
if err != nil || token == nil {
authURL := oauthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
log.Println("[EmailSync] No token saved. Authenticate Microsoft Graph with:")
log.Println(authURL)
return svc
}
baseSource := oauthConfig.TokenSource(context.Background(), token)
persistSource := &persistingTokenSource{base: baseSource, path: config.TokenPath, lastToken: token}
svc.HTTPClient = oauth2.NewClient(context.Background(), persistSource)
log.Println("[EmailSync] Authenticated with Microsoft Graph")
default:
log.Printf("[EmailSync] Unknown backend %q, defaulting to disabled", config.Backend)
}
return svc
}
// AuthURL returns the OAuth2 authorization URL for initial setup.
func (s *EmailSyncService) AuthURL() string {
return s.OAuthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
}
// CompleteAuth exchanges an authorization code for a token and initializes the HTTP client.
func (s *EmailSyncService) CompleteAuth(ctx context.Context, code string) error {
token, err := s.OAuthConfig.Exchange(ctx, code)
if err != nil {
return fmt.Errorf("token exchange failed: %w", err)
}
if err := SaveMSGraphToken(s.Config.TokenPath, token); err != nil {
return fmt.Errorf("saving token: %w", err)
}
baseSource := s.OAuthConfig.TokenSource(ctx, token)
persistSource := &persistingTokenSource{base: baseSource, path: s.Config.TokenPath, lastToken: token}
s.HTTPClient = oauth2.NewClient(ctx, persistSource)
log.Println("[EmailSync] Authentication completed successfully")
return nil
}
// StartScheduler runs SyncEmails immediately and then on every tick until ctx
// is cancelled. It is meant to be run in its own goroutine and returns
// straight away when the service is disabled or unauthenticated.
//
// Because readiness is only checked once here, authenticating later via
// /email/callback does NOT start the scheduler; the backend has to be
// restarted, or syncs triggered by hand through POST /email/sync.
func (s *EmailSyncService) StartScheduler(ctx context.Context) {
if !s.Config.Enabled {
log.Println("[EmailSync] Disabled, skipping scheduler")
return
}
if s.HTTPClient == nil {
log.Println("[EmailSync] Not authenticated, skipping scheduler")
return
}
log.Printf("[EmailSync] Starting scheduler, interval: %s", s.Config.SyncInterval)
// Run once immediately on startup
if err := s.SyncEmails(ctx); err != nil {
log.Printf("[EmailSync] Initial sync error: %v", err)
}
ticker := time.NewTicker(s.Config.SyncInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
log.Println("[EmailSync] Scheduler stopped")
return
case <-ticker.C:
if err := s.SyncEmails(ctx); err != nil {
log.Printf("[EmailSync] Sync error: %v", err)
}
}
}
}
// SyncEmails is the main pipeline: fetch, filter, dedup, classify, create/update.
func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
// TryLock, so a manual trigger during a scheduled run is rejected
// immediately instead of blocking a request for minutes.
if !s.mu.TryLock() {
return fmt.Errorf("sync already in progress")
}
defer s.mu.Unlock()
// Registered after the unlock defer, therefore it runs BEFORE it: the
// panic is absorbed here and the mutex is still released afterwards.
// A recovered panic makes SyncEmails return nil, so the caller sees a
// successful sync — the log line is the only evidence.
defer func() {
if r := recover(); r != nil {
log.Printf("[EmailSync] PANIC recovered: %v", r)
}
}()
log.Println("[EmailSync] Starting sync...")
// Window start comes from the newest email we have ever *received* (one of
// two clocks in play) rather than from when we processed it: receive time
// lags processing time by up to one sync duration, and a later window
// anchored to processing time would start AFTER mail that arrived just at
// the previous fetch — a permanent hole (the overlap the code always meant
// to have is produced only when both edges speak the same clock).
// Anchoring on ReceivedAt keeps the window behind the fetch, the
// ProcessedEmail dedup absorbs the deliberate re-fetch overlap, and on a
// cold database it falls back to the last 24 hours so the pipeline never
// tries to ingest an entire mailbox.
since := time.Now().Add(-24 * time.Hour)
var latest models.ProcessedEmail
if err := s.DB.Where("received_at > ?", time.Time{}).Order("received_at DESC").First(&latest).Error; err == nil {
// Pull the window back one slack period so mail delivered a second or
// two after the last fetch (or indexed late by the provider) is still
// inside the next window; dedup makes re-processing it harmless.
since = latest.ReceivedAt.Add(-fetchSlack)
}
// Pull the window back to cover any still-retryable failure. Without this
// the clamp above would have advanced past a failed email — the error row
// is written now, so the next window starts after it — and the retry
// below could never see the email again. Rows predating ReceivedAt have
// a zero value and are ignored rather than dragging the window to 0001.
//
// Old failures are age-capped: attempts only advance when the email is
// actually re-fetched, so a message that has left the mailbox would stay
// under the cap forever and rewind every sync on this day's fetch. After
// maxRewindAge the email is treated as gone, like any abandoned retry.
var oldestRetryable models.ProcessedEmail
if err := s.DB.
Where("action = ? AND attempts < ? AND received_at > ? AND received_at > ?",
"error", maxEmailAttempts, time.Time{}, time.Now().Add(-maxRewindAge)).
Order("received_at ASC").
First(&oldestRetryable).Error; err == nil && oldestRetryable.ReceivedAt.Before(since) {
log.Printf("[EmailSync] Rewinding window to %s to retry a previous failure",
oldestRetryable.ReceivedAt.Format(time.RFC3339))
since = oldestRetryable.ReceivedAt
}
// Fetch emails from Microsoft Graph
emails, err := s.fetchEmails(ctx, since)
if err != nil {
return fmt.Errorf("fetching emails: %w", err)
}
log.Printf("[EmailSync] Fetched %d emails since %s", len(emails), since.Format(time.RFC3339))
// Filter by subject/sender patterns
filtered := s.filterEmails(emails)
log.Printf("[EmailSync] %d emails passed filters", len(filtered))
var created, updated, skipped, errored int
for _, email := range filtered {
// Dedup check. A row is terminal — and so genuinely skippable — if it
// succeeded, or if it failed the maximum number of times. A row that
// failed but has attempts left is deliberately NOT skipped: it is
// reprocessed below and the same row updated, so a transient Claude
// or network outage no longer drops the email permanently.
var existing models.ProcessedEmail
found := s.DB.Where("graph_message_id = ?", email.ID).First(&existing).Error == nil
if found && !retryableFailure(&existing) {
skipped++
continue
}
if found {
log.Printf("[EmailSync] Retrying previously failed email %q (attempt %d of %d)",
email.Subject, existing.Attempts+1, maxEmailAttempts)
}
action, jobAppID, processErr := s.processEmail(ctx, email)
// The row carries the outcome either way. On failure the attempt
// counter advances, so repeated failures walk the row towards the cap
// and it eventually stops being retried. A cancelled sync (the admin
// closed the tab mid-backlog, or nginx cut the request) is not a
// failure of the email, though: attempts must not advance for it, or
// two closed tabs would strand a healthy email at the cap and skip it
// forever. Writing nothing preserves the existing row untouched, so it
// is simply retried at the next sync.
if processErr != nil && errors.Is(processErr, context.Canceled) {
skipped++
continue
}
record := models.ProcessedEmail{
GraphMessageID: email.ID,
Subject: truncate(email.Subject, 255),
Action: action,
JobAppID: jobAppID,
ReceivedAt: parseReceivedAt(email.ReceivedDateTime),
Attempts: existing.Attempts + 1,
}
if processErr != nil {
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
record.Action = "error"
record.JobAppID = nil
if record.Attempts >= maxEmailAttempts {
log.Printf("[EmailSync] Email %q has failed %d times; giving up on it",
email.Subject, record.Attempts)
}
s.saveProcessed(found, &existing, &record)
errored++
continue
}
s.saveProcessed(found, &existing, &record)
switch action {
case "created":
created++
case "updated":
updated++
default:
skipped++
}
}
log.Printf("[EmailSync] Sync complete: %d fetched, %d filtered, %d created, %d updated, %d skipped, %d errors",
len(emails), len(filtered), created, updated, skipped, errored)
return nil
}
// fetchEmails retrieves emails since the given time using the configured
// backend, normalising both into []graphMessage.
func (s *EmailSyncService) fetchEmails(ctx context.Context, since time.Time) ([]graphMessage, error) {
if s.Config.Backend == "imap" {
return s.fetchEmailsIMAP(since)
}
return s.fetchEmailsGraph(ctx, since)
}
// fetchEmailsGraph retrieves emails from the Microsoft Graph API since the given time.
func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time) ([]graphMessage, error) {
var all []graphMessage
sinceStr := since.UTC().Format("2006-01-02T15:04:05Z")
params := url.Values{
"$filter": {fmt.Sprintf("receivedDateTime ge %s", sinceStr)},
"$select": {"id,subject,from,receivedDateTime,body,bodyPreview"},
"$top": {"50"},
"$orderby": {"receivedDateTime asc"},
}
// Graph paginates with @odata.nextLink, which already carries every query
// parameter, so the loop below only builds this first URL by hand.
nextURL := fmt.Sprintf("https://graph.microsoft.com/v1.0/me/messages?%s", params.Encode())
for nextURL != "" {
req, err := http.NewRequestWithContext(ctx, "GET", nextURL, nil)
if err != nil {
return nil, err
}
resp, err := s.HTTPClient.Do(req)
if err != nil {
return nil, err
}
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
// Status is checked before the read error so that a non-200 reports
// Graph's own error body rather than a generic read failure.
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Graph API returned %d: %s", resp.StatusCode, string(body))
}
if err != nil {
return nil, err
}
var result graphMessagesResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("parsing response: %w", err)
}
all = append(all, result.Value...)
nextURL = result.NextLink
}
return all, nil
}
// filterEmails returns only emails that match subject keywords or sender domains.
func (s *EmailSyncService) filterEmails(emails []graphMessage) []graphMessage {
var matched []graphMessage
for _, email := range emails {
if s.matchesFilter(email) {
matched = append(matched, email)
}
}
return matched
}
// matchesFilter reports whether an email looks job-related on subject or
// sender alone. See subjectKeywords for why this errs towards including too
// much.
func (s *EmailSyncService) matchesFilter(email graphMessage) bool {
subjectLower := strings.ToLower(email.Subject)
for _, kw := range subjectKeywords {
if strings.Contains(subjectLower, kw) {
return true
}
}
senderAddr := strings.ToLower(email.From.EmailAddress.Address)
for _, domain := range senderDomains {
if strings.HasSuffix(senderAddr, "@"+domain) || strings.HasSuffix(senderAddr, "."+domain) {
return true
}
}
return false
}
// EmailClassifier is the one Claude call the pipeline makes.
type EmailClassifier interface {
ClassifyEmail(ctx context.Context, message string) (EmailAnalysis, error)
}
// maxClassifyRunes bounds what is sent to Claude for one email.
// cleanEmailBody already caps the body far below this, so the limit only
// bites on a pathological subject or sender.
const maxClassifyRunes = 200_000
// classifierMessage formats one email as the classifier's user turn: Subject,
// From and Date lines, a blank line, then the cleaned body. It goes to Claude
// unchanged, so this layout is part of what the prompt in
// internal/claude/email.go was written against.
//
// The result is cut to maxClassifyRunes on a rune boundary. The body comes
// last, so it is what gives way first.
func classifierMessage(email graphMessage) string {
msg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
email.Subject,
email.From.EmailAddress.Name,
email.From.EmailAddress.Address,
email.ReceivedDateTime,
cleanEmailBody(email.Body.Content, email.Body.ContentType),
)
// Counting runes means converting; skip it for the ordinary case, where
// even the byte length (never less than the rune count) is under the cap.
if len(msg) <= maxClassifyRunes {
return msg
}
runes := []rune(msg)
if len(runes) <= maxClassifyRunes {
return msg
}
return string(runes[:maxClassifyRunes])
}
// classifyEmail asks Claude what an email is. Every failure — Claude failing,
// no API key, a reply that will not decode — comes back as an error, which
// SyncEmails records as a retryable failure of this email.
func (s *EmailSyncService) classifyEmail(ctx context.Context, email graphMessage) (EmailAnalysis, error) {
analysis, err := s.Classifier.ClassifyEmail(ctx, classifierMessage(email))
if err != nil {
// %w keeps context.Canceled visible to SyncEmails, which must not
// count an abandoned sync against the email.
return EmailAnalysis{}, fmt.Errorf("classifying email: %w", err)
}
return analysis, nil
}
// processEmail has a single email classified and creates/updates a JobApplication.
// Returns the action taken ("created", "updated", "skipped") and the job application ID if applicable.
func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) (string, *uint, error) {
analysis, err := s.classifyEmail(ctx, email)
if err != nil {
return "", nil, err
}
if !analysis.IsJobEmail {
return "skipped", nil, nil
}
if analysis.Company == "" || analysis.JobTitle == "" {
return "skipped", nil, nil
}
// Applications are identified by (company, job title) compared
// case-insensitively — there is no external id to match on. Claude
// wording the same role slightly differently therefore creates a second
// application rather than updating the first. The most recent match wins
// when there are several.
// The lookup is Unscoped: a deleted-with-notes row is stored, not purged
// (see models.JobApplication), so invisibility here makes the matcher
// believe the application never existed and a follow-up email in the same
// thread re-creates it — the admin deletes it, it comes back. A hit on a
// deleted row instead becomes a suppression: nothing is updated, nothing
// is created, and the pipeline leaves the deletion to stand.
var existing models.JobApplication
found := s.DB.Unscoped().Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)",
analysis.Company, analysis.JobTitle).
Order("created_at DESC").
First(&existing).Error == nil
if found && existing.DeletedAt.Valid {
return "skipped", nil, nil
}
if found && analysis.Action == "update" {
return s.updateJobApplication(&existing, &analysis)
}
if !found {
return s.createJobApplication(&analysis)
}
// Found but action is "create" — the record already exists, skip
return "skipped", &existing.ID, nil
}
// NormalizeStatus coerces Claude's status guess into the tracked vocabulary,
// lowering the case it occasionally drifts on and rejecting anything outside
// statusOrder. An unrecognised status stored verbatim would disable the
// forward-only guard for that row (updateJobApplication allows any recognised
// status over an unknown one), so the safe fallback is the pipeline's default.
//
// It is for values that arrive outside GraphQL: the classifier's answer and
// the capture endpoint's body. The GraphQL mutations do not use it — their
// status is a JobStatus, which UnmarshalJobStatus refuses outright when it is
// not in the vocabulary rather than quietly storing "applied".
func NormalizeStatus(s string) string {
lowered := strings.ToLower(strings.TrimSpace(s))
if _, ok := statusOrder[lowered]; ok {
return lowered
}
return "applied"
}
// createJobApplication inserts a new application from Claude's analysis.
func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) {
app := models.JobApplication{
Company: analysis.Company,
JobTitle: analysis.JobTitle,
Status: NormalizeStatus(analysis.Status),
Location: analysis.Location,
URL: analysis.URL,
Notes: analysis.Notes,
}
// The prompt asks for YYYY-MM-DD but full RFC3339 comes back often enough
// to be worth trying first; an unparseable date is dropped silently.
if analysis.AppliedAt != nil {
if t, err := time.Parse(time.RFC3339, *analysis.AppliedAt); err == nil {
app.AppliedAt = &t
} else if t, err := time.Parse("2006-01-02", *analysis.AppliedAt); err == nil {
app.AppliedAt = &t
}
}
if app.Status == "" {
app.Status = "applied"
}
if err := s.DB.Create(&app).Error; err != nil {
return "", nil, fmt.Errorf("creating job application: %w", err)
}
log.Printf("[EmailSync] Created job application: %s at %s (status: %s)", app.JobTitle, app.Company, app.Status)
return "created", &app.ID, nil
}
// StatusAdvances reports whether next is a forward move from current through
// statusOrder. Emails commonly arrive out of order (a delayed "thanks for
// applying" after an interview invite), and this is what stops a stale email
// dragging an application backwards. An unknown next status is never applied;
// an unknown current status is treated as "anywhere before the start", so any
// recognised status can take over from it.
//
// Exported because the browser capture endpoint applies the same rule.
func StatusAdvances(current, next string) bool {
nextOrder, nextExists := statusOrder[next]
currentOrder, currentExists := statusOrder[current]
return nextExists && (!currentExists || nextOrder > currentOrder)
}
// updateJobApplication advances an existing application's status, but only
// ever forwards (see StatusAdvances).
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
if !StatusAdvances(existing.Status, analysis.Status) {
return "skipped", &existing.ID, nil
}
existing.Status = analysis.Status
// A row captured as "saved" has no applied date; the email that moves it
// to "applied" is the best evidence of when that happened.
if existing.AppliedAt == nil && existing.Status == "applied" {
now := time.Now()
existing.AppliedAt = &now
}
// Append to notes if Claude provided any
if analysis.Notes != nil && *analysis.Notes != "" {
if existing.Notes != nil && *existing.Notes != "" {
combined := *existing.Notes + "\n" + *analysis.Notes
existing.Notes = &combined
} else {
existing.Notes = analysis.Notes
}
}
if err := s.DB.Save(existing).Error; err != nil {
return "", nil, fmt.Errorf("updating job application: %w", err)
}
log.Printf("[EmailSync] Updated job application: %s at %s (status: %s)", existing.JobTitle, existing.Company, existing.Status)
return "updated", &existing.ID, nil
}
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
// the classifier, cutting token cost and noise.
//
// The HTML handling is a regex tag-strip, not a parser: fine for extracting
// prose, but it would mangle inline <script>/<style> content and mis-handle
// tags inside attribute values. That is acceptable because the output is only
// ever read by a language model, never rendered.
func cleanEmailBody(content string, contentType string) string {
text := content
if strings.EqualFold(contentType, "html") {
// Strip HTML tags
tagRegex := regexp.MustCompile(`<[^>]*>`)
text = tagRegex.ReplaceAllString(text, " ")
// Decode common HTML entities
replacer := strings.NewReplacer(
"&nbsp;", " ",
"&amp;", "&",
"&lt;", "<",
"&gt;", ">",
"&quot;", `"`,
"&#39;", "'",
"&apos;", "'",
)
text = replacer.Replace(text)
}
// Collapse whitespace
spaceRegex := regexp.MustCompile(`[ \t]+`)
text = spaceRegex.ReplaceAllString(text, " ")
nlRegex := regexp.MustCompile(`\n{3,}`)
text = nlRegex.ReplaceAllString(text, "\n\n")
text = strings.TrimSpace(text)
// Cut everything from the first signature marker onwards. The idx > 0
// test (not >= 0) means a body that begins with a marker is left alone,
// which avoids blanking the whole message.
sigPatterns := []string{
"\n-- \n",
"\nSent from my iPhone",
"\nSent from my iPad",
"\nGet Outlook for",
}
for _, pattern := range sigPatterns {
if idx := strings.Index(text, pattern); idx > 0 {
text = text[:idx]
}
}
// Remove forwarded email chains
lines := strings.Split(text, "\n")
var cleaned []string
for _, line := range lines {
if strings.HasPrefix(strings.TrimSpace(line), ">") {
continue
}
cleaned = append(cleaned, line)
}
text = strings.Join(cleaned, "\n")
// Cap the prompt size. This slices by bytes, so a cut can land mid-rune
// and leave an invalid UTF-8 tail. That is harmless: the text travels to
// the classifier as JSON, and encoding/json replaces the broken tail with
// U+FFFD rather than emitting invalid UTF-8.
if len(text) > 4000 {
text = text[:4000]
}
return strings.TrimSpace(text)
}
// truncate caps a string at maxLen bytes (not runes) before it is stored in
// ProcessedEmail.Subject.
func truncate(s string, maxLen int) string {
if len(s) <= maxLen {
return s
}
return s[:maxLen]
}
// maxEmailAttempts caps how many times a failing email is reprocessed. Each
// attempt costs a Claude call, so the cap is what stops one permanently
// unparseable email billing on every sync forever. Three gives a transient
// outage two further chances across subsequent syncs.
const maxEmailAttempts = 3
// fetchSlack pulls each sync's window edge back by this much so mail that was
// delayed between fetch and filter (or index-registered late) is still caught
// by the next window. Consumers pay for it with deliberate re-fetches, which
// the ProcessedEmail dedup makes free.
const fetchSlack = 30 * time.Second
// maxRewindAge stops a stuck retry from pinning the window open forever. A
// failed email is only rewound for while it is younger than this; past that it
// has probably been deleted from the mailbox or fallen out of the provider's
// returns, so re-fetching for it would never yield anything.
const maxRewindAge = 7 * 24 * time.Hour
// retryableFailure reports whether a previously recorded email should be
// processed again. Only failures are retried, and only while they have
// attempts left; anything that succeeded is terminal.
func retryableFailure(row *models.ProcessedEmail) bool {
return row.Action == "error" && row.Attempts < maxEmailAttempts
}
// parseReceivedAt converts the provider's timestamp to a time.Time, returning
// the zero value if it is missing or malformed. A zero value is safe: it only
// means this row cannot pull the fetch window back, so the email is retried
// on the next sync that happens to cover it rather than being chased.
func parseReceivedAt(raw string) time.Time {
if raw == "" {
return time.Time{}
}
received, err := time.Parse(time.RFC3339, raw)
if err != nil {
log.Printf("[EmailSync] Unparseable receivedDateTime %q: %v", raw, err)
return time.Time{}
}
return received
}
// saveProcessed writes the outcome of an attempt: updating the existing row
// when this was a retry, inserting when it is the first attempt. Update is
// used rather than Save so the row keeps its original CreatedAt, which the
// fetch window depends on.
func (s *EmailSyncService) saveProcessed(found bool, existing, record *models.ProcessedEmail) {
var err error
if found {
err = s.DB.Model(existing).Updates(map[string]any{
"action": record.Action,
"job_app_id": record.JobAppID,
"attempts": record.Attempts,
"received_at": record.ReceivedAt,
}).Error
} else {
err = s.DB.Create(record).Error
}
// Logged rather than returned: a bookkeeping failure must not abort the
// rest of the batch. It does mean the email is reprocessed next sync,
// which the dedup treats as a first attempt.
if err != nil {
log.Printf("[EmailSync] Failed to record processed email %q: %v", record.Subject, err)
}
}
+210
View File
@@ -0,0 +1,210 @@
package services
import (
"strings"
"testing"
"time"
"adam-french.co.uk/job-tracker/internal/models"
)
// These tests cover the pure helpers of the email sync: body cleaning,
// truncation, timestamp parsing, the retry predicate and the filter. The
// classify step, which goes through the EmailClassifier interface, is covered in
// email_classify_test.go. What is left uncovered — token acquisition, the
// Graph paging loop, and the create/update paths processEmail ends in — needs
// either a live *gorm.DB or a Microsoft Graph endpoint, neither of which
// exists in a test run.
//
// matchesFilter is a method but reads no field of the receiver (it matches
// against the package-level subjectKeywords/senderDomains), which is why a
// zero-value &EmailSyncService{} is a legitimate receiver below.
func TestCleanEmailBody(t *testing.T) {
cases := []struct {
name string
content string
contentType string
want string
}{
{
"html tags are stripped and entities decoded",
"<p>Hi&nbsp;Adam &amp; team</p><b>thanks</b>",
"html",
"Hi Adam & team thanks",
},
{
"contentType match is case-insensitive",
"<p>hello</p>",
"HTML",
"hello",
},
{
// Entities are only decoded on the HTML path, so plain text keeps
// them verbatim rather than being silently rewritten.
"text bodies are not entity-decoded",
"a &amp; b",
"text",
"a &amp; b",
},
{
"runs of spaces and tabs collapse to one space",
"one \t two",
"text",
"one two",
},
{
"three or more newlines collapse to a blank line",
"a\n\n\n\n\nb",
"text",
"a\n\nb",
},
{
"signature marker cuts the tail",
"body text\n-- \nAdam French\n07000",
"text",
"body text",
},
{
"Sent from my iPhone is treated as a signature",
"see attached\nSent from my iPhone",
"text",
"see attached",
},
{
// idx > 0, not >= 0: a body that is nothing but a signature would
// otherwise be blanked entirely, losing the only content there is.
"a body starting with a signature marker is left intact",
"Sent from my iPhone\nreal content",
"text",
"Sent from my iPhone\nreal content",
},
{
"quoted lines are dropped",
"my reply\n> their mail\n > indented quote\nmore reply",
"text",
"my reply\nmore reply",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := cleanEmailBody(c.content, c.contentType); got != c.want {
t.Fatalf("cleanEmailBody(%q, %q) = %q, want %q", c.content, c.contentType, got, c.want)
}
})
}
}
// The 4000-byte cap is what bounds the prompt cost, so it gets its own test:
// the cut is by bytes and is applied before the final TrimSpace.
func TestCleanEmailBodyCap(t *testing.T) {
got := cleanEmailBody(strings.Repeat("a", 5000), "text")
if len(got) != 4000 {
t.Fatalf("len = %d, want 4000", len(got))
}
// A body exactly at the cap must pass through untouched.
exact := strings.Repeat("b", 4000)
if got := cleanEmailBody(exact, "text"); got != exact {
t.Fatalf("body at the cap was modified: len = %d", len(got))
}
}
func TestTruncate(t *testing.T) {
cases := []struct {
name string
s string
maxLen int
want string
}{
{"shorter than the cap is unchanged", "abc", 10, "abc"},
{"exactly at the cap is unchanged", "abcde", 5, "abcde"},
{"longer is cut to the cap", "abcdef", 3, "abc"},
{"zero cap yields the empty string", "abc", 0, ""},
{"empty input", "", 5, ""},
// Bytes, not runes: the cut can land mid-rune. Asserted so the
// behaviour is a documented choice rather than a lurking surprise.
{"multi-byte runes are cut by byte", "é", 1, "\xc3"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := truncate(c.s, c.maxLen); got != c.want {
t.Fatalf("truncate(%q, %d) = %q, want %q", c.s, c.maxLen, got, c.want)
}
})
}
}
func TestParseReceivedAt(t *testing.T) {
cases := []struct {
name string
raw string
want time.Time
}{
{"valid RFC3339", "2024-03-15T10:30:00Z", time.Date(2024, 3, 15, 10, 30, 0, 0, time.UTC)},
{"empty means no timestamp", "", time.Time{}},
{"malformed falls back to zero rather than failing the sync", "15/03/2024", time.Time{}},
{"a date without a time is not RFC3339", "2024-03-15", time.Time{}},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := parseReceivedAt(c.raw); !got.Equal(c.want) {
t.Fatalf("parseReceivedAt(%q) = %v, want %v", c.raw, got, c.want)
}
})
}
}
func TestRetryableFailure(t *testing.T) {
cases := []struct {
name string
action string
attempts int
want bool
}{
{"a failure with attempts left is retried", "error", maxEmailAttempts - 1, true},
{"a failure at the cap is abandoned", "error", maxEmailAttempts, false},
{"a failure past the cap is abandoned", "error", maxEmailAttempts + 1, false},
{"a success is terminal even with attempts left", "created", 0, false},
{"a skip is terminal too", "skipped", 0, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
row := &models.ProcessedEmail{Action: c.action, Attempts: c.attempts}
if got := retryableFailure(row); got != c.want {
t.Fatalf("retryableFailure(%s, %d) = %v, want %v", c.action, c.attempts, got, c.want)
}
})
}
}
func TestMatchesFilter(t *testing.T) {
cases := []struct {
name string
subject string
sender string
want bool
}{
{"subject keyword anywhere in the line", "Your application to Acme", "[email protected]", true},
{"subject keyword is case-insensitive", "INTERVIEW CONFIRMED", "[email protected]", true},
{"sender on a tracked ATS domain", "hello", "[email protected]", true},
{"sender on a subdomain of a tracked domain", "hello", "[email protected]", true},
{"sender domain match is case-insensitive", "hello", "[email protected]", true},
// The rule is an @ or . boundary, so a lookalike domain that merely
// ends in the same letters must not match.
{"lookalike domain does not match", "hello", "[email protected]", false},
{"neither subject nor sender matches", "lunch tomorrow?", "[email protected]", false},
}
s := &EmailSyncService{}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
email := graphMessage{Subject: c.subject}
email.From.EmailAddress.Address = c.sender
if got := s.matchesFilter(email); got != c.want {
t.Fatalf("matchesFilter(%q, %q) = %v, want %v", c.subject, c.sender, got, c.want)
}
})
}
}
+808
View File
@@ -0,0 +1,808 @@
package services
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"strings"
"sync"
"time"
"unicode"
"adam-french.co.uk/job-tracker/internal/claude"
"adam-french.co.uk/job-tracker/internal/models"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// Job leads: the pipeline that finds postings, as opposed to tracking
// applications. On a timer it polls every enabled models.JobSource
// (job_sources.go), files what it has not seen before as a models.JobLead,
// marks which leads pass a keyword pre-filter, and asks Claude
// (internal/claude) to score those against the models.JobSearchProfile.
//
// Leads are a separate table from the tracker on purpose (see models.JobLead).
// The one way a lead reaches the tracker is promotion, a deliberate click on
// the leads page (graph/job_lead.resolvers.go), which goes through
// UpsertJobApplication so it cannot duplicate a posting already captured.
// Lead states, stored in JobLead.State.
const (
LeadNew = "new"
LeadDismissed = "dismissed"
LeadPromoted = "promoted"
)
const (
// maxScoresPerRun bounds the Claude calls one Run can make, and so both
// its cost and its length. A first poll of a few boards can match
// hundreds of leads; the rest are picked up by later runs, newest first,
// or all at once by ScoreAll. It is also ScoreAll's batch size.
maxScoresPerRun = 40
// maxScoreAttempts caps how many times a lead Claude failed to score is
// retried, for the same reason as maxEmailAttempts.
maxScoreAttempts = 3
// maxRunDuration bounds a whole run. Generous: forty scores at a worst
// case of two minutes each would exceed it, but a healthy call is a few
// seconds, and a run that is cut short loses nothing — unscored leads are
// simply still unscored next time.
maxRunDuration = 20 * time.Minute
// maxScoreAllDuration bounds ScoreAll, which has no cap on the count. An
// hour is several hundred leads at a few seconds each; whatever is left
// when it runs out is picked up by pressing the button again.
maxScoreAllDuration = time.Hour
// leadBatch sizes the IN lists and inserts, well inside Postgres's limit
// of 65535 bound parameters per statement.
leadBatch = 500
)
// ErrLeadSyncRunning is returned by Run when another run holds the lock.
var ErrLeadSyncRunning = errors.New("lead sync already in progress")
// JobLeadConfig configures the pipeline. The API keys are optional: a search
// source whose key is missing reports that as its own error and the rest of
// the run carries on.
type JobLeadConfig struct {
Enabled bool
Interval time.Duration
AdzunaAppID string
AdzunaAppKey string
ReedAPIKey string
}
// JobLeadService owns the lead pipeline.
type JobLeadService struct {
Config *JobLeadConfig
DB *gorm.DB
// Scorer makes the Claude call that scores one lead (normally a
// *claude.Client; the tests substitute a fake).
Scorer LeadScorer
// HTTPClient fetches the sources. Its timeout is per request, and has to
// allow for a multi-megabyte board arriving over the Pi's connection.
HTTPClient *http.Client
// mu is used with TryLock, as in EmailSyncService: a run requested while
// another is going is refused, not queued.
mu sync.Mutex
// statusMu guards the three fields below, which the leads page polls
// while a run it started is in flight.
statusMu sync.Mutex
running bool
lastRunAt *time.Time
lastError string
}
// LeadSyncStatus is what the leads page shows beside its "Check now" button.
type LeadSyncStatus struct {
Running bool
// LastRunAt is when the most recent run finished; nil until one has, in
// this process — it is not persisted, so a restart clears it.
LastRunAt *time.Time
// LastError is "" after a run in which nothing failed outright. One
// source failing is not here; it is on that JobSource.
LastError string
}
// InitJobLeads builds the service. It makes no network or database calls.
func InitJobLeads(config *JobLeadConfig, db *gorm.DB, scorer LeadScorer) *JobLeadService {
return &JobLeadService{
Config: config,
DB: db,
Scorer: scorer,
HTTPClient: &http.Client{Timeout: 60 * time.Second},
}
}
// Status reports whether a run is in flight and how the last one ended.
func (s *JobLeadService) Status() LeadSyncStatus {
s.statusMu.Lock()
defer s.statusMu.Unlock()
return LeadSyncStatus{Running: s.running, LastRunAt: s.lastRunAt, LastError: s.lastError}
}
// StartScheduler runs the pipeline on every tick until ctx is cancelled. It
// is meant to be run in its own goroutine and returns straight away when
// JOB_LEADS_ENABLED is not "true".
//
// Unlike the email scheduler it does not run at start-up: every deploy
// restarts the backend, and a deploy should not spend forty Claude calls. The
// first run is one interval in, or whenever "Check now" is pressed — which
// works whether or not the scheduler is enabled.
func (s *JobLeadService) StartScheduler(ctx context.Context) {
if !s.Config.Enabled {
log.Println("[JobLeads] Scheduler disabled; runs only on request")
return
}
log.Printf("[JobLeads] Starting scheduler, interval: %s", s.Config.Interval)
ticker := time.NewTicker(s.Config.Interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
log.Println("[JobLeads] Scheduler stopped")
return
case <-ticker.C:
if err := s.Run(ctx); err != nil {
log.Printf("[JobLeads] Run error: %v", err)
}
}
}
}
// LeadJob names one of the pipeline's three jobs, for RunInBackground.
type LeadJob int
const (
// LeadJobSync is Run: poll the sources, then score up to a cap.
LeadJobSync LeadJob = iota
// LeadJobScore is ScoreAll: score every unscored lead, polling nothing.
LeadJobScore
// LeadJobRescore is RescoreAll: score every inbox lead again.
LeadJobRescore
)
// RunInBackground starts a job and returns at once, reporting false when one
// was already going. It backs the page's buttons — "Check now", "Score
// unscored" and "Rescore all". Any of them can take minutes, far longer than
// a request should be held open, so the page polls Status instead of waiting.
func (s *JobLeadService) RunInBackground(job LeadJob) bool {
if s.Status().Running {
return false
}
run := s.Run
switch job {
case LeadJobScore:
run = s.ScoreAll
case LeadJobRescore:
run = s.RescoreAll
}
go func() {
// Not the request's context: the request is over long before this is.
if err := run(context.Background()); err != nil && !errors.Is(err, ErrLeadSyncRunning) {
log.Printf("[JobLeads] Manual run error: %v", err)
}
}()
return true
}
// Run is one pass of the pipeline: fetch, store, pre-filter, score.
func (s *JobLeadService) Run(ctx context.Context) error {
return s.exclusive(ctx, maxRunDuration, s.fetchAndScore)
}
// ScoreAll scores every matched lead that has no score yet, without polling
// any source. It exists because Run caps its scoring at maxScoresPerRun: after
// a first poll of several boards, or after the profile was filled in late,
// there is a backlog, and clearing it should not mean re-fetching every board
// (and spending search-API quota) forty leads at a time.
//
// The pre-filter is re-applied first, so keywords edited since the last run
// decide what gets scored. There is no cap on the count — the person pressed a
// button that says "all" — only maxScoreAllDuration on the time.
func (s *JobLeadService) ScoreAll(ctx context.Context) error {
return s.scoreAll(ctx, false)
}
// RescoreAll scores every matched lead in the inbox again, including the
// ones that already have a score. It is for when what a score means has
// changed: the profile was rewritten, or CLAUDE_MODEL was switched.
//
// Old scores are not wiped first. Each lead keeps the score it has until its
// new one arrives, so the inbox stays sorted and readable while the job runs,
// and a job that dies halfway (no API key, a restart) leaves every lead with
// a score, some new and some old, rather than half of them blank. What is
// left to do is told apart by ScoredAt: anything scored before this job
// started is still due. Pressing the button again after a failure therefore
// starts over rather than resuming, which costs calls but is never wrong.
//
// Leads that had used up their attempts get them back: a posting the old
// model could not score may be fine on the new one.
func (s *JobLeadService) RescoreAll(ctx context.Context) error {
return s.scoreAll(ctx, true)
}
func (s *JobLeadService) scoreAll(ctx context.Context, rescore bool) error {
return s.exclusive(ctx, maxScoreAllDuration, func(ctx context.Context) error {
profile, err := LoadJobSearchProfile(s.DB)
if err != nil {
return fmt.Errorf("loading the search profile: %w", err)
}
if strings.TrimSpace(profile.Profile) == "" {
return errors.New("the search profile is empty, so there is nothing to score against")
}
if err := s.refilter(newLeadFilter(profile)); err != nil {
return fmt.Errorf("re-applying the filter: %w", err)
}
var due *time.Time
if rescore {
started := time.Now()
due = &started
if err := s.DB.Model(&models.JobLead{}).
Where("state = ? AND matched = ? AND score_attempts > 0", LeadNew, true).
UpdateColumn("score_attempts", 0).Error; err != nil {
return fmt.Errorf("resetting score attempts: %w", err)
}
log.Println("[JobLeads] Rescoring every inbox lead")
} else {
log.Println("[JobLeads] Scoring all unscored leads")
}
total := 0
var failed []uint
for {
// Each pass takes the next batch. A lead that fails is skipped
// for the rest of this job, so one press spends one attempt on
// it, not all three — a passing Claude hiccup should not write a
// lead off for good. That is also why the loop terminates: every
// lead a pass looks at is either scored or added to `failed`.
scored, tried, nowFailed, err := s.scoreLeads(ctx, profile, failed, due)
total += scored
failed = append(failed, nowFailed...)
if err != nil || tried == 0 {
log.Printf("[JobLeads] Scoring finished: %d scored", total)
return err
}
}
})
}
// exclusive runs work as the one pipeline job in flight, maintaining the
// status the page polls. A second job requested meanwhile is refused.
func (s *JobLeadService) exclusive(ctx context.Context, limit time.Duration, work func(context.Context) error) (err error) {
if !s.mu.TryLock() {
return ErrLeadSyncRunning
}
defer s.mu.Unlock()
s.statusMu.Lock()
s.running = true
s.statusMu.Unlock()
// Runs before the unlock above. It also absorbs a panic, turning it into
// this job's error, so one malformed posting cannot take the backend down
// or leave `running` stuck true.
defer func() {
if r := recover(); r != nil {
log.Printf("[JobLeads] PANIC recovered: %v", r)
err = fmt.Errorf("internal error during the run")
}
now := time.Now()
s.statusMu.Lock()
s.running = false
s.lastRunAt = &now
s.lastError = ""
if err != nil {
s.lastError = err.Error()
}
s.statusMu.Unlock()
}()
ctx, cancel := context.WithTimeout(ctx, limit)
defer cancel()
return work(ctx)
}
// fetchAndScore is the body of Run.
func (s *JobLeadService) fetchAndScore(ctx context.Context) error {
profile, err := LoadJobSearchProfile(s.DB)
if err != nil {
return fmt.Errorf("loading the search profile: %w", err)
}
filter := newLeadFilter(profile)
var sources []models.JobSource
if err := s.DB.Where("enabled = ?", true).Order("id ASC").Find(&sources).Error; err != nil {
return fmt.Errorf("loading sources: %w", err)
}
tracked, err := s.trackedURLs()
if err != nil {
return fmt.Errorf("loading tracked applications: %w", err)
}
log.Printf("[JobLeads] Starting run over %d sources", len(sources))
added := 0
for _, src := range sources {
if ctx.Err() != nil {
return ctx.Err()
}
jobs, fetchErr := s.fetchSource(ctx, src)
var n int
if fetchErr == nil {
n, fetchErr = s.storeLeads(ctx, src, jobs, filter, tracked)
added += n
}
s.recordPoll(src, len(jobs), fetchErr)
}
if err := s.refilter(filter); err != nil {
return fmt.Errorf("re-applying the filter: %w", err)
}
scored, _, _, err := s.scoreLeads(ctx, profile, nil, nil)
log.Printf("[JobLeads] Run finished: %d new leads, %d scored", added, scored)
return err
}
// recordPoll writes a poll's outcome onto its source for the page to show.
// Updates rather than Save, so a source edited on the page mid-run is not
// overwritten with the copy this run loaded.
func (s *JobLeadService) recordPoll(src models.JobSource, count int, fetchErr error) {
now := time.Now()
updates := map[string]any{"last_fetched_at": &now, "last_error": ""}
if fetchErr != nil {
log.Printf("[JobLeads] %s %q failed: %v", src.Kind, src.Label, fetchErr)
updates["last_error"] = truncate(fetchErr.Error(), 300)
} else {
updates["last_count"] = count
}
if err := s.DB.Model(&models.JobSource{}).Where("id = ?", src.ID).Updates(updates).Error; err != nil {
log.Printf("[JobLeads] Recording the poll of source %d failed: %v", src.ID, err)
}
}
// trackedURLs maps the canonical URL of every live application that has one
// to its id, so a fetched posting that is already in the tracker can be told
// apart from a fresh lead.
func (s *JobLeadService) trackedURLs() (map[string]uint, error) {
var apps []models.JobApplication
if err := s.DB.Select("id", "url").Where("url IS NOT NULL AND url <> ''").Find(&apps).Error; err != nil {
return nil, err
}
tracked := make(map[string]uint, len(apps))
for _, app := range apps {
if canonical, ok := CanonicalJobURL(*app.URL); ok {
tracked[canonical] = app.ID
}
}
return tracked, nil
}
// storeLeads files the postings a source returned and reports how many were
// new. A posting seen before only has its LastSeenAt moved: its state, score
// and text are left exactly as they are, which is what keeps a dismissed
// lead dismissed.
func (s *JobLeadService) storeLeads(ctx context.Context, src models.JobSource, jobs []fetchedJob, filter leadFilter, tracked map[string]uint) (int, error) {
now := time.Now()
added := 0
for start := 0; start < len(jobs); start += leadBatch {
batch := jobs[start:min(start+leadBatch, len(jobs))]
ids := make([]string, len(batch))
for i, job := range batch {
ids[i] = job.ExternalID
}
var known []string
if err := s.DB.Model(&models.JobLead{}).
Where("source_kind = ? AND external_id IN ?", src.Kind, ids).
Pluck("external_id", &known).Error; err != nil {
return added, fmt.Errorf("looking up existing leads: %w", err)
}
if len(known) > 0 {
if err := s.DB.Model(&models.JobLead{}).
Where("source_kind = ? AND external_id IN ?", src.Kind, known).
UpdateColumn("last_seen_at", now).Error; err != nil {
return added, fmt.Errorf("updating existing leads: %w", err)
}
}
seen := make(map[string]bool, len(known))
for _, id := range known {
seen[id] = true
}
var fresh []models.JobLead
for _, job := range batch {
// `seen` also catches a posting listed twice in one response.
if seen[job.ExternalID] {
continue
}
seen[job.ExternalID] = true
lead, ok := newLead(src, job, filter, tracked, now)
if !ok {
continue
}
// The full text costs a request per job, so it is fetched only
// for a lead that will be shown and scored. A failure leaves the
// snippet in place rather than losing the lead.
if job.detailID != "" && lead.Matched && lead.State == LeadNew {
if full, err := s.fetchReedDescription(ctx, job.detailID); err == nil && full != "" {
lead.Description = truncateRunes(full, maxLeadRunes)
}
}
fresh = append(fresh, lead)
}
if len(fresh) == 0 {
continue
}
// DoNothing covers the one way a row can appear between the lookup
// above and this insert: a second search source of the same kind
// returning the same advert. Runs themselves never overlap.
result := s.DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&fresh)
if result.Error != nil {
return added, fmt.Errorf("saving new leads: %w", result.Error)
}
added += int(result.RowsAffected)
}
return added, nil
}
// newLead turns a fetched posting into the row to insert. ok is false for a
// posting with no id, title or company, which could be neither deduplicated
// nor promoted.
//
// A posting whose URL is already in the tracker is filed as promoted and
// linked to that application: it still has to be a row, or the next poll
// would consider it again, but it must not be offered in the inbox.
func newLead(src models.JobSource, job fetchedJob, filter leadFilter, tracked map[string]uint, now time.Time) (models.JobLead, bool) {
title := strings.TrimSpace(job.Title)
company := strings.TrimSpace(job.Company)
if job.ExternalID == "" || title == "" || company == "" {
return models.JobLead{}, false
}
lead := models.JobLead{
SourceID: src.ID,
SourceKind: src.Kind,
ExternalID: job.ExternalID,
JobTitle: title,
Company: company,
Location: strings.TrimSpace(job.Location),
URL: strings.TrimSpace(job.URL),
Description: truncateRunes(job.Description, maxLeadRunes),
PostedAt: job.PostedAt,
LastSeenAt: now,
State: LeadNew,
}
lead.Matched = filter.matches(lead.JobTitle, lead.Location)
if canonical, ok := CanonicalJobURL(lead.URL); ok {
lead.URL = canonical
if appID, found := tracked[canonical]; found {
lead.State = LeadPromoted
lead.JobAppID = &appID
}
}
return lead, true
}
// refilter brings Matched up to date for every lead still in the inbox, so
// that editing the keywords on the page takes effect on the next run instead
// of only for postings found afterwards.
func (s *JobLeadService) refilter(filter leadFilter) error {
var leads []models.JobLead
if err := s.DB.Select("id", "job_title", "location", "matched").
Where("state = ?", LeadNew).Find(&leads).Error; err != nil {
return err
}
var toMatch, toUnmatch []uint
for _, lead := range leads {
switch matched := filter.matches(lead.JobTitle, lead.Location); {
case matched && !lead.Matched:
toMatch = append(toMatch, lead.ID)
case !matched && lead.Matched:
toUnmatch = append(toUnmatch, lead.ID)
}
}
for value, ids := range map[bool][]uint{true: toMatch, false: toUnmatch} {
for start := 0; start < len(ids); start += leadBatch {
if err := s.DB.Model(&models.JobLead{}).
Where("id IN ?", ids[start:min(start+leadBatch, len(ids))]).
UpdateColumn("matched", value).Error; err != nil {
return err
}
}
}
return nil
}
// PromoteJobLead adds a lead to the tracker as a saved application and marks
// it promoted. It goes through UpsertJobApplication, so a posting that was
// captured from the browser in the meantime is linked to, not duplicated —
// the lead's text and score fill any fields that row was missing.
//
// Promoting twice is harmless: the second call finds the lead already
// promoted and returns it.
func PromoteJobLead(db *gorm.DB, id uint, now time.Time) (*models.JobLead, error) {
var lead models.JobLead
if err := db.First(&lead, id).Error; err != nil {
return nil, err
}
if lead.State == LeadPromoted && lead.JobAppID != nil {
return &lead, nil
}
app, _, err := UpsertJobApplication(db, JobCaptureInput{
JobTitle: lead.JobTitle,
Company: lead.Company,
Location: lead.Location,
URL: lead.URL,
Status: "saved",
Notes: leadNotes(&lead),
Description: lead.Description,
}, now)
if err != nil {
return nil, err
}
lead.State = LeadPromoted
lead.JobAppID = &app.ID
if err := db.Model(&lead).Updates(map[string]any{"state": lead.State, "job_app_id": lead.JobAppID}).Error; err != nil {
return nil, fmt.Errorf("marking the lead promoted: %w", err)
}
return &lead, nil
}
// leadNotes is the line a promoted lead leaves in the application's notes, so
// why it looked worth applying to is still there once the lead is forgotten.
func leadNotes(lead *models.JobLead) string {
if lead.Score == nil {
return ""
}
note := fmt.Sprintf("Lead score %d/100", *lead.Score)
if lead.ScoreReasons != nil && strings.TrimSpace(*lead.ScoreReasons) != "" {
note += ": " + strings.TrimSpace(*lead.ScoreReasons)
}
return note
}
// ValidateJobSource tidies a source's fields and reports the first thing
// wrong with it, in words for the page. Which fields are required depends on
// the kind; the ones a kind does not use are cleared so a source switched
// from one kind to another does not carry the old kind's settings around.
func ValidateJobSource(src *models.JobSource) error {
src.Kind = strings.ToLower(strings.TrimSpace(src.Kind))
src.Label = strings.TrimSpace(src.Label)
src.Token = strings.TrimSpace(src.Token)
src.Query = strings.TrimSpace(src.Query)
src.Location = strings.TrimSpace(src.Location)
switch {
case IsBoardSource(src.Kind):
// The token goes into a URL path. Board slugs are letters, digits
// and a little punctuation; anything else is a pasted URL or a typo.
if src.Token == "" || strings.ContainsAny(src.Token, "/?#& ") {
return fmt.Errorf("token must be the board's slug, e.g. the \"acme\" in boards.greenhouse.io/acme")
}
if src.Label == "" {
return fmt.Errorf("label is required: it is the company name its leads are filed under")
}
src.Query, src.Location = "", ""
case IsSearchSource(src.Kind):
if src.Query == "" {
return fmt.Errorf("query is required for a search source")
}
if src.Label == "" {
src.Label = src.Query
}
src.Token = ""
default:
return fmt.Errorf("kind must be one of greenhouse, lever, ashby, adzuna, reed")
}
return nil
}
// Pre-filter
// leadFilter is the keyword test a lead must pass before it is shown or
// costs a Claude call. It is intentionally crude and cheap: its job is to
// throw out the obviously irrelevant ninety percent of a company board
// (sales, legal, other countries), not to judge fit — that is the score.
type leadFilter struct {
include []string
exclude []string
locations []string
}
func newLeadFilter(profile *models.JobSearchProfile) leadFilter {
return leadFilter{
include: splitKeywords(profile.IncludeKeywords),
exclude: splitKeywords(profile.ExcludeKeywords),
locations: splitKeywords(profile.Locations),
}
}
// splitKeywords reads a keyword list as the page stores it: one entry per
// line, commas also accepted, case and surrounding space ignored.
func splitKeywords(list string) []string {
var out []string
for _, entry := range strings.FieldsFunc(list, func(r rune) bool { return r == '\n' || r == ',' }) {
if entry = strings.ToLower(strings.TrimSpace(entry)); entry != "" {
out = append(out, entry)
}
}
return out
}
// matches reports whether a posting passes. An empty list is no constraint,
// so with nothing configured every lead matches.
//
// - the title must contain one of the include keywords, and none of the
// exclude keywords, as whole words (see containsWord);
// - the location must contain one of the wanted locations as a plain
// substring ("london" finds "Cardiff, London or Remote (UK)"). A posting
// that states no location passes: unknown is not the same as wrong.
func (f leadFilter) matches(title, location string) bool {
title = strings.ToLower(title)
if len(f.include) > 0 && !containsAnyWord(title, f.include) {
return false
}
if containsAnyWord(title, f.exclude) {
return false
}
location = strings.ToLower(strings.TrimSpace(location))
if len(f.locations) == 0 || location == "" {
return true
}
for _, wanted := range f.locations {
if strings.Contains(location, wanted) {
return true
}
}
return false
}
func containsAnyWord(text string, words []string) bool {
for _, word := range words {
if containsWord(text, word) {
return true
}
}
return false
}
// containsWord reports whether word occurs in text on word boundaries, with
// an optional plural "s". Boundaries are what let "intern" be excluded
// without also excluding "Internal Tools Engineer", and the plural is what
// lets "engineer" find "Engineers". Both arguments are already lowercase.
func containsWord(text, word string) bool {
isWordRune := func(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) }
for from := 0; ; {
i := strings.Index(text[from:], word)
if i < 0 {
return false
}
start := from + i
end := start + len(word)
before := []rune(text[:start])
after := []rune(strings.TrimPrefix(text[end:], "s"))
if (len(before) == 0 || !isWordRune(before[len(before)-1])) &&
(len(after) == 0 || !isWordRune(after[0])) {
return true
}
from = start + 1
}
}
// Scoring
// LeadScore is Claude's verdict on one lead.
type LeadScore = claude.LeadScore
// LeadScorer is the one Claude call the pipeline makes. Its errors are
// claude's three kinds: a *claude.ReadError is about this lead, anything else
// is not (see scoreLeads).
type LeadScorer interface {
ScorePosting(ctx context.Context, profile, jobTitle, company, location, description string) (LeadScore, error)
}
// scoreLeads asks Claude to score the matched leads that have no score yet,
// newest first, up to maxScoresPerRun, leaving out the ids in skip. It reports
// how many it scored, how many it tried, and which ones Claude failed on;
// tried is zero once nothing is left to score, which is what ScoreAll loops
// on.
//
// rescoreBefore, when set, widens "has no score yet" to "has no score from
// this job": a lead whose score is older than that time is due again. Its old
// score stays in place until the new one is saved, and through a failure.
//
// With no profile text there is nothing to score against, so it does nothing
// — leads still arrive and can be read, they just carry no score.
func (s *JobLeadService) scoreLeads(ctx context.Context, profile *models.JobSearchProfile, skip []uint, rescoreBefore *time.Time) (scored, tried int, failed []uint, err error) {
if strings.TrimSpace(profile.Profile) == "" {
return 0, 0, nil, nil
}
query := s.DB.Where("state = ? AND matched = ? AND score_attempts < ?", LeadNew, true, maxScoreAttempts)
if rescoreBefore == nil {
query = query.Where("score IS NULL")
} else {
query = query.Where("(score IS NULL OR scored_at IS NULL OR scored_at < ?)", *rescoreBefore)
}
if len(skip) > 0 {
query = query.Where("id NOT IN ?", skip)
}
var leads []models.JobLead
if err := query.Order("created_at DESC, id DESC").Limit(maxScoresPerRun).Find(&leads).Error; err != nil {
return 0, 0, nil, fmt.Errorf("loading leads to score: %w", err)
}
for i := range leads {
lead := &leads[i]
result, err := s.scoreLead(ctx, profile.Profile, lead)
tried++
var readErr *claude.ReadError
switch {
case err == nil:
reasons := strings.TrimSpace(result.Reasons)
score := min(max(result.Score, 0), 100)
if dbErr := s.DB.Model(lead).Updates(map[string]any{"score": score, "score_reasons": reasons, "scored_at": time.Now()}).Error; dbErr != nil {
return scored, tried, failed, fmt.Errorf("saving a score: %w", dbErr)
}
scored++
case errors.As(err, &readErr):
// Claude answered badly for this posting. Count the attempt and
// move on; maxScoreAttempts stops it being retried forever.
log.Printf("[JobLeads] Scoring lead %d failed: %v", lead.ID, err)
if dbErr := s.DB.Model(lead).UpdateColumn("score_attempts", gorm.Expr("score_attempts + 1")).Error; dbErr != nil {
return scored, tried, failed, fmt.Errorf("recording a failed score: %w", dbErr)
}
failed = append(failed, lead.ID)
case ctx.Err() != nil:
// Out of time (or shut down) mid-call. Nothing is wrong with
// scoring, so say what happened rather than "unavailable".
return scored, tried, failed, errors.New("ran out of time before every lead was scored; run it again to continue")
default:
// Anything else is not about this lead: in practice, no API key.
// The next lead would fail the same way, so stop, and spend no
// attempt on it. The detail goes to the log; the returned error
// is shown on the leads page.
log.Printf("[JobLeads] Scoring stopped at lead %d: %v", lead.ID, err)
return scored, tried, failed, errors.New("scoring is unavailable: no Claude key is set (see the tracker's log)")
}
}
return scored, tried, failed, nil
}
func (s *JobLeadService) scoreLead(ctx context.Context, profile string, lead *models.JobLead) (LeadScore, error) {
return s.Scorer.ScorePosting(ctx, truncateRunes(profile, maxProfileRunes),
lead.JobTitle, lead.Company, lead.Location, lead.Description)
}
// Search profile
// maxProfileRunes caps the profile text, both as stored and as sent.
const maxProfileRunes = 12_000
// jobSearchProfileID is the one row's id; see models.JobSearchProfile.
const jobSearchProfileID = 1
// LoadJobSearchProfile returns the single profile row, creating it empty the
// first time it is asked for.
func LoadJobSearchProfile(db *gorm.DB) (*models.JobSearchProfile, error) {
profile := models.JobSearchProfile{ID: jobSearchProfileID}
if err := db.FirstOrCreate(&profile, models.JobSearchProfile{ID: jobSearchProfileID}).Error; err != nil {
return nil, err
}
return &profile, nil
}
// SaveJobSearchProfile stores an edited profile, bounding the free text.
func SaveJobSearchProfile(db *gorm.DB, profile *models.JobSearchProfile) error {
profile.ID = jobSearchProfileID
profile.Profile = truncateRunes(strings.TrimSpace(profile.Profile), maxProfileRunes)
profile.MinScore = min(max(profile.MinScore, 0), 100)
return db.Save(profile).Error
}
+221
View File
@@ -0,0 +1,221 @@
package services
import (
"context"
"slices"
"strings"
"testing"
"time"
"unicode/utf8"
"adam-french.co.uk/job-tracker/internal/models"
)
// The parts of the lead pipeline that need no database: the pre-filter, how a
// fetched posting becomes a row, source validation, the note a promoted lead
// leaves, and the scoring call. Storing, re-filtering and the scoring loop's
// bookkeeping all run queries and are exercised in the dev stack instead.
func TestLeadFilter(t *testing.T) {
filter := newLeadFilter(&models.JobSearchProfile{
IncludeKeywords: "Engineer\ndeveloper, SRE",
ExcludeKeywords: "intern\nsenior staff\nsales",
Locations: "London\nremote",
})
cases := []struct {
title, location string
want bool
}{
{"Backend Engineer", "London, UK", true},
{"Software Engineers (Platform)", "Remote - EMEA", true},
{"SRE", "Cardiff, London or Remote (UK)", true},
{"Engineering Manager", "London", false}, // "engineer" is not a whole word here
{"Account Executive", "London", false},
{"Engineer Intern", "London", false},
{"Internal Tools Engineer", "London", true}, // "intern" must not catch "Internal"
{"Senior Staff Engineer", "London", false},
{"Sales Engineer", "London", false},
{"Backend Engineer", "New York, NY", false},
{"Backend Engineer", "", true}, // unknown location passes
}
for _, c := range cases {
if got := filter.matches(c.title, c.location); got != c.want {
t.Errorf("matches(%q, %q) = %v, want %v", c.title, c.location, got, c.want)
}
}
// Nothing configured: everything passes.
if !newLeadFilter(&models.JobSearchProfile{}).matches("Chief Vibes Officer", "Mars") {
t.Error("an empty filter should match everything")
}
}
func TestContainsWord(t *testing.T) {
cases := []struct {
text, word string
want bool
}{
{"go developer", "go", true},
{"golang developer", "go", false},
{"c++ engineer", "c++", true},
{"developers wanted", "developer", true},
{"developerss", "developer", false},
{"site reliability engineer (sre)", "sre", true},
{"ingénieur logiciel", "nieur", false},
{"", "go", false},
}
for _, c := range cases {
if got := containsWord(c.text, c.word); got != c.want {
t.Errorf("containsWord(%q, %q) = %v, want %v", c.text, c.word, got, c.want)
}
}
}
func TestNewLead(t *testing.T) {
now := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
src := models.JobSource{ID: 7, Kind: SourceGreenhouse, Label: "Acme", Token: "acme"}
filter := newLeadFilter(&models.JobSearchProfile{IncludeKeywords: "engineer"})
tracked := map[string]uint{"https://boards.greenhouse.io/acme/jobs/2": 42}
t.Run("a fresh posting is a new, matched lead", func(t *testing.T) {
lead, ok := newLead(src, fetchedJob{
ExternalID: "acme/1", Title: " Backend Engineer ", Company: "Acme", Location: "London",
URL: "https://boards.greenhouse.io/acme/jobs/1/?gh_src=abc", Description: "Text",
}, filter, tracked, now)
if !ok {
t.Fatal("not ok")
}
if lead.State != LeadNew || !lead.Matched || lead.JobAppID != nil || lead.SourceID != 7 ||
lead.SourceKind != SourceGreenhouse || lead.JobTitle != "Backend Engineer" || !lead.LastSeenAt.Equal(now) {
t.Errorf("lead = %+v", lead)
}
// Stored canonical, so it is the same key the tracker would hold.
if lead.URL != "https://boards.greenhouse.io/acme/jobs/1" {
t.Errorf("url = %q", lead.URL)
}
})
t.Run("a posting already in the tracker is filed as promoted", func(t *testing.T) {
lead, ok := newLead(src, fetchedJob{
ExternalID: "acme/2", Title: "Backend Engineer", Company: "Acme",
URL: "https://boards.greenhouse.io/acme/jobs/2?utm_source=x",
}, filter, tracked, now)
if !ok || lead.State != LeadPromoted || lead.JobAppID == nil || *lead.JobAppID != 42 {
t.Errorf("lead = %+v, ok = %v", lead, ok)
}
})
t.Run("a posting that fails the filter is kept, unmatched", func(t *testing.T) {
lead, ok := newLead(src, fetchedJob{ExternalID: "acme/3", Title: "Account Executive", Company: "Acme"}, filter, tracked, now)
if !ok || lead.Matched || lead.State != LeadNew {
t.Errorf("lead = %+v, ok = %v", lead, ok)
}
})
t.Run("a posting with no id, title or company is dropped", func(t *testing.T) {
for _, job := range []fetchedJob{
{Title: "Engineer", Company: "Acme"},
{ExternalID: "acme/4", Company: "Acme"},
{ExternalID: "acme/5", Title: "Engineer", Company: " "},
} {
if _, ok := newLead(src, job, filter, tracked, now); ok {
t.Errorf("%+v should be dropped", job)
}
}
})
t.Run("a long description is cut on a rune boundary", func(t *testing.T) {
lead, _ := newLead(src, fetchedJob{
ExternalID: "acme/6", Title: "Engineer", Company: "Acme", Description: strings.Repeat("é", maxLeadRunes+10),
}, filter, tracked, now)
if got := len([]rune(lead.Description)); got != maxLeadRunes {
t.Errorf("description is %d runes", got)
}
})
}
func TestValidateJobSource(t *testing.T) {
ok := []struct {
in models.JobSource
want models.JobSource
}{
// Fields the kind does not use are cleared.
{models.JobSource{Kind: " Greenhouse ", Label: " Acme ", Token: " acme ", Query: "stale"},
models.JobSource{Kind: "greenhouse", Label: "Acme", Token: "acme"}},
// A search's label defaults to its query.
{models.JobSource{Kind: "reed", Query: "golang", Location: "London", Token: "stale"},
models.JobSource{Kind: "reed", Label: "golang", Query: "golang", Location: "London"}},
}
for _, c := range ok {
src := c.in
if err := ValidateJobSource(&src); err != nil || src != c.want {
t.Errorf("ValidateJobSource(%+v) = %+v, %v; want %+v", c.in, src, err, c.want)
}
}
bad := []models.JobSource{
{Kind: "monster", Label: "x", Query: "go"},
{Kind: "lever", Label: "Acme"},
{Kind: "lever", Label: "Acme", Token: "https://jobs.lever.co/acme"},
{Kind: "ashby", Token: "acme"},
{Kind: "adzuna", Label: "x"},
}
for _, src := range bad {
if err := ValidateJobSource(&src); err == nil {
t.Errorf("ValidateJobSource(%+v) should fail", src)
}
}
}
func TestLeadNotes(t *testing.T) {
score := 82
reasons := " Strong Go match; hybrid London. "
if got := leadNotes(&models.JobLead{}); got != "" {
t.Errorf("unscored lead notes = %q", got)
}
if got := leadNotes(&models.JobLead{Score: &score}); got != "Lead score 82/100" {
t.Errorf("notes = %q", got)
}
if got := leadNotes(&models.JobLead{Score: &score, ScoreReasons: &reasons}); got != "Lead score 82/100: Strong Go match; hybrid London." {
t.Errorf("notes = %q", got)
}
}
// fakeScorer records what it was asked to score and answers with reply/err.
type fakeScorer struct {
reply LeadScore
err error
got []string
}
func (f *fakeScorer) ScorePosting(_ context.Context, profile, jobTitle, company, location, description string) (LeadScore, error) {
f.got = []string{profile, jobTitle, company, location, description}
return f.reply, f.err
}
func TestScoreLeadPassesTheLead(t *testing.T) {
f := &fakeScorer{reply: LeadScore{Score: 82, Reasons: "Strong match"}}
s := &JobLeadService{Scorer: f}
lead := &models.JobLead{JobTitle: "Engineer", Company: "Acme", Location: "London", Description: "Text"}
got, err := s.scoreLead(context.Background(), "Five years of Go", lead)
if err != nil || got.Score != 82 || got.Reasons != "Strong match" {
t.Fatalf("scoreLead = %+v, %v", got, err)
}
if want := []string{"Five years of Go", "Engineer", "Acme", "London", "Text"}; !slices.Equal(f.got, want) {
t.Errorf("scored %q, want %q", f.got, want)
}
// The profile is cut to maxProfileRunes on the way out.
s.scoreLead(context.Background(), strings.Repeat("é", maxProfileRunes+5), lead)
if n := utf8.RuneCountInString(f.got[0]); n != maxProfileRunes {
t.Errorf("profile sent as %d runes, want %d", n, maxProfileRunes)
}
}
func TestLeadSyncStatusStartsIdle(t *testing.T) {
s := InitJobLeads(&JobLeadConfig{}, nil, &fakeScorer{})
if status := s.Status(); status.Running || status.LastRunAt != nil || status.LastError != "" {
t.Errorf("status = %+v", status)
}
}
+502
View File
@@ -0,0 +1,502 @@
package services
import (
"context"
"encoding/json"
"fmt"
"html"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"adam-french.co.uk/job-tracker/internal/models"
)
// The job sources the lead fetcher (job_leads.go) polls: one function per
// models.JobSource.Kind, each turning that source's JSON into the common
// fetchedJob. Nothing here touches the database.
//
// The three board kinds are public, keyless endpoints that return a whole
// company board, description included, in one response. Their shapes were
// checked against live boards. The two search kinds need API keys and their
// shapes are taken from the providers' documentation — if one of them starts
// reporting zero results or a decode error, its struct here is the first
// thing to compare against a real response.
// Source kinds. The strings are stored in JobSource.Kind and JobLead.SourceKind
// and repeated in the leads page's kind picker (web/src/views/JobSources.vue).
const (
SourceGreenhouse = "greenhouse"
SourceLever = "lever"
SourceAshby = "ashby"
SourceAdzuna = "adzuna"
SourceReed = "reed"
)
// IsBoardSource reports whether kind is one company's board, identified by a
// token, rather than a keyword search.
func IsBoardSource(kind string) bool {
return kind == SourceGreenhouse || kind == SourceLever || kind == SourceAshby
}
// IsSearchSource reports whether kind is a keyword search.
func IsSearchSource(kind string) bool {
return kind == SourceAdzuna || kind == SourceReed
}
// Base URLs, variables so the tests can point each at a stub server.
var (
greenhouseBase = "https://boards-api.greenhouse.io"
leverBase = "https://api.lever.co"
ashbyBase = "https://api.ashbyhq.com"
adzunaBase = "https://api.adzuna.com"
reedBase = "https://www.reed.co.uk"
)
const (
// maxSourceBody bounds one response. A large board with every description
// inline runs to several megabytes (Palantir's Lever board is about six);
// this is far above that and only there so a misbehaving endpoint cannot
// fill the Pi's memory.
maxSourceBody = 64 << 20
// searchPages × searchPageSize is how deep a keyword search is read on
// each poll. Results are newest first and polls are hours apart, so the
// first hundred is where anything new will be.
searchPages = 2
searchPageSize = 50
// adzunaMaxDaysOld keeps a search to recent adverts; older ones were seen
// by an earlier poll or are not worth surfacing now.
adzunaMaxDaysOld = 14
// maxLeadRunes caps a stored description, which is also what bounds the
// posting sent to Claude for scoring.
maxLeadRunes = 40_000
)
// fetchedJob is one posting as a source reported it, before it becomes a
// models.JobLead.
type fetchedJob struct {
// ExternalID is unique within the source kind; see models.JobLead.
ExternalID string
Title string
Company string
Location string
URL string
Description string
PostedAt *time.Time
// detailID is set when Description is only a snippet and the full text is
// one more request away (Reed). The fetcher makes that request only for
// a new lead that passed the pre-filter.
detailID string
}
// fetchSource returns everything src currently lists.
func (s *JobLeadService) fetchSource(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
switch src.Kind {
case SourceGreenhouse:
return s.fetchGreenhouse(ctx, src)
case SourceLever:
return s.fetchLever(ctx, src)
case SourceAshby:
return s.fetchAshby(ctx, src)
case SourceAdzuna:
return s.fetchAdzuna(ctx, src)
case SourceReed:
return s.fetchReed(ctx, src)
}
return nil, fmt.Errorf("unknown source kind %q", src.Kind)
}
// getJSON GETs target and decodes a 200 reply into out. basicUser, when set,
// is sent as the username of HTTP basic auth with an empty password, which is
// how Reed takes its API key.
//
// The error never includes the URL: Adzuna's carries the API key in its query
// string, and this error is stored in JobSource.LastError and shown on the
// page.
func (s *JobLeadService) getJSON(ctx context.Context, target, basicUser string, out any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil)
if err != nil {
return fmt.Errorf("building request")
}
req.Header.Set("Accept", "application/json")
if basicUser != "" {
req.SetBasicAuth(basicUser, "")
}
resp, err := s.HTTPClient.Do(req)
if err != nil {
// A *url.Error's message quotes the full URL; keep only its cause.
if urlErr, ok := err.(*url.Error); ok {
err = urlErr.Err
}
return fmt.Errorf("request failed: %v", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusNotFound:
return fmt.Errorf("not found (404): check the board token")
case resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden:
return fmt.Errorf("refused (%d): check the API key", resp.StatusCode)
case resp.StatusCode != http.StatusOK:
return fmt.Errorf("source returned %d", resp.StatusCode)
}
if err := json.NewDecoder(io.LimitReader(resp.Body, maxSourceBody)).Decode(out); err != nil {
return fmt.Errorf("unexpected response: %v", err)
}
return nil
}
// Greenhouse
type greenhouseBoard struct {
Jobs []struct {
ID int64 `json:"id"`
Title string `json:"title"`
AbsoluteURL string `json:"absolute_url"`
// Content is HTML that has itself been entity-escaped ("&lt;p&gt;").
Content string `json:"content"`
FirstPublished string `json:"first_published"`
UpdatedAt string `json:"updated_at"`
Location struct {
Name string `json:"name"`
} `json:"location"`
} `json:"jobs"`
}
func (s *JobLeadService) fetchGreenhouse(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
var board greenhouseBoard
target := fmt.Sprintf("%s/v1/boards/%s/jobs?content=true", greenhouseBase, url.PathEscape(src.Token))
if err := s.getJSON(ctx, target, "", &board); err != nil {
return nil, err
}
jobs := make([]fetchedJob, 0, len(board.Jobs))
for _, j := range board.Jobs {
posted := j.FirstPublished
if posted == "" {
posted = j.UpdatedAt
}
jobs = append(jobs, fetchedJob{
ExternalID: boardExternalID(src.Token, strconv.FormatInt(j.ID, 10)),
Title: j.Title,
Company: src.Label,
Location: j.Location.Name,
URL: j.AbsoluteURL,
// Unescape once to get the HTML back; htmlToText handles the rest.
Description: htmlToText(html.UnescapeString(j.Content)),
PostedAt: parseTime(time.RFC3339, posted),
})
}
return jobs, nil
}
// Lever
type leverPosting struct {
ID string `json:"id"`
Text string `json:"text"`
HostedURL string `json:"hostedUrl"`
CreatedAt int64 `json:"createdAt"` // Unix milliseconds
Categories struct {
Location string `json:"location"`
} `json:"categories"`
WorkplaceType string `json:"workplaceType"`
DescriptionPlain string `json:"descriptionPlain"`
AdditionalPlain string `json:"additionalPlain"`
// Lists are the posting's headed bullet sections ("What you'll do"),
// which descriptionPlain does not include.
Lists []struct {
Text string `json:"text"`
Content string `json:"content"` // HTML <li> items
} `json:"lists"`
}
func (s *JobLeadService) fetchLever(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
var postings []leverPosting
target := fmt.Sprintf("%s/v0/postings/%s?mode=json", leverBase, url.PathEscape(src.Token))
if err := s.getJSON(ctx, target, "", &postings); err != nil {
return nil, err
}
jobs := make([]fetchedJob, 0, len(postings))
for _, p := range postings {
parts := []string{strings.TrimSpace(p.DescriptionPlain)}
for _, list := range p.Lists {
parts = append(parts, strings.TrimSpace(list.Text)+"\n"+htmlToText(list.Content))
}
parts = append(parts, strings.TrimSpace(p.AdditionalPlain))
var posted *time.Time
if p.CreatedAt > 0 {
t := time.UnixMilli(p.CreatedAt).UTC()
posted = &t
}
jobs = append(jobs, fetchedJob{
ExternalID: boardExternalID(src.Token, p.ID),
Title: p.Text,
Company: src.Label,
Location: withWorkplace(p.Categories.Location, p.WorkplaceType),
URL: p.HostedURL,
Description: joinNonEmpty(parts, "\n\n"),
PostedAt: posted,
})
}
return jobs, nil
}
// Ashby
type ashbyBoard struct {
Jobs []struct {
ID string `json:"id"`
Title string `json:"title"`
Location string `json:"location"`
WorkplaceType string `json:"workplaceType"`
PublishedAt string `json:"publishedAt"`
IsListed bool `json:"isListed"`
JobURL string `json:"jobUrl"`
DescriptionPlain string `json:"descriptionPlain"`
} `json:"jobs"`
}
func (s *JobLeadService) fetchAshby(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
var board ashbyBoard
target := fmt.Sprintf("%s/posting-api/job-board/%s", ashbyBase, url.PathEscape(src.Token))
if err := s.getJSON(ctx, target, "", &board); err != nil {
return nil, err
}
jobs := make([]fetchedJob, 0, len(board.Jobs))
for _, j := range board.Jobs {
// Unlisted postings are reachable by direct link only; the company
// has chosen not to advertise them.
if !j.IsListed {
continue
}
jobs = append(jobs, fetchedJob{
ExternalID: boardExternalID(src.Token, j.ID),
Title: strings.TrimSpace(j.Title),
Company: src.Label,
Location: withWorkplace(j.Location, j.WorkplaceType),
URL: j.JobURL,
Description: strings.TrimSpace(j.DescriptionPlain),
PostedAt: parseTime(time.RFC3339, j.PublishedAt),
})
}
return jobs, nil
}
// Adzuna
type adzunaResults struct {
Results []struct {
// A string in the API, though it is all digits.
ID json.Number `json:"id"`
Title string `json:"title"`
Description string `json:"description"` // a snippet, about 500 characters
RedirectURL string `json:"redirect_url"`
Created string `json:"created"`
Company struct {
DisplayName string `json:"display_name"`
} `json:"company"`
Location struct {
DisplayName string `json:"display_name"`
} `json:"location"`
} `json:"results"`
}
// fetchAdzuna runs one UK keyword search. Adzuna only ever returns a snippet
// of the description and has no endpoint for the rest, so these leads are
// scored on less text than the others.
func (s *JobLeadService) fetchAdzuna(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
if s.Config.AdzunaAppID == "" || s.Config.AdzunaAppKey == "" {
return nil, fmt.Errorf("ADZUNA_APP_ID and ADZUNA_APP_KEY are not set")
}
var jobs []fetchedJob
for page := 1; page <= searchPages; page++ {
query := url.Values{
"app_id": {s.Config.AdzunaAppID},
"app_key": {s.Config.AdzunaAppKey},
"what": {src.Query},
"results_per_page": {strconv.Itoa(searchPageSize)},
"max_days_old": {strconv.Itoa(adzunaMaxDaysOld)},
"sort_by": {"date"},
}
if src.Location != "" {
query.Set("where", src.Location)
}
var results adzunaResults
target := fmt.Sprintf("%s/v1/api/jobs/gb/search/%d?%s", adzunaBase, page, query.Encode())
if err := s.getJSON(ctx, target, "", &results); err != nil {
return nil, err
}
for _, r := range results.Results {
jobs = append(jobs, fetchedJob{
ExternalID: r.ID.String(),
// Adzuna wraps the matched search terms in <strong>.
Title: htmlToText(r.Title),
Company: r.Company.DisplayName,
Location: r.Location.DisplayName,
URL: r.RedirectURL,
Description: htmlToText(r.Description),
PostedAt: parseTime(time.RFC3339, r.Created),
})
}
if len(results.Results) < searchPageSize {
break
}
}
return jobs, nil
}
// Reed
type reedResults struct {
Results []struct {
JobID int64 `json:"jobId"`
EmployerName string `json:"employerName"`
JobTitle string `json:"jobTitle"`
LocationName string `json:"locationName"`
Date string `json:"date"` // dd/mm/yyyy
JobDescription string `json:"jobDescription"`
JobURL string `json:"jobUrl"`
} `json:"results"`
}
type reedDetail struct {
JobDescription string `json:"jobDescription"` // HTML
}
// fetchReed runs one keyword search. The search returns a snippet of each
// description; the full text is fetchReedDescription, one request per job.
func (s *JobLeadService) fetchReed(ctx context.Context, src models.JobSource) ([]fetchedJob, error) {
if s.Config.ReedAPIKey == "" {
return nil, fmt.Errorf("REED_API_KEY is not set")
}
var jobs []fetchedJob
for page := 0; page < searchPages; page++ {
query := url.Values{
"keywords": {src.Query},
"resultsToTake": {strconv.Itoa(searchPageSize)},
"resultsToSkip": {strconv.Itoa(page * searchPageSize)},
}
if src.Location != "" {
query.Set("locationName", src.Location)
}
var results reedResults
target := fmt.Sprintf("%s/api/1.0/search?%s", reedBase, query.Encode())
if err := s.getJSON(ctx, target, s.Config.ReedAPIKey, &results); err != nil {
return nil, err
}
for _, r := range results.Results {
id := strconv.FormatInt(r.JobID, 10)
jobs = append(jobs, fetchedJob{
ExternalID: id,
Title: r.JobTitle,
Company: r.EmployerName,
Location: r.LocationName,
URL: r.JobURL,
Description: htmlToText(r.JobDescription),
PostedAt: parseTime("02/01/2006", r.Date),
detailID: id,
})
}
if len(results.Results) < searchPageSize {
break
}
}
return jobs, nil
}
// fetchReedDescription returns the full text of one Reed advert.
func (s *JobLeadService) fetchReedDescription(ctx context.Context, jobID string) (string, error) {
var detail reedDetail
target := fmt.Sprintf("%s/api/1.0/jobs/%s", reedBase, url.PathEscape(jobID))
if err := s.getJSON(ctx, target, s.Config.ReedAPIKey, &detail); err != nil {
return "", err
}
return htmlToText(detail.JobDescription), nil
}
// Helpers
// boardExternalID namespaces a board's own job id with the board, because
// ids are only unique within one company's board.
func boardExternalID(token, id string) string {
return strings.ToLower(strings.TrimSpace(token)) + "/" + id
}
// withWorkplace appends a posting's remote/hybrid/on-site label to its
// location, where the source reports one separately. The pre-filter matches
// on the result, so "remote" in the wanted locations finds these.
func withWorkplace(location, workplace string) string {
location = strings.TrimSpace(location)
workplace = strings.ToLower(strings.TrimSpace(workplace))
if workplace == "" || workplace == "unspecified" || strings.Contains(strings.ToLower(location), workplace) {
return location
}
if location == "" {
return workplace
}
return location + " (" + workplace + ")"
}
func joinNonEmpty(parts []string, sep string) string {
kept := parts[:0:0]
for _, p := range parts {
if strings.TrimSpace(p) != "" {
kept = append(kept, p)
}
}
return strings.Join(kept, sep)
}
// parseTime returns nil for a value that does not parse: a missing posting
// date is not worth failing a fetch over.
func parseTime(layout, value string) *time.Time {
t, err := time.Parse(layout, strings.TrimSpace(value))
if err != nil {
return nil
}
return &t
}
var (
// Tags that end a line in rendered HTML. Replaced with a newline before
// the rest are stripped, so paragraphs and bullets survive as lines.
htmlBlockTag = regexp.MustCompile(`(?i)</?(p|div|br|li|ul|ol|h[1-6]|tr|section)\b[^>]*>`)
htmlAnyTag = regexp.MustCompile(`<[^>]*>`)
htmlSpaces = regexp.MustCompile(`[ \t\x{00a0}]+`)
htmlBlankRuns = regexp.MustCompile(`\n[ \t]*(\n[ \t]*)+`)
)
// htmlToText reduces a posting's HTML to readable plain text. Like
// cleanEmailBody it is a regex strip, not a parser, which is enough for text
// that is read by a person and by a language model and never rendered as
// HTML. Unlike cleanEmailBody it keeps the whole text and its line structure.
func htmlToText(content string) string {
text := htmlBlockTag.ReplaceAllString(content, "\n")
text = htmlAnyTag.ReplaceAllString(text, "")
text = html.UnescapeString(text)
text = htmlSpaces.ReplaceAllString(text, " ")
text = htmlBlankRuns.ReplaceAllString(text, "\n\n")
lines := strings.Split(text, "\n")
for i, line := range lines {
lines[i] = strings.TrimSpace(line)
}
return strings.TrimSpace(strings.Join(lines, "\n"))
}
// 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])
}
+281
View File
@@ -0,0 +1,281 @@
package services
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"adam-french.co.uk/job-tracker/internal/models"
)
// The source fetchers, each against a stub server replying with a cut-down
// copy of a real response (the board kinds) or of the documented shape (the
// search kinds, which need API keys). What is under test is the request each
// one makes and how its JSON becomes a fetchedJob.
// sourceStub points every source's base URL at one stub server for the test.
func sourceStub(t *testing.T, config JobLeadConfig, handler http.HandlerFunc) *JobLeadService {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
for _, base := range []*string{&greenhouseBase, &leverBase, &ashbyBase, &adzunaBase, &reedBase} {
old := *base
*base = srv.URL
t.Cleanup(func() { *base = old })
}
return &JobLeadService{Config: &config, HTTPClient: srv.Client()}
}
func TestFetchGreenhouse(t *testing.T) {
var path string
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
path = r.URL.RequestURI()
w.Write([]byte(`{"jobs": [{
"absolute_url": "https://job-boards.greenhouse.io/monzo/jobs/8143930",
"location": {"name": "Cardiff, London or Remote (UK)"},
"id": 8143930,
"updated_at": "2026-09-25T05:17:09-04:00",
"title": "Backend Engineer",
"first_published": "2026-08-24T09:04:42-04:00",
"content": "&lt;div class=&quot;intro&quot;&gt;&lt;p&gt;&lt;strong&gt;About us&lt;/strong&gt;&lt;/p&gt;&lt;ul&gt;&lt;li&gt;Go &amp;amp; Kotlin&lt;/li&gt;&lt;li&gt;On-call&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;"
}], "meta": {"total": 1}}`))
})
jobs, err := s.fetchGreenhouse(context.Background(), models.JobSource{Kind: SourceGreenhouse, Label: "Monzo", Token: "Monzo"})
if err != nil {
t.Fatalf("fetchGreenhouse: %v", err)
}
if path != "/v1/boards/Monzo/jobs?content=true" {
t.Errorf("request = %q", path)
}
if len(jobs) != 1 {
t.Fatalf("got %d jobs", len(jobs))
}
j := jobs[0]
// The id is namespaced by the board, lowercased so "Monzo" and "monzo"
// are one board.
if j.ExternalID != "monzo/8143930" || j.Title != "Backend Engineer" || j.Company != "Monzo" ||
j.Location != "Cardiff, London or Remote (UK)" || j.URL != "https://job-boards.greenhouse.io/monzo/jobs/8143930" {
t.Errorf("job = %+v", j)
}
// Doubly escaped HTML comes out as plain lines.
if j.Description != "About us\n\nGo & Kotlin\n\nOn-call" {
t.Errorf("description = %q", j.Description)
}
if j.PostedAt == nil || j.PostedAt.UTC().Format("2006-01-02") != "2026-08-24" {
t.Errorf("postedAt = %v", j.PostedAt)
}
}
func TestFetchLever(t *testing.T) {
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
if r.URL.RequestURI() != "/v0/postings/acme?mode=json" {
t.Errorf("request = %q", r.URL.RequestURI())
}
w.Write([]byte(`[{
"additionalPlain": "We are an equal opportunity employer.",
"categories": {"commitment": "Full-time", "location": "London, UK", "team": "Platform"},
"createdAt": 1786469891368,
"descriptionPlain": "A World-Changing Company\n",
"id": "6ed76ce8-4156",
"lists": [{"text": "What you'll do", "content": "<li>Build things</li><li>Run them</li>"}],
"text": "Platform Engineer",
"workplaceType": "hybrid",
"hostedUrl": "https://jobs.lever.co/acme/6ed76ce8-4156"
}]`))
})
jobs, err := s.fetchLever(context.Background(), models.JobSource{Kind: SourceLever, Label: "Acme", Token: "acme"})
if err != nil || len(jobs) != 1 {
t.Fatalf("fetchLever: %v, %d jobs", err, len(jobs))
}
j := jobs[0]
if j.ExternalID != "acme/6ed76ce8-4156" || j.Title != "Platform Engineer" || j.Location != "London, UK (hybrid)" {
t.Errorf("job = %+v", j)
}
want := "A World-Changing Company\n\nWhat you'll do\nBuild things\n\nRun them\n\nWe are an equal opportunity employer."
if j.Description != want {
t.Errorf("description = %q\nwant %q", j.Description, want)
}
if j.PostedAt == nil || j.PostedAt.Year() != 2026 {
t.Errorf("postedAt = %v", j.PostedAt)
}
}
func TestFetchAshbySkipsUnlisted(t *testing.T) {
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/posting-api/job-board/ramp" {
t.Errorf("path = %q", r.URL.Path)
}
w.Write([]byte(`{"apiVersion": "1", "jobs": [
{"id": "34413f8d", "title": " Security Engineer, Cloud", "location": "London", "workplaceType": "Remote",
"publishedAt": "2026-04-07T17:12:35.753+00:00", "isListed": true,
"jobUrl": "https://jobs.ashbyhq.com/ramp/34413f8d", "descriptionPlain": "ABOUT RAMP\n\nRamp is building."},
{"id": "hidden", "title": "Secret", "isListed": false, "jobUrl": "https://jobs.ashbyhq.com/ramp/hidden"}
]}`))
})
jobs, err := s.fetchAshby(context.Background(), models.JobSource{Kind: SourceAshby, Label: "Ramp", Token: "ramp"})
if err != nil || len(jobs) != 1 {
t.Fatalf("fetchAshby: %v, %d jobs", err, len(jobs))
}
j := jobs[0]
if j.ExternalID != "ramp/34413f8d" || j.Title != "Security Engineer, Cloud" || j.Location != "London (remote)" ||
j.Description != "ABOUT RAMP\n\nRamp is building." || j.PostedAt == nil {
t.Errorf("job = %+v", j)
}
}
func TestFetchAdzuna(t *testing.T) {
var requests []string
s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "key1"}, func(w http.ResponseWriter, r *http.Request) {
requests = append(requests, r.URL.Path)
q := r.URL.Query()
if q.Get("app_id") != "id1" || q.Get("app_key") != "key1" || q.Get("what") != "golang" || q.Get("where") != "London" {
t.Errorf("query = %v", q)
}
w.Write([]byte(`{"results": [{
"id": "5012345678", "title": "<strong>Golang</strong> Developer",
"description": "We need a <strong>Golang</strong> developer…",
"redirect_url": "https://www.adzuna.co.uk/jobs/land/ad/5012345678?se=abc",
"created": "2026-10-01T09:00:00Z",
"company": {"display_name": "Acme Ltd"}, "location": {"display_name": "London, UK"}
}]}`))
})
jobs, err := s.fetchAdzuna(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "golang", Location: "London"})
if err != nil || len(jobs) != 1 {
t.Fatalf("fetchAdzuna: %v, %d jobs", err, len(jobs))
}
// A short page is the last page: no second request.
if len(requests) != 1 || requests[0] != "/v1/api/jobs/gb/search/1" {
t.Errorf("requests = %v", requests)
}
j := jobs[0]
if j.ExternalID != "5012345678" || j.Title != "Golang Developer" || j.Company != "Acme Ltd" ||
j.Description != "We need a Golang developer…" || j.detailID != "" {
t.Errorf("job = %+v", j)
}
}
func TestFetchReed(t *testing.T) {
s := sourceStub(t, JobLeadConfig{ReedAPIKey: "reedkey"}, func(w http.ResponseWriter, r *http.Request) {
// The key is the basic-auth username, with an empty password.
if user, pass, ok := r.BasicAuth(); !ok || user != "reedkey" || pass != "" {
t.Errorf("basic auth = %q %q %v", user, pass, ok)
}
switch r.URL.Path {
case "/api/1.0/search":
if q := r.URL.Query(); q.Get("keywords") != "golang" || q.Get("locationName") != "London" {
t.Errorf("query = %v", q)
}
w.Write([]byte(`{"results": [{"jobId": 51234567, "employerName": "Acme", "jobTitle": "Go Engineer",
"locationName": "London", "date": "03/10/2026", "jobDescription": "Snippet…",
"jobUrl": "https://www.reed.co.uk/jobs/go-engineer/51234567"}], "totalResults": 1}`))
case "/api/1.0/jobs/51234567":
w.Write([]byte(`{"jobId": 51234567, "jobDescription": "<p>The full advert.</p><p>Second paragraph.</p>"}`))
default:
t.Errorf("unexpected path %q", r.URL.Path)
}
})
jobs, err := s.fetchReed(context.Background(), models.JobSource{Kind: SourceReed, Query: "golang", Location: "London"})
if err != nil || len(jobs) != 1 {
t.Fatalf("fetchReed: %v, %d jobs", err, len(jobs))
}
j := jobs[0]
if j.ExternalID != "51234567" || j.Company != "Acme" || j.Description != "Snippet…" || j.detailID != "51234567" {
t.Errorf("job = %+v", j)
}
if j.PostedAt == nil || j.PostedAt.Format("2006-01-02") != "2026-10-03" {
t.Errorf("postedAt = %v", j.PostedAt)
}
full, err := s.fetchReedDescription(context.Background(), j.detailID)
if err != nil || full != "The full advert.\n\nSecond paragraph." {
t.Errorf("fetchReedDescription = %q, %v", full, err)
}
}
func TestSearchSourcesNeedTheirKeys(t *testing.T) {
s := sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) {
t.Errorf("no request should be made without a key, got %s", r.URL.Path)
})
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"}); err == nil || !strings.Contains(err.Error(), "ADZUNA_APP_ID") {
t.Errorf("adzuna err = %v", err)
}
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceReed, Query: "go"}); err == nil || !strings.Contains(err.Error(), "REED_API_KEY") {
t.Errorf("reed err = %v", err)
}
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: "monster"}); err == nil {
t.Error("an unknown kind should be an error")
}
}
// The error ends up in JobSource.LastError, on the page. It must say what to
// fix and must never quote the request URL, which for Adzuna holds the key.
func TestSourceErrorsAreSafeToShow(t *testing.T) {
cases := []struct {
status int
want string
}{
{http.StatusNotFound, "check the board token"},
{http.StatusUnauthorized, "check the API key"},
{http.StatusInternalServerError, "source returned 500"},
}
for _, c := range cases {
s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "sekrit"}, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(c.status)
})
_, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"})
if err == nil || !strings.Contains(err.Error(), c.want) || strings.Contains(err.Error(), "sekrit") {
t.Errorf("status %d: err = %v", c.status, err)
}
}
// A connection failure is the case where net/http would quote the URL.
s := sourceStub(t, JobLeadConfig{AdzunaAppID: "id1", AdzunaAppKey: "sekrit"}, func(http.ResponseWriter, *http.Request) {})
adzunaBase = "http://127.0.0.1:1"
_, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceAdzuna, Query: "go"})
if err == nil || strings.Contains(err.Error(), "sekrit") {
t.Errorf("connection failure: err = %v", err)
}
s = sourceStub(t, JobLeadConfig{}, func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("<html>")) })
if _, err := s.fetchSource(context.Background(), models.JobSource{Kind: SourceLever, Token: "acme"}); err == nil || !strings.Contains(err.Error(), "unexpected response") {
t.Errorf("non-JSON reply: err = %v", err)
}
}
func TestHTMLToText(t *testing.T) {
cases := []struct{ in, want string }{
{"<p>One</p><p>Two</p>", "One\n\nTwo"},
{"<ul><li>a</li><li>b &amp; c</li></ul>", "a\n\nb & c"},
{"plain text here", "plain text here"},
{"<span>inline</span> <b>tags</b> stay on a line", "inline tags stay on a line"},
{"line<br>break<br/>twice", "line\nbreak\ntwice"},
{"", ""},
}
for _, c := range cases {
if got := htmlToText(c.in); got != c.want {
t.Errorf("htmlToText(%q) = %q, want %q", c.in, got, c.want)
}
}
}
func TestWithWorkplace(t *testing.T) {
cases := []struct{ location, workplace, want string }{
{"London", "Hybrid", "London (hybrid)"},
{"Remote - UK", "remote", "Remote - UK"},
{"", "Remote", "remote"},
{"London", "", "London"},
{"London", "unspecified", "London"},
}
for _, c := range cases {
if got := withWorkplace(c.location, c.workplace); got != c.want {
t.Errorf("withWorkplace(%q, %q) = %q, want %q", c.location, c.workplace, got, c.want)
}
}
}
+75
View File
@@ -0,0 +1,75 @@
package services
import (
"fmt"
"strings"
"github.com/99designs/gqlgen/graphql"
)
// The job-status vocabulary, as GraphQL sees it.
//
// The schema declares `enum JobStatus` (graph/schema/job_application.graphql)
// and gqlgen.yml binds it to the two functions below instead of letting
// gqlgen generate a Go enum type. That keeps models.JobApplication.Status a
// plain string column — no migration, and the email pipeline and the capture
// endpoint go on writing strings — while the GraphQL boundary still refuses a
// status nobody ranked.
//
// statusOrder (email_sync.go) is the vocabulary; the enum in the schema has to
// list the same values, and TestJobStatusEnumMatchesStatusOrder fails when
// they differ. The functions live in this package, rather than in graph,
// because this is where statusOrder is and graph already imports services.
// KnownStatus reports whether s is exactly one of the tracked statuses. No
// trimming or case folding: see NormalizeStatus for the forgiving version the
// email pipeline and the capture endpoint use on values that did not come
// through GraphQL.
func KnownStatus(s string) bool {
_, ok := statusOrder[s]
return ok
}
// MarshalJobStatus writes a stored status to a GraphQL response.
//
// It is deliberately lenient, where the input side is strict. The column is
// older than the enum, so a row can hold a status outside the vocabulary: the
// tracker's early Title Case values ("Rejected"), or something written by
// hand. A generated enum type would fail to serialise such a row, and because
// JobApplication.status is non-null that one error would null out the whole
// jobApplications list — one stale row hiding every application. So:
//
// - a value that is in the vocabulary once trimmed and lowered is emitted
// in that canonical form, which also means an edit form sends back
// something the input side accepts;
// - anything else is emitted exactly as stored. That is not a legal
// JobStatus, strictly, but the response is JSON and the tracker page
// shows an unlisted status as-is so that it can be corrected, which is
// more use than an error or a made-up substitute.
//
// The value is written with gqlgen's own String marshaller, so it is the same
// quoted JSON string the field produced when it was declared String.
func MarshalJobStatus(s string) graphql.Marshaler {
if canonical := strings.ToLower(strings.TrimSpace(s)); KnownStatus(canonical) {
s = canonical
}
return graphql.MarshalString(s)
}
// UnmarshalJobStatus reads a status from a mutation's input, and is where
// drift is refused: only the exact lowercase values are accepted, so nothing
// outside the vocabulary can be written through GraphQL.
//
// The value arrives as a string whether the client sent a JSON string
// variable ("applied", which is what the tracker page does) or wrote the enum
// literal in the query document (applied).
func UnmarshalJobStatus(v any) (string, error) {
s, ok := v.(string)
if !ok {
return "", fmt.Errorf("status must be a string")
}
if !KnownStatus(s) {
return "", fmt.Errorf("%q is not a valid JobStatus", s)
}
return s, nil
}
+126
View File
@@ -0,0 +1,126 @@
package services
import (
"bytes"
"os"
"slices"
"sort"
"testing"
"github.com/vektah/gqlparser/v2"
"github.com/vektah/gqlparser/v2/ast"
)
// jobStatusEnumValues reads `enum JobStatus` out of the schema file itself.
// The test lives here, not in graph, because statusOrder is unexported and
// graph imports this package; parsing the file directly avoids both an
// export that exists only for a test and an import cycle.
func jobStatusEnumValues(t *testing.T) []string {
t.Helper()
const path = "../graph/schema/job_application.graphql"
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("reading the schema: %v", err)
}
// The file extends Query and Mutation and uses Time and the two
// authorisation directives, all declared in schema.graphql; give it just
// enough of those to parse on its own.
const prelude = "scalar Time\ndirective @admin on FIELD_DEFINITION\ndirective @signedIn on FIELD_DEFINITION\ntype Query\ntype Mutation\n"
schema, gqlErr := gqlparser.LoadSchema(
&ast.Source{Name: "prelude", Input: prelude},
&ast.Source{Name: path, Input: string(raw)},
)
if gqlErr != nil {
t.Fatalf("parsing the schema: %v", gqlErr)
}
def := schema.Types["JobStatus"]
if def == nil || def.Kind != ast.Enum {
t.Fatal("the schema has no `enum JobStatus`")
}
var values []string
for _, v := range def.EnumValues {
values = append(values, v.Name)
}
return values
}
// One vocabulary, two places it has to be written down: the enum the GraphQL
// API validates against and the map the email pipeline ranks with. A status
// in the enum but not the map could be saved from the tracker and then never
// advanced; one in the map but not the enum could be stored by the pipeline
// and then not edited.
func TestJobStatusEnumMatchesStatusOrder(t *testing.T) {
enum := jobStatusEnumValues(t)
var ranked []string
for status := range statusOrder {
ranked = append(ranked, status)
}
sort.Strings(ranked)
sorted := slices.Clone(enum)
sort.Strings(sorted)
if !slices.Equal(sorted, ranked) {
t.Fatalf("enum JobStatus = %v\nstatusOrder = %v\nthe two must list the same statuses", sorted, ranked)
}
// The schema lists them in lifecycle order, which is the order the
// tracker shows; keep it agreeing with the ranks.
for i, status := range enum {
if statusOrder[status] != i {
t.Errorf("enum lists %q at position %d but statusOrder ranks it %d", status, i, statusOrder[status])
}
}
}
// The exact strings, spelled out once: these are what is stored in the
// database and sent by the front end and the userscript, so a rename is a
// data migration, not an edit.
func TestJobStatusVocabulary(t *testing.T) {
want := []string{"saved", "applied", "screening", "assessment", "interviewing", "offer", "rejected", "withdrawn"}
if got := jobStatusEnumValues(t); !slices.Equal(got, want) {
t.Fatalf("enum JobStatus = %v, want %v", got, want)
}
}
func TestUnmarshalJobStatus(t *testing.T) {
for status := range statusOrder {
if got, err := UnmarshalJobStatus(status); err != nil || got != status {
t.Errorf("UnmarshalJobStatus(%q) = %q, %v", status, got, err)
}
}
// Strict on the way in: none of the forgiveness NormalizeStatus shows the
// email pipeline. In particular nothing is coerced to "applied".
for _, bad := range []any{"hired", "Applied", " applied", "", "on hold", 3, nil, true} {
if got, err := UnmarshalJobStatus(bad); err == nil {
t.Errorf("UnmarshalJobStatus(%#v) = %q, want an error", bad, got)
}
}
}
func TestMarshalJobStatus(t *testing.T) {
cases := []struct {
name string
stored string
want string
}{
{"a tracked status is a quoted string, as when the field was a String", "interviewing", `"interviewing"`},
{"the tracker's old Title Case rows read back canonical", "Rejected", `"rejected"`},
{"stray whitespace is dropped for a tracked status", " offer ", `"offer"`},
// The reason this is a custom marshaller: a generated enum type would
// error here, and status is non-null, so one such row would null the
// whole jobApplications list.
{"an untracked status is passed through, not refused", "Interview", `"Interview"`},
{"an untracked status is not rewritten to the default", "on hold", `"on hold"`},
{"an empty status stays empty", "", `""`},
{"quotes in a stray value are escaped", `a"b`, `"a\"b"`},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
var b bytes.Buffer
MarshalJobStatus(c.stored).MarshalGQL(&b)
if b.String() != c.want {
t.Fatalf("MarshalJobStatus(%q) wrote %s, want %s", c.stored, &b, c.want)
}
})
}
}
+241
View File
@@ -0,0 +1,241 @@
package services
import (
"fmt"
"net/url"
"regexp"
"strings"
"time"
"adam-french.co.uk/job-tracker/internal/models"
"gorm.io/gorm"
)
// Adding a posting to the job tracker without making a second row for one
// that is already there. Three callers share this: the browser capture
// endpoint (handlers/handle_job_capture.go), promoting a discovered lead
// (graph/job_lead.resolvers.go), and the lead fetcher (job_leads.go), which
// uses the URL matching to keep a posting already tracked out of the inbox.
// It lives in services because the fetcher does, and services cannot import
// handlers.
// 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
}
// FindApplicationByURL 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 FindApplicationByURL(db *gorm.DB, canonical, raw string) (*models.JobApplication, error) {
return firstApplication(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
}
// JobCaptureInput is a posting to add to the tracker. Its JSON form is the
// body of POST /jobs/capture: the popup's fields.
type JobCaptureInput 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 JobCaptureInput, now time.Time) bool {
changed := false
if status := NormalizeStatus(in.Status); 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
}
// JobInputError is a problem with the input itself (a missing title, a URL
// that is not one), worded for the person who sent it. Anything else
// UpsertJobApplication returns is a database failure and belongs in the log.
type JobInputError struct{ msg string }
func (e *JobInputError) Error() string { return e.msg }
// UpsertJobApplication adds a posting to the tracker, or folds it into the
// application it matches, and reports which: "created", "updated" or
// "unchanged".
//
// The upsert 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.
// Capturing or promoting is a deliberate act, so doing it for a posting whose
// row was deleted makes a new row.
//
// The caller bounds Description's length; everything else is trimmed here.
func UpsertJobApplication(db *gorm.DB, input JobCaptureInput, now time.Time) (*models.JobApplication, string, error) {
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 = strings.TrimSpace(input.Description)
if input.JobTitle == "" || input.Company == "" {
return nil, "", &JobInputError{"jobTitle and company are required"}
}
rawURL := input.URL
if strings.TrimSpace(rawURL) != "" {
canonical, ok := CanonicalJobURL(rawURL)
if !ok {
return nil, "", &JobInputError{"url must be an absolute http(s) URL"}
}
input.URL = canonical
} else {
input.URL = ""
}
var existing *models.JobApplication
var err error
if input.URL != "" {
existing, err = FindApplicationByURL(db, input.URL, rawURL)
}
if err == nil && existing == nil {
existing, err = firstApplication(db.Where(
"LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", input.Company, input.JobTitle))
}
if err != nil {
return nil, "", fmt.Errorf("looking up the application: %w", err)
}
if existing != nil {
if !MergeCapture(existing, input, now) {
return existing, "unchanged", nil
}
if err := db.Save(existing).Error; err != nil {
return nil, "", fmt.Errorf("updating the application: %w", err)
}
return existing, "updated", nil
}
// A new row is the merge of the input 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 := db.Create(&app).Error; err != nil {
return nil, "", fmt.Errorf("creating the application: %w", err)
}
return &app, "created", nil
}
+121
View File
@@ -0,0 +1,121 @@
package services
import (
"testing"
"time"
"adam-french.co.uk/job-tracker/internal/models"
)
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 := JobCaptureInput{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, JobCaptureInput{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, JobCaptureInput{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, JobCaptureInput{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 := JobCaptureInput{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 := JobCaptureInput{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)
}
})
}
+73
View File
@@ -0,0 +1,73 @@
package services
import (
"log"
"time"
"adam-french.co.uk/job-tracker/internal/models"
"gorm.io/gorm"
)
// SeedDatabase populates an empty database with demo content for local
// development. It is called from main only when SEED_DB=true, which the
// standalone docker-compose.yml and the main site's dev override set.
func SeedDatabase(db *gorm.DB) {
// "The profile row exists" is the whole idempotency check: if it does,
// nothing is seeded, even if the other tables were emptied.
var count int64
if db.Model(&models.JobSearchProfile{}).Count(&count); count > 0 {
log.Println("Database already has data, skipping seed")
return
}
log.Println("Seeding database with test data...")
now := time.Now()
applied := now.AddDate(0, 0, -10)
london := "London"
applications := []models.JobApplication{
{JobTitle: "Backend Engineer", Company: "Acme", Location: &london, Status: "interviewing", AppliedAt: &applied},
{JobTitle: "Platform Engineer", Company: "Globex", Status: "applied", AppliedAt: &applied},
{JobTitle: "Go Developer", Company: "Initech", Status: "saved"},
{JobTitle: "Software Engineer", Company: "Umbrella", Status: "rejected", AppliedAt: &applied},
}
db.Create(&applications)
db.Create(&[]models.JobAppReference{
{Category: "Links", Label: "GitHub", Value: "https://example.com/github", SortOrder: 0},
{Category: "Answers", Label: "Notice period", Value: "One month", SortOrder: 0},
})
// Leads, so /jobs/leads has something to show without a poll: the dev
// stack usually has no Claude key, and the scheduler is off by default.
// The sources are real public boards, so "Check now" works against them.
db.Create(&models.JobSearchProfile{
ID: jobSearchProfileID,
Profile: "Five years of backend work in Go and Python. Looking for a mid-level or senior backend or platform role, in London or remote in the UK.",
IncludeKeywords: "engineer\ndeveloper",
ExcludeKeywords: "intern\nmanager",
Locations: "london\nremote",
MinScore: 60,
})
sources := []models.JobSource{
{Kind: SourceGreenhouse, Label: "Monzo", Token: "monzo", Enabled: true},
{Kind: SourceAshby, Label: "Ramp", Token: "ramp", Enabled: false},
}
db.Create(&sources)
high, mid, low := 86, 64, 35
highWhy := "Your Go and platform experience matches the core requirements; no payments background."
midWhy := "Backend fit is good, but the role wants Kotlin, which your profile does not mention."
lowWhy := "The role is a staff-level position leading several teams, above the level you are after."
posted := now.AddDate(0, 0, -3)
leads := []models.JobLead{
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-1", JobTitle: "Backend Engineer, Platform", Company: "Monzo", Location: "London or Remote (UK)", URL: "https://example.com/jobs/1", Description: "We are looking for a backend engineer to join our platform team.\n\nYou will build and run Go services.", PostedAt: &posted, LastSeenAt: now, Matched: true, State: LeadNew, Score: &high, ScoreReasons: &highWhy},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-2", JobTitle: "Senior Backend Engineer", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/2", Description: "Kotlin services at scale.", LastSeenAt: now, Matched: true, State: LeadNew, Score: &mid, ScoreReasons: &midWhy},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-3", JobTitle: "Staff Engineer", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/3", LastSeenAt: now, Matched: true, State: LeadNew, Score: &low, ScoreReasons: &lowWhy},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-4", JobTitle: "Software Engineer, Data", Company: "Monzo", Location: "Remote (UK)", URL: "https://example.com/jobs/4", LastSeenAt: now, Matched: true, State: LeadNew},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-5", JobTitle: "Account Executive", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/5", LastSeenAt: now, Matched: false, State: LeadNew},
{SourceID: sources[0].ID, SourceKind: SourceGreenhouse, ExternalID: "monzo/seed-6", JobTitle: "Android Engineer", Company: "Monzo", Location: "London", URL: "https://example.com/jobs/6", LastSeenAt: now, Matched: true, State: LeadDismissed, Score: &low},
}
db.Create(&leads)
log.Println("Database seeded successfully")
}