|
| 1 | +package httptool |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "io" |
| 10 | + "net/http" |
| 11 | + "strings" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/LAA-Software-Engineering/agentic-control-plane/internal/models" |
| 15 | + "github.com/LAA-Software-Engineering/agentic-control-plane/internal/spec" |
| 16 | +) |
| 17 | + |
| 18 | +// ExecMeta is timing/cost metadata for an HTTP tool call (§13.2 placeholders). |
| 19 | +type ExecMeta struct { |
| 20 | + DurationMs int64 |
| 21 | + CostUSD float64 |
| 22 | +} |
| 23 | + |
| 24 | +// clientError is a 4xx response (not retried). |
| 25 | +type clientError struct { |
| 26 | + code int |
| 27 | + msg string |
| 28 | +} |
| 29 | + |
| 30 | +func (e *clientError) Error() string { |
| 31 | + return fmt.Sprintf("httptool: HTTP %d %s", e.code, e.msg) |
| 32 | +} |
| 33 | + |
| 34 | +// serverHTTPError is a 5xx response (retried when policy allows). |
| 35 | +type serverHTTPError struct { |
| 36 | + code int |
| 37 | + body string |
| 38 | +} |
| 39 | + |
| 40 | +func (e *serverHTTPError) Error() string { |
| 41 | + return fmt.Sprintf("httptool: HTTP %d", e.code) |
| 42 | +} |
| 43 | + |
| 44 | +// Execute performs one logical HTTP tool call, including optional retries on transport/5xx errors. |
| 45 | +// client may be nil to use http.DefaultClient (tests should pass srv.Client()). |
| 46 | +func Execute(ctx context.Context, cfg *spec.ToolHTTP, retry *spec.ToolRetry, operation string, with map[string]any, client *http.Client) (map[string]any, ExecMeta, error) { |
| 47 | + if cfg == nil { |
| 48 | + return nil, ExecMeta{}, errors.New("httptool: nil http config") |
| 49 | + } |
| 50 | + base := strings.TrimSpace(cfg.BaseURL) |
| 51 | + if base == "" { |
| 52 | + return nil, ExecMeta{}, errors.New("httptool: empty baseUrl") |
| 53 | + } |
| 54 | + method, path, err := parseOperation(operation) |
| 55 | + if err != nil { |
| 56 | + return nil, ExecMeta{}, err |
| 57 | + } |
| 58 | + urlStr := joinURL(base, path) |
| 59 | + |
| 60 | + attempts := 1 |
| 61 | + if retry != nil && retry.MaxAttempts > 0 { |
| 62 | + attempts = retry.MaxAttempts |
| 63 | + } |
| 64 | + backoff := "" |
| 65 | + if retry != nil { |
| 66 | + backoff = retry.Backoff |
| 67 | + } |
| 68 | + if client == nil { |
| 69 | + client = http.DefaultClient |
| 70 | + } |
| 71 | + |
| 72 | + start := time.Now() |
| 73 | + var lastErr error |
| 74 | + for attempt := 0; attempt < attempts; attempt++ { |
| 75 | + if attempt > 0 { |
| 76 | + sleepBackoff(ctx, attempt, backoff) |
| 77 | + } |
| 78 | + out, err := doRequest(ctx, client, method, urlStr, cfg.Headers, with) |
| 79 | + if err == nil { |
| 80 | + return out, ExecMeta{DurationMs: time.Since(start).Milliseconds(), CostUSD: 0}, nil |
| 81 | + } |
| 82 | + lastErr = err |
| 83 | + if !retryableHTTP(err) { |
| 84 | + break |
| 85 | + } |
| 86 | + } |
| 87 | + return nil, ExecMeta{DurationMs: time.Since(start).Milliseconds(), CostUSD: 0}, lastErr |
| 88 | +} |
| 89 | + |
| 90 | +func parseOperation(operation string) (method, path string, err error) { |
| 91 | + operation = strings.TrimSpace(operation) |
| 92 | + if operation == "" { |
| 93 | + return "", "", fmt.Errorf("httptool: empty operation") |
| 94 | + } |
| 95 | + parts := strings.Split(operation, ".") |
| 96 | + verbs := map[string]string{ |
| 97 | + "get": "GET", "post": "POST", "put": "PUT", "delete": "DELETE", "patch": "PATCH", |
| 98 | + } |
| 99 | + if m, ok := verbs[strings.ToLower(parts[0])]; ok { |
| 100 | + if len(parts) == 1 { |
| 101 | + return m, "/", nil |
| 102 | + } |
| 103 | + return m, "/" + strings.Join(parts[1:], "/"), nil |
| 104 | + } |
| 105 | + return "GET", "/" + strings.Join(parts, "/"), nil |
| 106 | +} |
| 107 | + |
| 108 | +func joinURL(base, path string) string { |
| 109 | + base = strings.TrimRight(strings.TrimSpace(base), "/") |
| 110 | + if path == "" { |
| 111 | + return base + "/" |
| 112 | + } |
| 113 | + if !strings.HasPrefix(path, "/") { |
| 114 | + path = "/" + path |
| 115 | + } |
| 116 | + return base + path |
| 117 | +} |
| 118 | + |
| 119 | +func resolveHeaders(h map[string]string) (http.Header, error) { |
| 120 | + hdr := make(http.Header) |
| 121 | + if h == nil { |
| 122 | + return hdr, nil |
| 123 | + } |
| 124 | + for k, v := range h { |
| 125 | + resolved, err := resolveHeaderValue(v) |
| 126 | + if err != nil { |
| 127 | + return nil, fmt.Errorf("httptool: header %q: %w", k, err) |
| 128 | + } |
| 129 | + hdr.Set(k, resolved) |
| 130 | + } |
| 131 | + return hdr, nil |
| 132 | +} |
| 133 | + |
| 134 | +func resolveHeaderValue(v string) (string, error) { |
| 135 | + v = strings.TrimSpace(v) |
| 136 | + if strings.HasPrefix(v, "env:") { |
| 137 | + return models.ResolveAPIKeyFrom(v) |
| 138 | + } |
| 139 | + return v, nil |
| 140 | +} |
| 141 | + |
| 142 | +func doRequest(ctx context.Context, cli *http.Client, method, urlStr string, headers map[string]string, with map[string]any) (map[string]any, error) { |
| 143 | + hdr, err := resolveHeaders(headers) |
| 144 | + if err != nil { |
| 145 | + return nil, err |
| 146 | + } |
| 147 | + |
| 148 | + var body io.Reader |
| 149 | + switch method { |
| 150 | + case "POST", "PUT", "PATCH": |
| 151 | + if with == nil { |
| 152 | + with = map[string]any{} |
| 153 | + } |
| 154 | + b, err := json.Marshal(with) |
| 155 | + if err != nil { |
| 156 | + return nil, err |
| 157 | + } |
| 158 | + body = bytes.NewReader(b) |
| 159 | + if hdr.Get("Content-Type") == "" { |
| 160 | + hdr.Set("Content-Type", "application/json") |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + req, err := http.NewRequestWithContext(ctx, method, urlStr, body) |
| 165 | + if err != nil { |
| 166 | + return nil, err |
| 167 | + } |
| 168 | + req.Header = hdr |
| 169 | + |
| 170 | + resp, err := cli.Do(req) |
| 171 | + if err != nil { |
| 172 | + return nil, err |
| 173 | + } |
| 174 | + defer resp.Body.Close() |
| 175 | + |
| 176 | + b, err := io.ReadAll(resp.Body) |
| 177 | + if err != nil { |
| 178 | + return nil, err |
| 179 | + } |
| 180 | + |
| 181 | + if resp.StatusCode >= 500 { |
| 182 | + return nil, &serverHTTPError{code: resp.StatusCode, body: string(b)} |
| 183 | + } |
| 184 | + if resp.StatusCode >= 400 { |
| 185 | + return nil, &clientError{code: resp.StatusCode, msg: truncateBody(b, 512)} |
| 186 | + } |
| 187 | + |
| 188 | + return decodeResponseBody(b, resp.Header.Get("Content-Type")) |
| 189 | +} |
| 190 | + |
| 191 | +func decodeResponseBody(b []byte, contentType string) (map[string]any, error) { |
| 192 | + ct := strings.ToLower(contentType) |
| 193 | + if len(b) == 0 { |
| 194 | + return map[string]any{}, nil |
| 195 | + } |
| 196 | + if strings.Contains(ct, "application/json") || b[0] == '{' || b[0] == '[' { |
| 197 | + var obj map[string]any |
| 198 | + if json.Unmarshal(b, &obj) == nil { |
| 199 | + return obj, nil |
| 200 | + } |
| 201 | + var arr []any |
| 202 | + if json.Unmarshal(b, &arr) == nil { |
| 203 | + return map[string]any{"items": arr}, nil |
| 204 | + } |
| 205 | + } |
| 206 | + return map[string]any{"body": string(b)}, nil |
| 207 | +} |
| 208 | + |
| 209 | +func truncateBody(b []byte, n int) string { |
| 210 | + s := string(b) |
| 211 | + if len(s) <= n { |
| 212 | + return s |
| 213 | + } |
| 214 | + return s[:n] + "..." |
| 215 | +} |
| 216 | + |
| 217 | +func retryableHTTP(err error) bool { |
| 218 | + if err == nil { |
| 219 | + return false |
| 220 | + } |
| 221 | + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| 222 | + return false |
| 223 | + } |
| 224 | + var ce *clientError |
| 225 | + if errors.As(err, &ce) { |
| 226 | + return false |
| 227 | + } |
| 228 | + var se *serverHTTPError |
| 229 | + if errors.As(err, &se) { |
| 230 | + return true |
| 231 | + } |
| 232 | + return true |
| 233 | +} |
| 234 | + |
| 235 | +func sleepBackoff(ctx context.Context, attempt int, kind string) { |
| 236 | + if attempt <= 0 { |
| 237 | + return |
| 238 | + } |
| 239 | + var d time.Duration |
| 240 | + switch strings.ToLower(strings.TrimSpace(kind)) { |
| 241 | + case "exponential": |
| 242 | + shift := attempt |
| 243 | + if shift > 8 { |
| 244 | + shift = 8 |
| 245 | + } |
| 246 | + d = time.Millisecond * time.Duration(50*(1<<shift)) |
| 247 | + case "fixed": |
| 248 | + d = 100 * time.Millisecond |
| 249 | + default: |
| 250 | + d = 50 * time.Millisecond |
| 251 | + } |
| 252 | + select { |
| 253 | + case <-ctx.Done(): |
| 254 | + case <-time.After(d): |
| 255 | + } |
| 256 | +} |
0 commit comments