Move the rowing photo Claude call to the Python service

POST /rowing in the Go backend no longer calls the Anthropic SDK. It keeps
the admin gate, EXIF date, duplicate check, sanity bounds and insert, and
sends the image to a new internal Python route, POST /internal/rowing/read,
which makes the Claude call and returns the three numbers it read.

The route spends a paid call and has no auth of its own, so nginx 404s
/py/internal/ and the route refuses anything carrying the proxy headers
nginx adds. The python container now receives CLAUDE_API_KEY.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-09 11:46:17 +01:00
co-authored by Claude Opus 5.5
parent 8d7606bbe8
commit f8d48ba9af
19 changed files with 661 additions and 92 deletions
+7 -5
View File
@@ -107,8 +107,9 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
recent mail (Microsoft Graph *or* a hand-rolled IMAP client), keyword-filter
it, ask Claude to extract structured data, create or advance a
`JobApplication`. Runs on a timer and can be triggered by an admin.
- **claude.go** — the shared Anthropic client, used by the email pipeline and
by the rowing photo reader.
- **claude.go** — the Anthropic client, used by the email pipeline. (The
rowing photo reader's Claude call lives in the Python service; `POST /rowing`
reaches it directly at `http://$PYTHON_HOST:$PYTHON_PORT/internal/rowing/read`.)
- **notes.go** — path-traversal-safe file lookup for the notes directory.
- **seed.go** — dev-only test data. Creates an admin with the password
`password`, so it must never run in production (`SEED_DB=true` is set only
@@ -150,8 +151,8 @@ generated struct rather than the model you expected.
are benign (at worst a duplicate upstream fetch), but do not add a field
there that would be unsafe to tear.
- **Claude output is parsed as JSON** after stripping a possible markdown code
fence — via the shared `services.StripMarkdownFence`, used by both
`handle_rowing.go` and `email_sync.go`.
fence — `services.StripMarkdownFence` in `email_sync.go`, with a port of it
in `python/app/rowing.py` for the rowing photo reader.
- **The email pipeline retries a failure up to `maxEmailAttempts` (3) times.**
A failed email is recorded with action `"error"` and an attempt counter;
while it has attempts left the next sync reprocesses it and updates the same
@@ -180,7 +181,8 @@ generated struct rather than the model you expected.
| `SEED_DB` | seed dev test data (never in production) |
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
| `CLAUDE_API_KEY` | Anthropic API |
| `CLAUDE_API_KEY` | Anthropic API (email pipeline; the python service reads it too) |
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the rowing photo reader (default `python:8000`) |
| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed |
| `STEAM_API_KEY` / `STEAM_ID` | Steam presence |
| `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) |
+97 -59
View File
@@ -1,19 +1,19 @@
package handlers
import (
"bytes"
"context"
"encoding/base64"
"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/anthropics/anthropic-sdk-go"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
@@ -22,15 +22,87 @@ import (
// the admin uploads a photo of the rowing machine display and Claude reads the
// numbers off it. The session date comes from the photo's EXIF metadata, which
// also doubles as the deduplication key.
//
// The Claude call itself lives in the Python service (python/app/rowing.py),
// reached directly over the Docker network. Everything that needs the session
// or the database — the admin gate, EXIF, the duplicate check, the sanity
// bounds, the insert — stays here.
// ExtractedRowingData is the JSON contract for what Claude reads off the
// display; the keys must match the prompt in CreateRowing.
// display: the body of the Python service's reply, whose keys are the ones
// its prompt asks the model for (RowingReading in python/app/rowing.py).
type ExtractedRowingData struct {
TimeMinutes uint64 `json:"timeMinutes"`
TimeSeconds uint64 `json:"timeSeconds"`
Distance uint64 `json:"distance"`
}
// 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.
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.
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 {
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
// first.
func (store *Store) GetRowing(ctx *gin.Context) {
@@ -47,9 +119,10 @@ func (store *Store) GetRowing(ctx *gin.Context) {
// CreateRowing backs the admin-only POST /rowing: it takes a photo of the
// rowing machine display, dates it from EXIF, has Claude read the time and
// distance, sanity-checks the result and stores a session.
// distance (via the Python service), sanity-checks the result and stores a
// session.
//
// Note it is admin-gated and calls a paid API once per request, so the
// Note it is admin-gated and costs a paid API call once per request, so the
// validation below exists to catch misreadings rather than hostile input.
func (store *Store) CreateRowing(ctx *gin.Context) {
file, err := ctx.FormFile("image")
@@ -81,16 +154,17 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
}
// exif.Decode consumed part of the stream, so rewind before reading the
// bytes to send to Claude.
// bytes to send on for reading.
if _, err := f.Seek(0, io.SeekStart); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to seek image"})
return
}
// Cap the upload before buffering it (and then base64-encoding it, 1.33x
// bigger): the route is admin-only but an unbounded read would still let
// a giant file exhaust the Pi's memory and produce a huge paid API call.
// 10MB is well above any photo this endpoint is meant to take.
// bigger, on its way to the Python service): the route is admin-only but
// an unbounded read would still let a giant file exhaust the Pi's memory
// and produce a huge paid API call. 10MB is well above any photo this
// endpoint is meant to take; the Python side's own limit is sized from it.
if file.Size > 10<<20 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"})
return
@@ -110,13 +184,14 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
}
// This is the browser's claimed type, not a sniffed one; it is passed
// straight through to the Anthropic API, so the allow-list is there to
// keep the API call well-formed rather than to police the file.
// keep the API call well-formed rather than to police the file. The
// Python service enforces the same list; checking here first gives the
// admin a clear 400 instead of that side's validation error.
mediaType := file.Header.Get("Content-Type")
if !allowedMediaTypes[mediaType] {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
return
}
encoded := base64.StdEncoding.EncodeToString(data)
// Duplicate guard: two photos of the same session share an EXIF capture
// time to the second. Checked before the Claude call so a re-upload costs
@@ -137,55 +212,18 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
return
}
// Build the message with an image + text prompt
message, err := store.ClaudeClient.Messages.New(context.Background(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeHaiku4_5,
MaxTokens: 256,
Messages: []anthropic.MessageParam{
{
Role: "user",
Content: []anthropic.ContentBlockParamUnion{
// Image block
anthropic.NewImageBlock(anthropic.Base64ImageSourceParam{
Type: "base64",
MediaType: anthropic.Base64ImageSourceMediaType(mediaType),
Data: encoded,
}),
// Text prompt requesting exactly 2 variables
anthropic.NewTextBlock(
`Look at this rowing machine display. Extract the total elapsed time and total distance.
Return ONLY a JSON object with these exact keys and numeric values:
- "timeMinutes": total minutes (e.g. 2:30 = 2)
- "timeSeconds": total seconds (e.g. 2:30 = 30)
- "distance": distance in meters as a number (e.g. 5000)
No text, no markdown, no explanation. Just the JSON object.`),
},
},
},
})
extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to process image"})
return
}
if len(message.Content) == 0 {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "empty response from image processor"})
return
}
// Strip a markdown code fence if the model wrapped its JSON in one
// despite the prompt; shared with the email pipeline, which asks for bare
// JSON in the same way and gets fenced output just as often.
extractedData := ExtractedRowingData{}
raw := services.StripMarkdownFence(message.Content[0].Text)
err = json.Unmarshal([]byte(raw), &extractedData)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse image data"})
// The reader's own messages ("failed to parse image data", ...) are
// passed on; anything else is a plumbing failure the admin can do
// nothing with.
msg := "failed to process image"
var readErr *displayReadError
if errors.As(err, &readErr) {
msg = readErr.detail
}
ctx.JSON(http.StatusInternalServerError, gin.H{"error": msg})
return
}
+94
View File
@@ -0,0 +1,94 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
// readRowingDisplay is the Go half of the contract with the Python service's
// /internal/rowing/read. CreateRowing itself needs a database and a real
// multipart photo with EXIF, so what is covered is the call: the request the
// Python side receives, and how each kind of reply comes back.
func rowingReader(t *testing.T, handler http.HandlerFunc) *Store {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
return &Store{PythonURL: srv.URL}
}
func TestReadRowingDisplayRequestAndReply(t *testing.T) {
var got struct {
MediaType string `json:"media_type"`
Data string `json:"data"`
}
var path string
var forwarded bool
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
// The Python route treats either header as "came through nginx" and
// answers 404, so this call must never carry 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(`{"timeMinutes": 20, "timeSeconds": 5, "distance": 5000}`))
})
data, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("hello"))
if err != nil {
t.Fatalf("readRowingDisplay: %v", err)
}
if data != (ExtractedRowingData{TimeMinutes: 20, TimeSeconds: 5, Distance: 5000}) {
t.Fatalf("got %+v", data)
}
if path != rowingReadPath {
t.Fatalf("path = %q, want %q", path, rowingReadPath)
}
if forwarded {
t.Fatal("request carried a proxy header the Python route rejects")
}
// "hello" in standard base64, the encoding the Anthropic API expects.
if got.MediaType != "image/jpeg" || got.Data != "aGVsbG8=" {
t.Fatalf("request body = %+v", got)
}
}
func TestReadRowingDisplayErrors(t *testing.T) {
cases := []struct {
name string
status int
body string
wantDetail string // non-empty: a displayReadError 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"}]}`, ""},
{"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
{"non-JSON 502 is not relayed", http.StatusBadGateway, `<html>bad gateway</html>`, ""},
{"malformed success body", http.StatusOK, `not json`, ""},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
store := rowingReader(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(c.status)
w.Write([]byte(c.body))
})
_, err := store.readRowingDisplay(context.Background(), "image/jpeg", []byte("x"))
if err == nil {
t.Fatal("expected an error")
}
var readErr *displayReadError
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)
}
})
}
}
+5 -2
View File
@@ -8,7 +8,6 @@ import (
"time"
"adam-french.co.uk/backend/services"
"github.com/anthropics/anthropic-sdk-go"
"github.com/zmb3/spotify/v2"
spotifyauth "github.com/zmb3/spotify/v2/auth"
"gorm.io/gorm"
@@ -30,12 +29,16 @@ type Store struct {
DB *gorm.DB
SpotifyAuth *spotifyauth.Authenticator
SpotifyClient *spotify.Client
ClaudeClient *anthropic.Client
Auth *services.Auth
Notes *services.Notes
LoginLimiter *services.RateLimiter
EmailSync *services.EmailSyncService
// Base URL of the Python service on the Docker network, no trailing
// slash. Used for the one call that bypasses nginx: reading a rowing
// display photo (see handle_rowing.go).
PythonURL string
// Cached "recently played" tracks, refreshed at most once a minute by the
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
// mean "never fetched" distinctly from "fetched, empty".
+17 -1
View File
@@ -90,6 +90,8 @@ func main() {
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
// CLAUDE
// Only the email pipeline uses this client now; the rowing photo reader's
// Claude call moved to the Python service, which reads the same key.
claudeAPIKey := os.Getenv("CLAUDE_API_KEY")
claudeConfig := services.ClaudeConfig{APIKey: claudeAPIKey}
claudeClient := services.InitClaude(&claudeConfig)
@@ -114,6 +116,20 @@ func main() {
steamAPIKey := os.Getenv("STEAM_API_KEY")
steamID := os.Getenv("STEAM_ID")
// PYTHON SERVICE
// Called directly over the Docker network, not through nginx, for the
// rowing photo reader. The defaults mirror docker-compose.yml, where both
// variables are optional.
pythonHost := os.Getenv("PYTHON_HOST")
if pythonHost == "" {
pythonHost = "python"
}
pythonPort := os.Getenv("PYTHON_PORT")
if pythonPort == "" {
pythonPort = "8000"
}
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
// EMAIL SYNC
// An unparseable EMAIL_SYNC_INTERVAL is silently ignored and the 30
// minute default stands — a typo here fails quietly.
@@ -144,7 +160,7 @@ func main() {
// and the GraphQL login mutation. Nginx rate-limits the login route too.
loginLimiter := services.NewRateLimiter(5, time.Minute)
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, ClaudeClient: claudeClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID}
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL}
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
// the Gin context, so the order in the admin group matters.
+5 -4
View File
@@ -10,15 +10,16 @@ type ClaudeConfig struct {
APIKey string
}
// InitClaude builds the shared Anthropic client. It is used in two places:
// reading a rowing machine display from a photo (handlers.CreateRowing) and
// classifying job-application emails (EmailSyncService.processEmail).
// 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
// to share one client across every caller.
// so it can be handed around without copying.
client := anthropic.NewClient(option.WithAPIKey(config.APIKey))
return &client
}
+2 -2
View File
@@ -888,8 +888,8 @@ If isJobEmail is false, only include that field. No text, no markdown, no explan
// a plain "```" otherwise. It is deliberately forgiving: unfenced input is
// returned unchanged apart from surrounding whitespace.
//
// Shared with handlers.CreateRowing, which prompts for bare JSON in the same
// way and gets the same fenced output.
// 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")