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:
@@ -1,12 +1,8 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -20,7 +16,7 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Job capture: the three endpoints behind userscripts/job-capture.user.js,
|
||||
// Job capture: the three endpoints behind vue/public/job-capture.user.js,
|
||||
// which adds the posting open in the browser to the job tracker.
|
||||
//
|
||||
// These are REST, and token-authenticated, because the caller is a userscript
|
||||
@@ -51,10 +47,6 @@ const (
|
||||
maxPageRunes = 40_000
|
||||
)
|
||||
|
||||
// jobExtractClient bounds the wait on the Python service; see
|
||||
// rowingReadClient for why two minutes.
|
||||
var jobExtractClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
// CaptureTokenMiddleware guards the capture routes with the token generated
|
||||
// in the admin panel (services.CaptureToken), presented as
|
||||
// "Authorization: Bearer <token>".
|
||||
@@ -250,55 +242,16 @@ type ExtractedJobPosting struct {
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
// postingReadError is a failure the Python service reported in words that are
|
||||
// safe to show in the capture popup (its 502 detail); the job-capture
|
||||
// counterpart of displayReadError.
|
||||
type postingReadError struct{ detail string }
|
||||
|
||||
func (e *postingReadError) Error() string { return e.detail }
|
||||
|
||||
// extractJobPosting sends a page's text to the Python service and returns the
|
||||
// fields Claude picked out. It mirrors readRowingDisplay, including which
|
||||
// replies are relayed and which are only logged.
|
||||
// fields Claude picked out. Like readRowingDisplay it is a thin wrapper over
|
||||
// services.CallPython, which decides which replies are relayed (a
|
||||
// *services.PythonError) and which are only logged.
|
||||
func (store *Store) extractJobPosting(ctx context.Context, pageURL, title, text string) (ExtractedJobPosting, error) {
|
||||
var posting ExtractedJobPosting
|
||||
|
||||
body, err := json.Marshal(struct {
|
||||
return services.CallPython[ExtractedJobPosting](ctx, store.PythonURL, jobExtractPath, struct {
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}{pageURL, title, text})
|
||||
if err != nil {
|
||||
return posting, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+jobExtractPath, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return posting, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := jobExtractClient.Do(req)
|
||||
if err != nil {
|
||||
return posting, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var failure struct {
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
||||
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
|
||||
return posting, &postingReadError{detail: failure.Detail}
|
||||
}
|
||||
return posting, fmt.Errorf("job extractor returned %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&posting); err != nil {
|
||||
return posting, fmt.Errorf("decoding job extractor response: %w", err)
|
||||
}
|
||||
return posting, nil
|
||||
}
|
||||
|
||||
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
|
||||
@@ -344,9 +297,9 @@ func (store *Store) JobCaptureExtract(ctx *gin.Context) {
|
||||
truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes))
|
||||
if err != nil {
|
||||
log.Println("Job extract failed:", err)
|
||||
var readErr *postingReadError
|
||||
var readErr *services.PythonError
|
||||
if errors.As(err, &readErr) {
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.detail})
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.Detail})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": "failed to read the page"})
|
||||
|
||||
@@ -308,7 +308,7 @@ func TestExtractJobPostingErrors(t *testing.T) {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a postingReadError with this message
|
||||
wantDetail string // non-empty: a services.PythonError with this message
|
||||
}{
|
||||
{"extractor failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse the posting"}`, "failed to parse the posting"},
|
||||
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
@@ -325,12 +325,12 @@ func TestExtractJobPostingErrors(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var readErr *postingReadError
|
||||
var readErr *services.PythonError
|
||||
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if readErr != nil && readErr.detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.detail, c.wantDetail)
|
||||
if readErr != nil && readErr.Detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/rwcarlsen/goexif/exif"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -39,68 +36,21 @@ type ExtractedRowingData struct {
|
||||
|
||||
// rowingReadPath is the Python route. It is internal: nginx refuses
|
||||
// /py/internal/ and the route itself refuses anything nginx forwarded, so the
|
||||
// only way in is this direct container-to-container call.
|
||||
// only way in is the direct container-to-container call services.CallPython
|
||||
// makes.
|
||||
const rowingReadPath = "/internal/rowing/read"
|
||||
|
||||
// rowingReadClient 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.
|
||||
var rowingReadClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
// displayReadError is a failure the Python service reported in words that are
|
||||
// safe and useful to show the admin (its 502 detail), as opposed to a
|
||||
// transport or decoding failure, which is only logged.
|
||||
type displayReadError struct{ detail string }
|
||||
|
||||
func (e *displayReadError) Error() string { return e.detail }
|
||||
|
||||
// readRowingDisplay sends the image to the Python service and returns what
|
||||
// Claude read off it. No plausibility checking happens on either side of this
|
||||
// call; that is CreateRowing's job.
|
||||
// call; that is CreateRowing's job. A failure the reader described in its own
|
||||
// words comes back as a *services.PythonError (see services.CallPython).
|
||||
func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) {
|
||||
var extracted ExtractedRowingData
|
||||
|
||||
// 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.
|
||||
body, err := json.Marshal(struct {
|
||||
// Data is a []byte so that it is sent as standard base64, the encoding
|
||||
// the Anthropic API expects.
|
||||
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
|
||||
MediaType string `json:"media_type"`
|
||||
Data []byte `json:"data"`
|
||||
}{mediaType, image})
|
||||
if err != nil {
|
||||
return extracted, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+rowingReadPath, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return extracted, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := rowingReadClient.Do(req)
|
||||
if err != nil {
|
||||
return extracted, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// FastAPI errors are {"detail": ...}. Only a 502 carries one of the
|
||||
// reader'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.
|
||||
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 extracted, &displayReadError{detail: failure.Detail}
|
||||
}
|
||||
return extracted, fmt.Errorf("rowing reader returned %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&extracted); err != nil {
|
||||
return extracted, fmt.Errorf("decoding rowing reader response: %w", err)
|
||||
}
|
||||
return extracted, nil
|
||||
}
|
||||
|
||||
// GetRowing backs the public GET /rowing with every logged session, newest
|
||||
@@ -219,9 +169,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
// passed on; anything else is a plumbing failure the admin can do
|
||||
// nothing with.
|
||||
msg := "failed to process image"
|
||||
var readErr *displayReadError
|
||||
var readErr *services.PythonError
|
||||
if errors.As(err, &readErr) {
|
||||
msg = readErr.detail
|
||||
msg = readErr.Detail
|
||||
}
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": msg})
|
||||
return
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// readRowingDisplay is the Go half of the contract with the Python service's
|
||||
@@ -63,7 +65,7 @@ func TestReadRowingDisplayErrors(t *testing.T) {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a displayReadError with this message
|
||||
wantDetail string // non-empty: a services.PythonError with this message
|
||||
}{
|
||||
{"reader failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
|
||||
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
@@ -82,12 +84,12 @@ func TestReadRowingDisplayErrors(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var readErr *displayReadError
|
||||
var readErr *services.PythonError
|
||||
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if readErr != nil && readErr.detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.detail, c.wantDetail)
|
||||
if readErr != nil && readErr.Detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -35,8 +35,10 @@ type Store struct {
|
||||
EmailSync *services.EmailSyncService
|
||||
|
||||
// Base URL of the Python service on the Docker network, no trailing
|
||||
// slash. Used for the calls that bypass nginx: reading a rowing display
|
||||
// photo (handle_rowing.go) and a job posting (handle_job_capture.go).
|
||||
// slash. Used for the calls that bypass nginx, all through
|
||||
// services.CallPython: reading a rowing display photo (handle_rowing.go)
|
||||
// and a job posting (handle_job_capture.go). The email pipeline makes the
|
||||
// third such call and holds its own copy of this value.
|
||||
PythonURL string
|
||||
|
||||
// Bearer token for the browser capture routes (handle_job_capture.go),
|
||||
|
||||
Reference in New Issue
Block a user