feat: forward optional FastAPI control token

This commit is contained in:
Noel Sabia committed 2026-11-14 04:47:21 +01:00
1 parent 4b9c2da9f7
commit a88bfad1d4
5 files changed
+70 -23

No files matched your search

+17 -6
View File
@@ -25,20 +25,28 @@ const controlTimeout = 30 * time.Second
// Client talks to the FastAPI ML service.
type Client struct {
baseURL string
http *http.Client
control *http.Client
baseURL string
http *http.Client
control *http.Client
controlToken string
}
// New returns a client for baseURL (for example http://localhost:8000).
func New(baseURL string, timeout time.Duration) *Client {
return NewWithToken(baseURL, timeout, "")
}
// NewWithToken is New plus the Bearer token FastAPI's internal /train
// endpoints expect. An empty token sends no Authorization header.
func NewWithToken(baseURL string, timeout time.Duration, controlToken string) *Client {
if timeout <= 0 {
timeout = DefaultTimeout
}
return &Client{
baseURL: strings.TrimRight(baseURL, "/"),
http: &http.Client{Timeout: timeout},
control: &http.Client{Timeout: controlTimeout},
baseURL: strings.TrimRight(baseURL, "/"),
http: &http.Client{Timeout: timeout},
control: &http.Client{Timeout: controlTimeout},
controlToken: controlToken,
}
}
@@ -139,6 +147,9 @@ func (c *Client) controlRequest(ctx context.Context, method, path, contentType s
req.Header.Set("Content-Type", contentType)
}
req.Header.Set("Accept", "application/json")
if c.controlToken != "" {
req.Header.Set("Authorization", "Bearer "+c.controlToken)
}
resp, err := c.control.Do(req)
if err != nil {
+26
View File
@@ -160,6 +160,32 @@ func TestTrainForwardsBodyContentTypeAndStatus(t *testing.T) {
}
}
func TestControlRequestsForwardBearerToken(t *testing.T) {
var got []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = append(got, r.Header.Get("Authorization"))
w.Header().Set("Content-Type", "application/json")
if r.Method == http.MethodPost {
w.WriteHeader(http.StatusAccepted)
}
_, _ = w.Write([]byte(`{"job_id":"job-1","status":"queued"}`))
}))
defer srv.Close()
client := NewWithToken(srv.URL, time.Second, "token-123")
if _, _, err := client.Train(context.Background(), "application/json", strings.NewReader(`{"path":"/tmp/x.csv"}`)); err != nil {
t.Fatalf("Train: %v", err)
}
if _, _, err := client.TrainStatus(context.Background(), "job-1"); err != nil {
t.Fatalf("TrainStatus: %v", err)
}
for i, auth := range got {
if auth != "Bearer token-123" {
t.Errorf("request %d Authorization=%q, want Bearer token-123", i, auth)
}
}
}
func TestTrainStatusForwardsJobIDAndUpstreamError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {