Declare GraphQL auth in the schema and drop the Go Claude client
Authorisation: @admin and @signedIn schema directives replace the 25 hand-copied resolver checks. A test fails if a mutation has neither and is not on the public allow-list, so a new mutation cannot ship unguarded. IDs: uint model IDs bind through graphql.UintID, removing the ten int(obj.ID) resolvers. Job status is a GraphQL enum, tied to services.statusOrder by a test. Input is strict, so the mutations no longer coerce an unknown status to "applied"; output is lenient so one legacy row cannot fail the list. deleteJobApplication and deleteJobAppReference now error on a missing id like the other deletes. The rowing reader, the job extractor and now the email classifier reach the Python service through one services.CallPython helper. The email pipeline's prompt and fence stripping moved to Python, and anthropic-sdk-go is gone from go.mod. Fix the auth test fixture, whose 11-byte secret had been panicking the services test package since InitAuth began requiring 32 bytes. Add a test that keeps the python service's compose environment list in step with the env registry. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -18,7 +18,9 @@ import (
|
||||
|
||||
func testAuth() *Auth {
|
||||
return InitAuth(&AuthConfig{
|
||||
Secret: []byte("test-secret"),
|
||||
// InitAuth panics on anything under 32 bytes, so the fixture has to be
|
||||
// a realistic length even though nothing here depends on its value.
|
||||
Secret: []byte("test-secret-0123456789abcdef0123456789"),
|
||||
Domain: "example.test",
|
||||
AccessTokenLifetime: time.Hour,
|
||||
RefreshTokenLifetime: 24 * time.Hour,
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
)
|
||||
|
||||
// ClaudeConfig holds the Anthropic API credentials.
|
||||
type ClaudeConfig struct {
|
||||
APIKey string
|
||||
}
|
||||
|
||||
// InitClaude builds the Anthropic client used to classify job-application
|
||||
// emails (EmailSyncService.processEmail). The other Claude caller, the rowing
|
||||
// photo reader, lives in the Python service and builds its own client from
|
||||
// the same CLAUDE_API_KEY.
|
||||
//
|
||||
// No validation happens here: with an empty or wrong API key construction
|
||||
// still succeeds and the failure only surfaces on the first request.
|
||||
func InitClaude(config *ClaudeConfig) *anthropic.Client {
|
||||
// anthropic.NewClient returns a value, not a pointer, so take its address
|
||||
// so it can be handed around without copying.
|
||||
client := anthropic.NewClient(option.WithAPIKey(config.APIKey))
|
||||
return &client
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// The classify step of the email pipeline: the request the Python service's
|
||||
// /internal/email/classify receives, and what processEmail does with each
|
||||
// kind of reply. A stub server stands in for Python.
|
||||
//
|
||||
// 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.
|
||||
|
||||
func classifierStub(t *testing.T, handler http.HandlerFunc) *EmailSyncService {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return &EmailSyncService{PythonURL: srv.URL}
|
||||
}
|
||||
|
||||
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 for applying</p>"},
|
||||
}
|
||||
email.From.EmailAddress = graphEmailAddress{Name: "Acme Hiring", Address: "[email protected]"}
|
||||
return email
|
||||
}
|
||||
|
||||
func TestClassifyEmailRequest(t *testing.T) {
|
||||
var path string
|
||||
var body map[string]any
|
||||
s := classifierStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"isJobEmail": true, "action": "create", "company": "Acme", "jobTitle": "Engineer",
|
||||
"status": "applied", "location": "London", "url": null, "appliedAt": "2026-03-15", "notes": null}`))
|
||||
})
|
||||
|
||||
analysis, err := s.classifyEmail(context.Background(), testEmail())
|
||||
if err != nil {
|
||||
t.Fatalf("classifyEmail: %v", err)
|
||||
}
|
||||
if path != "/internal/email/classify" {
|
||||
t.Fatalf("path = %q", path)
|
||||
}
|
||||
// The whole contract: one key, holding the headers, a blank line and the
|
||||
// cleaned body. The Python side hands this string to Claude unchanged.
|
||||
want := "Subject: Your application to Acme\nFrom: Acme Hiring <[email protected]>\nDate: 2026-03-15T10:30:00Z\n\nThanks for applying"
|
||||
if len(body) != 1 || body["message"] != want {
|
||||
t.Fatalf("request body = %v\nwant message %q", body, want)
|
||||
}
|
||||
|
||||
if !analysis.IsJobEmail || analysis.Action != "create" || analysis.Company != "Acme" ||
|
||||
analysis.JobTitle != "Engineer" || analysis.Status != "applied" {
|
||||
t.Fatalf("analysis = %+v", analysis)
|
||||
}
|
||||
if analysis.Location == nil || *analysis.Location != "London" || analysis.URL != nil ||
|
||||
analysis.AppliedAt == nil || *analysis.AppliedAt != "2026-03-15" || analysis.Notes != nil {
|
||||
t.Fatalf("nullable fields = %+v", analysis)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcessEmailWithoutAJob(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
reply string
|
||||
}{
|
||||
// What Python sends for a non-job email: every other field defaulted.
|
||||
{"not a job email", `{"isJobEmail": false, "action": "", "company": "", "jobTitle": "", "status": "",
|
||||
"location": null, "url": null, "appliedAt": null, "notes": null}`},
|
||||
// (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", `{"isJobEmail": true, "action": "create", "company": "", "jobTitle": "Engineer", "status": "applied"}`},
|
||||
{"a job email with no title", `{"isJobEmail": true, "action": "create", "company": "Acme", "jobTitle": "", "status": "applied"}`},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s := classifierStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(c.reply))
|
||||
})
|
||||
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
|
||||
status int
|
||||
body string
|
||||
wantRelayed string // the 502 detail, when there is one
|
||||
}{
|
||||
{"Claude failed", http.StatusBadGateway, `{"detail": "failed to classify the email"}`, "failed to classify the email"},
|
||||
{"Claude's reply was unparseable", http.StatusBadGateway, `{"detail": "failed to parse the email classification"}`, "failed to parse the email classification"},
|
||||
{"no API key", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"request rejected", http.StatusUnprocessableEntity, `{"detail": [{"msg": "too long"}]}`, ""},
|
||||
{"malformed 200 body", http.StatusOK, `not json`, ""},
|
||||
{"200 body of the wrong shape", http.StatusOK, `{"isJobEmail": "yes"}`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
s := classifierStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
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)
|
||||
}
|
||||
var pyErr *PythonError
|
||||
if errors.As(err, &pyErr) != (c.wantRelayed != "") {
|
||||
t.Fatalf("err = %v, want PythonError: %v", err, c.wantRelayed != "")
|
||||
}
|
||||
if pyErr != nil && pyErr.Detail != c.wantRelayed {
|
||||
t.Fatalf("detail = %q, want %q", pyErr.Detail, c.wantRelayed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 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(t, func(http.ResponseWriter, *http.Request) {})
|
||||
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, as the Python side
|
||||
// does, 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")
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import "testing"
|
||||
// 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 Claude or the
|
||||
// Graph API either; email classification is a network call by construction.
|
||||
// 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 {
|
||||
|
||||
@@ -17,7 +17,6 @@ import (
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"golang.org/x/oauth2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -27,6 +26,13 @@ import (
|
||||
// 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: like the site's other two, it
|
||||
// lives in the Python service (python/app/email_classify.py, which owns the
|
||||
// prompt and the parsing of the model's reply) and is reached through
|
||||
// CallPython. 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.
|
||||
|
||||
// MSGRAPH_TOKEN_JSON_PATH lives in a Docker volume so the OAuth refresh token
|
||||
// survives restarts, exactly like the Spotify token.
|
||||
@@ -54,9 +60,12 @@ type EmailSyncService struct {
|
||||
// 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
|
||||
ClaudeClient *anthropic.Client
|
||||
HTTPClient *http.Client
|
||||
DB *gorm.DB
|
||||
// PythonURL is the Python service's base URL on the Docker network, no
|
||||
// trailing slash: the same value as handlers.Store.PythonURL. The
|
||||
// classifier is called there (see classifyEmail).
|
||||
PythonURL string
|
||||
// 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.
|
||||
@@ -103,11 +112,15 @@ type graphBody struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Claude response type
|
||||
// Classifier response type
|
||||
|
||||
// EmailAnalysis is the JSON contract Claude is asked to return; the keys here
|
||||
// must stay in step with emailClassificationPrompt at the bottom of this file.
|
||||
// Pointer fields are the ones Claude is allowed to answer null for.
|
||||
// EmailAnalysis is the JSON contract with the Python service's
|
||||
// /internal/email/classify: the body of its 200 reply. The keys here must stay
|
||||
// in step with EmailAnalysis and the prompt in python/app/email_classify.py,
|
||||
// which asks Claude for exactly these. Pointer fields are the ones that may
|
||||
// come back null; the plain strings come back "" when the model had nothing
|
||||
// (or when the email is not a job email, in which case only IsJobEmail means
|
||||
// anything).
|
||||
type EmailAnalysis struct {
|
||||
IsJobEmail bool `json:"isJobEmail"`
|
||||
Action string `json:"action"`
|
||||
@@ -122,7 +135,7 @@ type EmailAnalysis struct {
|
||||
|
||||
// Email filtering config
|
||||
|
||||
// Cheap pre-filter, applied before any Claude call so that the bulk of a
|
||||
// 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).
|
||||
@@ -155,6 +168,13 @@ var senderDomains = []string{
|
||||
// "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 python/app/email_classify.py (all but "saved"), the
|
||||
// tracker page and the capture userscript.
|
||||
var statusOrder = map[string]int{
|
||||
"saved": 0,
|
||||
"applied": 1,
|
||||
@@ -263,11 +283,15 @@ func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
|
||||
// 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.
|
||||
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, claudeClient *anthropic.Client) *EmailSyncService {
|
||||
//
|
||||
// pythonURL is where the classifier lives. It is not validated or probed: an
|
||||
// unreachable Python service shows up as each email failing and being
|
||||
// retried, the same way a bad API key used to.
|
||||
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, pythonURL string) *EmailSyncService {
|
||||
svc := &EmailSyncService{
|
||||
Config: config,
|
||||
DB: db,
|
||||
ClaudeClient: claudeClient,
|
||||
Config: config,
|
||||
DB: db,
|
||||
PythonURL: pythonURL,
|
||||
}
|
||||
|
||||
switch config.Backend {
|
||||
@@ -618,48 +642,66 @@ func (s *EmailSyncService) matchesFilter(email graphMessage) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// processEmail sends a single email to Claude 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) {
|
||||
cleaned := cleanEmailBody(email.Body.Content, email.Body.ContentType)
|
||||
// emailClassifyPath is the Python route, internal in the same way as the
|
||||
// rowing and job-posting readers' (see python_call.go).
|
||||
const emailClassifyPath = "/internal/email/classify"
|
||||
|
||||
userMsg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
|
||||
// maxClassifyRunes mirrors MAX_MESSAGE_CHARS in python/app/email_classify.py,
|
||||
// which answers 422 to anything longer. cleanEmailBody already caps the body
|
||||
// far below this, so the limit only bites on a pathological subject or sender
|
||||
// — but a 422 would be recorded as a failed attempt and retried to the cap,
|
||||
// so the cut is made here rather than left to chance.
|
||||
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. The Python side
|
||||
// passes the string to Claude unchanged, so this layout is part of what the
|
||||
// prompt there 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,
|
||||
cleaned,
|
||||
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])
|
||||
}
|
||||
|
||||
message, err := s.ClaudeClient.Messages.New(ctx, anthropic.MessageNewParams{
|
||||
Model: anthropic.ModelClaudeHaiku4_5,
|
||||
MaxTokens: 512,
|
||||
System: []anthropic.TextBlockParam{
|
||||
{Text: emailClassificationPrompt},
|
||||
},
|
||||
Messages: []anthropic.MessageParam{
|
||||
{
|
||||
Role: "user",
|
||||
Content: []anthropic.ContentBlockParamUnion{anthropic.NewTextBlock(userMsg)},
|
||||
},
|
||||
},
|
||||
})
|
||||
// classifyEmail asks the Python service what an email is. Every failure —
|
||||
// the service unreachable, Claude failing (502), no API key (503), 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 := CallPython[EmailAnalysis](ctx, s.PythonURL, emailClassifyPath, struct {
|
||||
Message string `json:"message"`
|
||||
}{classifierMessage(email)})
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("Claude API error: %w", err)
|
||||
// %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
|
||||
}
|
||||
|
||||
if len(message.Content) == 0 {
|
||||
return "", nil, fmt.Errorf("empty response from Claude")
|
||||
}
|
||||
|
||||
// Only the first content block is read, and the prompt asks for bare JSON,
|
||||
// but models still wrap output in a markdown fence often enough that it is
|
||||
// stripped defensively here.
|
||||
raw := StripMarkdownFence(message.Content[0].Text)
|
||||
|
||||
var analysis EmailAnalysis
|
||||
if err := json.Unmarshal([]byte(raw), &analysis); err != nil {
|
||||
return "", nil, fmt.Errorf("parsing Claude response: %w (raw: %s)", err, raw)
|
||||
// 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 {
|
||||
@@ -708,6 +750,11 @@ func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage)
|
||||
// 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 {
|
||||
@@ -798,7 +845,7 @@ func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication,
|
||||
}
|
||||
|
||||
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
|
||||
// Claude, cutting token cost and noise.
|
||||
// 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
|
||||
@@ -859,7 +906,9 @@ func cleanEmailBody(content string, contentType string) string {
|
||||
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; harmless for a model prompt.
|
||||
// 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]
|
||||
}
|
||||
@@ -876,44 +925,6 @@ func truncate(s string, maxLen int) string {
|
||||
return s[:maxLen]
|
||||
}
|
||||
|
||||
// emailClassificationPrompt must stay in sync with the EmailAnalysis struct:
|
||||
// every key it names is a field there, and the status values it lists are the
|
||||
// keys of statusOrder — all but "saved", which only the browser capture sets
|
||||
// and no email can mean.
|
||||
const emailClassificationPrompt = `You are an email classifier for job applications. You will receive the subject line, sender, and body of an email. Determine if this email is related to a job application, and if so, extract structured data.
|
||||
|
||||
Return ONLY a JSON object with these exact keys:
|
||||
- "isJobEmail": boolean - true if this email is about a job application
|
||||
- "action": "create" | "update" | "none" - whether this represents a new application confirmation or an update to an existing one
|
||||
- "company": string - the company name
|
||||
- "jobTitle": string - the job title/position
|
||||
- "status": string - one of: "applied", "screening", "interviewing", "assessment", "offer", "rejected", "withdrawn"
|
||||
- "location": string or null - job location if mentioned
|
||||
- "url": string or null - any application portal URL
|
||||
- "appliedAt": string or null - ISO 8601 date if an application date is mentioned (YYYY-MM-DD format)
|
||||
- "notes": string or null - brief summary of what this email communicates (e.g. "Interview scheduled for March 15", "Application confirmed via Greenhouse")
|
||||
|
||||
If isJobEmail is false, only include that field. No text, no markdown, no explanation. Just the JSON object.`
|
||||
|
||||
// StripMarkdownFence removes a surrounding markdown code fence from a model's
|
||||
// response, so text that should have been bare JSON can be unmarshalled
|
||||
// whether or not the model wrapped it.
|
||||
//
|
||||
// The two TrimPrefix calls are ordered so that "```json" is removed first and
|
||||
// a plain "```" otherwise. It is deliberately forgiving: unfenced input is
|
||||
// returned unchanged apart from surrounding whitespace.
|
||||
//
|
||||
// python/app/rowing.py carries a port of this for the rowing photo reader,
|
||||
// which prompts for bare JSON in the same way and gets the same fenced output.
|
||||
func StripMarkdownFence(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@@ -8,12 +8,13 @@ import (
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// These tests cover only the pure helpers of the email sync: body cleaning,
|
||||
// truncation, fence stripping, timestamp parsing, the retry predicate and the
|
||||
// filter. Everything else in email_sync.go — token acquisition, the Graph
|
||||
// paging loop, processEmail and the create/update paths — needs either a live
|
||||
// *gorm.DB, a Microsoft Graph endpoint or a Claude call, none of which exist
|
||||
// in a test run, so they are deliberately not exercised here.
|
||||
// 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 is an HTTP call to the Python service, 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
|
||||
@@ -135,29 +136,6 @@ func TestTruncate(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripMarkdownFence(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{"json-tagged fence", "```json\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"bare fence", "```\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"unfenced input is returned as-is", `{"a":1}`, `{"a":1}`},
|
||||
{"surrounding whitespace is trimmed", "\n\n {\"a\":1} \n", `{"a":1}`},
|
||||
{"leading whitespace before the fence", " ```json\n{\"a\":1}\n``` ", `{"a":1}`},
|
||||
{"opening fence only", "```json\n{\"a\":1}", `{"a":1}`},
|
||||
{"empty input", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := StripMarkdownFence(c.raw); got != c.want {
|
||||
t.Fatalf("StripMarkdownFence(%q) = %q, want %q", c.raw, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseReceivedAt(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
|
||||
@@ -63,6 +63,93 @@ func TestEnvRegistryMatchesEnvExample(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// composePythonEnv returns the variable names in the `environment:` list of
|
||||
// the `python` service in docker-compose.yml.
|
||||
//
|
||||
// It reads the file as text rather than through a YAML library — there is
|
||||
// none among this module's direct dependencies, and the shape needed is
|
||||
// narrow: a two-space-indented `python:` key under `services:`, a
|
||||
// four-space-indented `environment:` under it, and `- NAME=value` items. If
|
||||
// the compose file is ever restructured so that this finds nothing, the test
|
||||
// below fails loudly rather than passing on an empty list.
|
||||
func composePythonEnv(t *testing.T) []string {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile("../../docker-compose.yml")
|
||||
if err != nil {
|
||||
t.Fatalf("reading docker-compose.yml: %v", err)
|
||||
}
|
||||
|
||||
item := regexp.MustCompile(`^ - ["']?([A-Z][A-Z0-9_]*)(=|["']?\s*$)`)
|
||||
var names []string
|
||||
inPython, inEnvironment := false, false
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
||||
continue
|
||||
}
|
||||
indent := len(line) - len(strings.TrimLeft(line, " "))
|
||||
switch {
|
||||
case indent <= 2:
|
||||
// A new service (or a top-level key) ends the block.
|
||||
inPython, inEnvironment = line == " python:", false
|
||||
case inPython && indent == 4:
|
||||
inEnvironment = trimmed == "environment:"
|
||||
case inPython && inEnvironment:
|
||||
match := item.FindStringSubmatch(line)
|
||||
if match == nil {
|
||||
t.Fatalf("python.environment has an entry this test cannot read: %q", line)
|
||||
}
|
||||
names = append(names, match[1])
|
||||
}
|
||||
}
|
||||
if len(names) == 0 {
|
||||
t.Fatal("found no python.environment list in docker-compose.yml; has the file's layout changed?")
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
// The python service is the one container given an explicit `environment:`
|
||||
// list instead of the whole .env, so that it never holds the database
|
||||
// password or the JWT secret. The cost is a third place a new Python variable
|
||||
// has to be added — the registry, .env.example and that list — and forgetting
|
||||
// the third is silent: the variable is simply empty inside the container.
|
||||
//
|
||||
// So the registry's claim "python reads this" and the compose list must
|
||||
// agree, in both directions:
|
||||
//
|
||||
// - a variable the registry says python reads must be passed to it;
|
||||
// - an editable variable that is passed to it must say so in the registry,
|
||||
// or changing it in the admin panel would not recreate the container.
|
||||
//
|
||||
// Locked variables are exempt from the second rule. They are never applied
|
||||
// through the panel, so the registry gives none of them a services list
|
||||
// (PYTHON_PORT is passed to python and is one of these). Names in the compose
|
||||
// list that are not registry variables at all, such as the literal ROOT_PATH,
|
||||
// are not this test's business.
|
||||
func TestEnvRegistryMatchesComposePythonEnvironment(t *testing.T) {
|
||||
compose := composePythonEnv(t)
|
||||
|
||||
registry := map[string]EnvVar{}
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
registry[v.Name] = v
|
||||
if slices.Contains(v.Services, "python") && !slices.Contains(compose, v.Name) {
|
||||
t.Errorf("%s lists the python service in env_registry.json but is not in "+
|
||||
"python.environment in docker-compose.yml, so the container never receives it", v.Name)
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range compose {
|
||||
v, known := registry[name]
|
||||
if !known || !v.Editable {
|
||||
continue
|
||||
}
|
||||
if !slices.Contains(v.Services, "python") {
|
||||
t.Errorf("%s is passed to the python service in docker-compose.yml but env_registry.json "+
|
||||
"does not list python among its services, so editing it would not recreate the container", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvRegistryEntriesAreWellFormed(t *testing.T) {
|
||||
kinds := []string{"secret", "generated", "text", "url", "bool", "duration", "number", "enum"}
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
[
|
||||
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Email pipeline, rowing photo reader, job posting reader", "kind": "secret", "editable": true, "services": ["backend", "python"], "docsUrl": "https://console.anthropic.com/settings/keys"},
|
||||
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Claude calls, all made by the Python service: email classifier, rowing photo reader, job posting reader", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://console.anthropic.com/settings/keys"},
|
||||
{"name": "STEAM_API_KEY", "group": "API keys", "purpose": "Steam status widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://steamcommunity.com/dev/apikey"},
|
||||
{"name": "STEAM_ID", "group": "API keys", "purpose": "Steam account the widget reports on (64-bit ID)", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "TFL_APP_KEY", "group": "API keys", "purpose": "TfL Unified API, used by the hotel finder", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://api-portal.tfl.gov.uk/profile"},
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Every Claude call the site makes lives in the Python service, behind an
|
||||
// /internal/ route. This file is the one way the Go backend reaches those
|
||||
// routes: the rowing photo reader and the job posting reader (handlers), and
|
||||
// the email classifier (email_sync.go). It sits in services rather than
|
||||
// handlers because both packages need it and handlers already imports
|
||||
// services, not the other way round.
|
||||
//
|
||||
// The routes are internal in a specific sense: nginx answers 404 for
|
||||
// /py/internal/, and each route itself refuses a request carrying a proxy
|
||||
// header, so the only way in is this direct container-to-container call. That
|
||||
// is why the request below sets nothing but Content-Type.
|
||||
|
||||
// pythonClient bounds the wait on the Python service. Two minutes sits above
|
||||
// that side's own worst case (a 30s Claude timeout, retried twice with
|
||||
// backoff), so a slow Claude surfaces as Python's error rather than as a
|
||||
// timeout here. One client for every route, so they share a connection pool.
|
||||
var pythonClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
// PythonError is a failure the Python service reported in words that are safe
|
||||
// and useful to show a person: the string `detail` of a 502, which is always
|
||||
// one of that route's own fixed messages ("failed to parse image data", ...).
|
||||
//
|
||||
// Everything else — a refused connection, a 422, a 503 for a missing API key,
|
||||
// a reply that will not decode — comes back as an ordinary error instead. The
|
||||
// distinction is the point: a caller relays a PythonError and only logs the
|
||||
// rest, because the rest describe plumbing the user can do nothing about and
|
||||
// may quote internals.
|
||||
type PythonError struct{ Detail string }
|
||||
|
||||
func (e *PythonError) Error() string { return e.Detail }
|
||||
|
||||
// CallPython POSTs body as JSON to baseURL+path and decodes a 200 reply into
|
||||
// T. baseURL is the service's address on the Docker network with no trailing
|
||||
// slash (handlers.Store.PythonURL); path is the route, starting with a slash.
|
||||
//
|
||||
// Any non-200 is an error. See PythonError for which ones are relayable. A
|
||||
// cancelled ctx is wrapped, not replaced, so errors.Is(err, context.Canceled)
|
||||
// still holds — the email pipeline relies on that to tell an abandoned sync
|
||||
// from a failed email.
|
||||
func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T, error) {
|
||||
var out T
|
||||
|
||||
// Note for callers sending bytes: encoding/json writes a []byte as
|
||||
// standard base64, which is the form the Anthropic API wants and so what
|
||||
// the Python side passes straight through.
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("encoding request for %s: %w", path, err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+path, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := pythonClient.Do(req)
|
||||
if err != nil {
|
||||
return out, fmt.Errorf("calling %s: %w", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// FastAPI errors are {"detail": ...}. Only a 502 carries one of the
|
||||
// route's own fixed messages; a 422's detail is a list, which fails
|
||||
// to decode into the string and falls through to the generic error,
|
||||
// and a 503's detail names an environment variable, which is for the
|
||||
// log rather than the page. The body is capped because it is only
|
||||
// ever quoted in a log line.
|
||||
var failure struct {
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
||||
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
|
||||
return out, &PythonError{Detail: failure.Detail}
|
||||
}
|
||||
return out, fmt.Errorf("%s returned %d: %s", path, resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
// A fresh zero value, so a half-decoded T never escapes with an error.
|
||||
var zero T
|
||||
return zero, fmt.Errorf("decoding %s response: %w", path, err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// CallPython is the one path from this backend to the Python service's
|
||||
// internal routes, so its contract is tested here once rather than per
|
||||
// caller: what the request looks like, and which replies come back as a
|
||||
// relayable *PythonError, which as a plain error.
|
||||
|
||||
type pythonReply struct {
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
Note *string `json:"note"`
|
||||
}
|
||||
|
||||
func pythonStub(t *testing.T, handler http.HandlerFunc) string {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv.URL
|
||||
}
|
||||
|
||||
func TestCallPythonRequestAndReply(t *testing.T) {
|
||||
var (
|
||||
method, path, contentType string
|
||||
forwarded bool
|
||||
got map[string]any
|
||||
)
|
||||
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
method, path, contentType = r.Method, r.URL.Path, r.Header.Get("Content-Type")
|
||||
// The Python routes treat either header as "came through nginx" and
|
||||
// answer 404, so the helper must never send them.
|
||||
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"name": "x", "count": 3, "note": null}`))
|
||||
})
|
||||
|
||||
reply, err := CallPython[pythonReply](context.Background(), url, "/internal/thing", struct {
|
||||
Text string `json:"text"`
|
||||
Data []byte `json:"data"`
|
||||
}{"hello", []byte("hello")})
|
||||
if err != nil {
|
||||
t.Fatalf("CallPython: %v", err)
|
||||
}
|
||||
if reply.Name != "x" || reply.Count != 3 || reply.Note != nil {
|
||||
t.Fatalf("reply = %+v", reply)
|
||||
}
|
||||
if method != http.MethodPost || path != "/internal/thing" || contentType != "application/json" {
|
||||
t.Fatalf("request was %s %s (%s)", method, path, contentType)
|
||||
}
|
||||
if forwarded {
|
||||
t.Fatal("request carried a proxy header the Python routes reject")
|
||||
}
|
||||
// A []byte travels as standard base64, which is what the rowing reader
|
||||
// relies on for the image.
|
||||
if got["text"] != "hello" || got["data"] != "aGVsbG8=" {
|
||||
t.Fatalf("request body = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPythonErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a *PythonError with this message
|
||||
}{
|
||||
{"a 502's string detail is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
|
||||
{"a 502 with an empty detail is not", http.StatusBadGateway, `{"detail": ""}`, ""},
|
||||
{"a 502 that is not JSON is not", http.StatusBadGateway, `<html>bad gateway</html>`, ""},
|
||||
// A 422's detail is a list of validation errors, not a message.
|
||||
{"a validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
// Its detail is a string, but it names an environment variable: for
|
||||
// the log, not for the page.
|
||||
{"a missing API key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"a 404 is not relayed", http.StatusNotFound, `{"detail": "Not Found"}`, ""},
|
||||
{"a malformed success body is an error", http.StatusOK, `not json`, ""},
|
||||
{"a success body of the wrong shape is an error", http.StatusOK, `{"count": "three"}`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
url := pythonStub(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
|
||||
reply, err := CallPython[pythonReply](context.Background(), url, "/internal/thing", struct{}{})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
if reply != (pythonReply{}) {
|
||||
t.Fatalf("reply = %+v alongside an error, want the zero value", reply)
|
||||
}
|
||||
var pyErr *PythonError
|
||||
if relayed := errors.As(err, &pyErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if pyErr != nil && (pyErr.Detail != c.wantDetail || pyErr.Error() != c.wantDetail) {
|
||||
t.Fatalf("detail = %q, want %q", pyErr.Detail, c.wantDetail)
|
||||
}
|
||||
// A plumbing error names the route, so the log line says which
|
||||
// of the three calls it was.
|
||||
if pyErr == nil && !strings.Contains(err.Error(), "/internal/thing") {
|
||||
t.Fatalf("err = %v, want it to name the route", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPythonUnreachable(t *testing.T) {
|
||||
url := pythonStub(t, func(http.ResponseWriter, *http.Request) {})
|
||||
// Port 1 on localhost: nothing listens there.
|
||||
_, err := CallPython[pythonReply](context.Background(), "http://127.0.0.1:1", "/internal/thing", struct{}{})
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var pyErr *PythonError
|
||||
if errors.As(err, &pyErr) {
|
||||
t.Fatalf("a transport failure was reported as relayable: %v", err)
|
||||
}
|
||||
|
||||
// A cancelled call must still read as context.Canceled: the email
|
||||
// pipeline uses that to avoid counting an abandoned sync as a failure.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := CallPython[pythonReply](ctx, url, "/internal/thing", struct{}{}); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("err = %v, want it to wrap context.Canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallPythonUnencodableBody(t *testing.T) {
|
||||
// Channels cannot be marshalled; the point is that this fails before any
|
||||
// request is made, so the URL is never dialled.
|
||||
if _, err := CallPython[pythonReply](context.Background(), "http://127.0.0.1:1", "/internal/thing", make(chan int)); err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,6 @@ import (
|
||||
// - FetchLatestFeed: it is an HTTP call to the Gitea container. Its only
|
||||
// logic beyond the request is the empty-feed nil,nil case, and testing it
|
||||
// would mean either a network or an injected client that does not exist.
|
||||
// - claude.go: InitClaude is a single SDK constructor with no validation and
|
||||
// no prompt building; there is nothing to assert that is not the SDK's.
|
||||
// - The 1-minute Gitea cache TTL: it lives in handlers.Store, not here.
|
||||
// - RateLimiter's window expiry uses the real clock (Allow calls time.Now
|
||||
// directly and there is no injectable clock), so the expiry case below
|
||||
|
||||
Reference in New Issue
Block a user