File size: 8,345 Bytes
097eaf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
<?php

declare(strict_types=1);

namespace Firecrawl\Client;

use Firecrawl\Exceptions\AuthenticationException;
use Firecrawl\Exceptions\FirecrawlException;
use Firecrawl\Exceptions\RateLimitException;
use Firecrawl\Version;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\RequestOptions;

/**
 * @internal
 */
final class FirecrawlHttpClient
{
    private readonly ClientInterface $httpClient;
    private readonly string $baseUrl;

    public function __construct(
        private readonly string $apiKey,
        string $baseUrl,
        float $timeoutSeconds,
        private readonly int $maxRetries,
        private readonly float $backoffFactor,
        ?ClientInterface $httpClient = null,
    ) {
        $this->baseUrl = rtrim($baseUrl, '/');

        $this->httpClient = $httpClient ?? new GuzzleClient([
            RequestOptions::TIMEOUT => $timeoutSeconds,
            RequestOptions::CONNECT_TIMEOUT => min($timeoutSeconds, 30),
            RequestOptions::HTTP_ERRORS => false,
        ]);
    }

    /**
     * @param array<string, mixed>  $body
     * @param array<string, string> $extraHeaders
     * @return array<string, mixed>
     */
    public function post(string $path, array $body, array $extraHeaders = []): array
    {
        return $this->request('POST', $this->baseUrl . $path, $body, $extraHeaders);
    }

    /** @return array<string, mixed> */
    public function get(string $path): array
    {
        return $this->request('GET', $this->baseUrl . $path);
    }

    /** @return array<string, mixed> */
    public function getAbsolute(string $absoluteUrl): array
    {
        return $this->request('GET', $absoluteUrl);
    }

    /** @return array<string, mixed> */
    public function delete(string $path): array
    {
        return $this->request('DELETE', $this->baseUrl . $path);
    }

    /**
     * @param array<string, mixed> $body
     * @return array<string, mixed>
     */
    public function patch(string $path, array $body): array
    {
        return $this->request('PATCH', $this->baseUrl . $path, $body);
    }

    /**
     * Send a POST request with a multipart/form-data body.
     *
     * @param array<string, string> $fields
     * @return array<string, mixed>
     */
    public function postMultipart(
        string $path,
        array $fields,
        string $fileField,
        string $fileName,
        string $fileContent,
        ?string $fileContentType = null,
    ): array {
        $multipart = [];
        foreach ($fields as $name => $value) {
            $multipart[] = [
                'name' => $name,
                'contents' => $value,
            ];
        }

        $filePart = [
            'name' => $fileField,
            'contents' => $fileContent,
            'filename' => $fileName,
        ];
        if ($fileContentType !== null && $fileContentType !== '') {
            $filePart['headers'] = ['Content-Type' => $fileContentType];
        }
        $multipart[] = $filePart;

        return $this->request(
            'POST',
            $this->baseUrl . $path,
            body: [],
            extraHeaders: [],
            multipart: $multipart,
        );
    }

    public function getBaseUrl(): string
    {
        return $this->baseUrl;
    }

    /**
     * @param array<string, mixed>                  $body
     * @param array<string, string>                 $extraHeaders
     * @param list<array<string, mixed>>|null       $multipart
     * @return array<string, mixed>
     */
    private function request(
        string $method,
        string $url,
        array $body = [],
        array $extraHeaders = [],
        ?array $multipart = null,
    ): array {
        $defaultHeaders = [
            'Authorization' => 'Bearer ' . $this->apiKey,
            'Accept' => 'application/json',
            'User-Agent' => 'firecrawl-php/' . Version::SDK_VERSION,
        ];

        if ($multipart === null) {
            $defaultHeaders['Content-Type'] = 'application/json';
        }

        $headers = array_merge($defaultHeaders, $extraHeaders);

        $options = [
            RequestOptions::HEADERS => $headers,
            RequestOptions::HTTP_ERRORS => false,
        ];

        if ($multipart !== null) {
            $options[RequestOptions::MULTIPART] = $multipart;
        } elseif (($method === 'POST' || $method === 'PATCH') && $body !== []) {
            $options[RequestOptions::JSON] = $body;
        }

        $attempt = 0;

        while (true) {
            try {
                $response = $this->httpClient->request($method, $url, $options);
                $statusCode = $response->getStatusCode();
                $responseBody = (string) $response->getBody();

                if ($statusCode >= 200 && $statusCode < 300) {
                    if ($responseBody === '' || $responseBody === '{}') {
                        return [];
                    }
                    /** @var array<string, mixed> */
                    return json_decode($responseBody, true, 512, JSON_THROW_ON_ERROR);
                }

                $errorMessage = $this->extractErrorMessage($responseBody, $statusCode);
                $errorCode = $this->extractErrorCode($responseBody);

                // Non-retryable client errors
                if ($statusCode === 401) {
                    throw new AuthenticationException($errorMessage, $errorCode);
                }

                if ($statusCode === 429) {
                    throw new RateLimitException($errorMessage, $errorCode);
                }

                if ($statusCode >= 400 && $statusCode < 500 && $statusCode !== 408 && $statusCode !== 409) {
                    throw new FirecrawlException($errorMessage, $statusCode, $errorCode);
                }

                // Retryable errors: 408, 409, 502, 5xx
                if ($attempt < $this->maxRetries) {
                    $attempt++;
                    $this->sleepWithBackoff($attempt);
                    continue;
                }

                throw new FirecrawlException($errorMessage, $statusCode, $errorCode);
            } catch (FirecrawlException $e) {
                throw $e;
            } catch (ConnectException $e) {
                if ($attempt < $this->maxRetries) {
                    $attempt++;
                    $this->sleepWithBackoff($attempt);
                    continue;
                }
                throw new FirecrawlException('Connection failed: ' . $e->getMessage(), previous: $e);
            } catch (RequestException $e) {
                if ($attempt < $this->maxRetries) {
                    $attempt++;
                    $this->sleepWithBackoff($attempt);
                    continue;
                }
                throw new FirecrawlException('Request failed: ' . $e->getMessage(), previous: $e);
            } catch (\JsonException $e) {
                throw new FirecrawlException('Failed to parse API response: ' . $e->getMessage(), previous: $e);
            }
        }
    }

    private function extractErrorMessage(string $body, int $statusCode): string
    {
        try {
            /** @var array<string, mixed> $parsed */
            $parsed = json_decode($body, true, 512, JSON_THROW_ON_ERROR);

            if (isset($parsed['error']) && is_string($parsed['error'])) {
                return $parsed['error'];
            }

            if (isset($parsed['message']) && is_string($parsed['message'])) {
                return $parsed['message'];
            }
        } catch (\JsonException) {
            // ignore
        }

        return "HTTP {$statusCode} error";
    }

    private function extractErrorCode(string $body): ?string
    {
        try {
            /** @var array<string, mixed> $parsed */
            $parsed = json_decode($body, true, 512, JSON_THROW_ON_ERROR);

            if (isset($parsed['code'])) {
                return (string) $parsed['code'];
            }
        } catch (\JsonException) {
            // ignore
        }

        return null;
    }

    private function sleepWithBackoff(int $attempt): void
    {
        $delayMs = (int) ($this->backoffFactor * 1000 * pow(2, $attempt - 1));
        usleep($delayMs * 1000);
    }
}