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]>
68 lines
2.0 KiB
Go
68 lines
2.0 KiB
Go
package services
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// CallPython is how the backend reaches the Python service's /internal/
|
|
// routes, container to container (Caddy refuses them, and they refuse
|
|
// proxied requests).
|
|
|
|
// Above Python's own worst case (30s Claude timeout, two retries), so a slow
|
|
// Claude surfaces as Python's error.
|
|
var pythonClient = &http.Client{Timeout: 2 * time.Minute}
|
|
|
|
// PythonError is the `detail` of a 502: one of the route's fixed messages,
|
|
// safe to show a user. Every other failure is a plain error, for the log only.
|
|
type PythonError struct{ Detail string }
|
|
|
|
func (e *PythonError) Error() string { return e.Detail }
|
|
|
|
// CallPython POSTs body as JSON and decodes a 200 into T; anything else is an
|
|
// error. baseURL has no trailing slash.
|
|
func CallPython[T any](ctx context.Context, baseURL, path string, body any) (T, error) {
|
|
var out T
|
|
|
|
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 {
|
|
// Only a 502's detail is user-facing: a 422's is a list (fails to
|
|
// decode) and a 503's names an env var.
|
|
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 {
|
|
var zero T
|
|
return zero, fmt.Errorf("decoding %s response: %w", path, err)
|
|
}
|
|
return out, nil
|
|
}
|