package runner import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strings" "time" ) // Client is the site's side: it posts to the runner service at BaseURL. type Client struct { BaseURL string HTTP *http.Client } // NewClient talks to the runner at baseURL (RUNNER_URL). The timeout is // above the service's own per-request deadline, so a slow run comes back as // the service's answer rather than a client timeout. func NewClient(baseURL string) *Client { return &Client{ BaseURL: strings.TrimRight(baseURL, "/"), HTTP: &http.Client{Timeout: 90 * time.Second}, } } // Run compiles req.Source once and runs it on every test. func (c *Client) Run(ctx context.Context, req RunRequest) (RunResponse, error) { var out RunResponse err := c.post(ctx, "/run", req, &out) return out, err } // Lint returns the source's diagnostics. func (c *Client) Lint(ctx context.Context, req LintRequest) (LintResponse, error) { var out LintResponse err := c.post(ctx, "/lint", req, &out) return out, err } func (c *Client) post(ctx context.Context, path string, in, out any) error { body, err := json.Marshal(in) if err != nil { return err } req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+path, bytes.NewReader(body)) if err != nil { return err } req.Header.Set("Content-Type", "application/json") resp, err := c.HTTP.Do(req) if err != nil { return fmt.Errorf("runner: %w", err) } defer resp.Body.Close() data, err := io.ReadAll(io.LimitReader(resp.Body, 16<<20)) if err != nil { return fmt.Errorf("runner: %w", err) } if resp.StatusCode != http.StatusOK { // The service answers errors as {"error": "..."}, meant for the admin. var e struct { Error string `json:"error"` } if json.Unmarshal(data, &e) == nil && e.Error != "" { return fmt.Errorf("runner: %s", e.Error) } return fmt.Errorf("runner: %s", resp.Status) } return json.Unmarshal(data, out) }