Trim comments to the non-obvious why
Test and deploy / test (push) Successful in 28s
Test and deploy / deploy (push) Successful in 31s

Drop narration, history and restated-code comments across the repo,
keep short ones for security boundaries, upstream quirks and ordering
constraints, and record the convention in CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 20:49:03 +00:00
co-authored by Claude Opus 5.5
parent effddd2794
commit 4530cb8dc4
222 changed files with 1173 additions and 5423 deletions
+22 -68
View File
@@ -15,51 +15,30 @@ import (
"gorm.io/gorm"
)
// Rowing log. The interesting endpoint is CreateRowing: rather than a form,
// 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.
// CreateRowing reads a photo of the rowing machine display. The Claude call
// is in python/app/rowing.py; auth, EXIF, dedup and bounds checks stay here.
// ExtractedRowingData is the JSON contract for what Claude reads off the
// 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).
// ExtractedRowingData matches 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: Caddy refuses
// /py/internal/ and the route itself refuses anything Caddy forwarded, so the
// only way in is the direct container-to-container call services.CallPython
// makes.
// Internal: Caddy refuses /py/internal/, so only a direct container call works.
const rowingReadPath = "/internal/rowing/read"
// 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. 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) {
// Data is a []byte so that it is sent as standard base64, the encoding
// the Anthropic API expects.
// []byte marshals as standard base64, as the Anthropic API expects.
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
MediaType string `json:"media_type"`
Data []byte `json:"data"`
}{mediaType, image})
}
// GetRowing backs the public GET /rowing with every logged session, newest
// first.
func (store *Store) GetRowing(ctx *gin.Context) {
var rowing []models.Rowing
// "Created_At" works because Postgres folds unquoted identifiers to lower
// case; the column is created_at.
if err := store.DB.Order("Created_At DESC").Find(&rowing).Error; err != nil {
if err := store.DB.Order("created_at DESC").Find(&rowing).Error; err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
@@ -67,13 +46,8 @@ func (store *Store) GetRowing(ctx *gin.Context) {
ctx.JSON(http.StatusOK, rowing)
}
// 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 (via the Python service), sanity-checks the result and stores a
// session.
//
// 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.
// CreateRowing is admin-only, so its checks target misreadings, not hostile
// input.
func (store *Store) CreateRowing(ctx *gin.Context) {
file, err := ctx.FormFile("image")
if err != nil {
@@ -88,9 +62,7 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
}
defer f.Close()
// EXIF is required, not optional: it is both the session date and the
// duplicate key, so a stripped-metadata image (anything that has been
// through most messaging apps) is rejected outright.
// EXIF is required: it is both the session date and the duplicate key.
exifData, err := exif.Decode(f)
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "no EXIF data found"})
@@ -103,19 +75,14 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
return
}
// exif.Decode consumed part of the stream, so rewind before reading the
// 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, 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 {
// Bounded before buffering, to cap memory and the paid API call.
const maxPhotoSize = 10 << 20
if file.Size > maxPhotoSize {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "image too large (max 10MB)"})
return
}
@@ -132,24 +99,16 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
"image/gif": true,
"image/webp": true,
}
// 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. The
// Python service enforces the same list; checking here first gives the
// admin a clear 400 instead of that side's validation error.
// The browser's claimed type, checked only to keep the API call
// well-formed and give a clear 400.
mediaType := file.Header.Get("Content-Type")
if !allowedMediaTypes[mediaType] {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported image type"})
return
}
// 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
// nothing.
//
// Fails closed: only gorm.ErrRecordNotFound means "no duplicate". Any
// other error is a real database problem, and treating it as "not found"
// would both insert a duplicate and spend a paid Claude call to do it.
// Checked before the paid call. Fails closed: only ErrRecordNotFound
// means "no duplicate".
var existing models.Rowing
err = store.DB.Where("date = ?", dateTaken).First(&existing).Error
switch {
@@ -165,9 +124,7 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
extractedData, err := store.readRowingDisplay(ctx.Request.Context(), mediaType, data)
if err != nil {
log.Println(err)
// 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.
// Pass on the reader's own messages; hide plumbing failures.
msg := "failed to process image"
var readErr *services.PythonError
if errors.As(err, &readErr) {
@@ -184,10 +141,8 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
totalSeconds := extractedData.TimeMinutes*60 + extractedData.TimeSeconds
// Sanity bounds on what Claude claims to have read. A misread digit
// typically lands far outside human rowing performance, and the pace
// check catches the case where time and distance are individually
// plausible but inconsistent with each other.
// A misread digit usually lands outside human performance; the pace check
// catches plausible time and distance that disagree.
const (
minDistance = 100 // metres
maxDistance = 100000 // metres
@@ -211,10 +166,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
return
}
// Rough calorie estimate from distance alone: roughly 500 kcal per
// 7500 m. Not from the machine and not physiologically derived — it is a
// display figure only.
calories := float64(extractedData.Distance) / 7500.0 * 500.0
// A display-only estimate, ~500 kcal per 7500 m.
const kcalPerMetre = 500.0 / 7500.0
calories := float64(extractedData.Distance) * kcalPerMetre
rowing := models.Rowing{
Date: dateTaken,