-
-
Notifications
You must be signed in to change notification settings - Fork 680
Expand file tree
/
Copy pathHttpTransporter.php
More file actions
185 lines (148 loc) · 5.85 KB
/
HttpTransporter.php
File metadata and controls
185 lines (148 loc) · 5.85 KB
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
<?php
declare(strict_types=1);
namespace OpenAI\Transporters;
use Closure;
use GuzzleHttp\Exception\ClientException;
use JsonException;
use OpenAI\Contracts\TransporterContract;
use OpenAI\Enums\Transporter\ContentType;
use OpenAI\Exceptions\ErrorException;
use OpenAI\Exceptions\RateLimitException;
use OpenAI\Exceptions\TransporterException;
use OpenAI\Exceptions\UnserializableResponse;
use OpenAI\ValueObjects\Transporter\AdaptableResponse;
use OpenAI\ValueObjects\Transporter\BaseUri;
use OpenAI\ValueObjects\Transporter\Headers;
use OpenAI\ValueObjects\Transporter\Payload;
use OpenAI\ValueObjects\Transporter\QueryParams;
use OpenAI\ValueObjects\Transporter\Response;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
/**
* @internal
*/
final class HttpTransporter implements TransporterContract
{
/**
* Creates a new Http Transporter instance.
*/
public function __construct(
private readonly ClientInterface $client,
private readonly BaseUri $baseUri,
private Headers $headers,
private readonly QueryParams $queryParams,
private readonly Closure $streamHandler,
) {
// ..
}
/**
* {@inheritDoc}
*/
public function addHeader(string $name, string $value): self
{
$this->headers = $this->headers->withCustomHeader($name, $value);
return $this;
}
/**
* {@inheritDoc}
*/
public function requestObject(Payload $payload): Response
{
$request = $payload->toRequest($this->baseUri, $this->headers, $this->queryParams);
$response = $this->sendRequest(fn (): \Psr\Http\Message\ResponseInterface => $this->client->sendRequest($request));
$contents = (string) $response->getBody();
$this->throwIfRateLimit($response);
$this->throwIfJsonError($response, $contents);
try {
/** @var array{error?: array{message: string, type: string, code: string}} $data */
$data = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $jsonException) {
throw new UnserializableResponse($jsonException, $response);
}
return Response::from($data, $response->getHeaders());
}
/**
* {@inheritDoc}
*/
public function requestStringOrObject(Payload $payload): AdaptableResponse
{
$request = $payload->toRequest($this->baseUri, $this->headers, $this->queryParams);
$response = $this->sendRequest(fn (): \Psr\Http\Message\ResponseInterface => $this->client->sendRequest($request));
$contents = (string) $response->getBody();
if (str_contains($response->getHeaderLine('Content-Type'), ContentType::TEXT_PLAIN->value)) {
return AdaptableResponse::from($contents, $response->getHeaders());
}
$this->throwIfRateLimit($response);
$this->throwIfJsonError($response, $contents);
try {
/** @var array{error?: array{message: string, type: string, code: string}} $data */
$data = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $jsonException) {
throw new UnserializableResponse($jsonException, $response);
}
return AdaptableResponse::from($data, $response->getHeaders());
}
/**
* {@inheritDoc}
*/
public function requestContent(Payload $payload): string
{
$request = $payload->toRequest($this->baseUri, $this->headers, $this->queryParams);
$response = $this->sendRequest(fn (): \Psr\Http\Message\ResponseInterface => $this->client->sendRequest($request));
$contents = (string) $response->getBody();
$this->throwIfRateLimit($response);
$this->throwIfJsonError($response, $contents);
return $contents;
}
/**
* {@inheritDoc}
*/
public function requestStream(Payload $payload): ResponseInterface
{
$request = $payload->toRequest($this->baseUri, $this->headers, $this->queryParams);
$response = $this->sendRequest(fn () => ($this->streamHandler)($request));
$this->throwIfRateLimit($response);
$this->throwIfJsonError($response, $response);
return $response;
}
private function sendRequest(Closure $callable): ResponseInterface
{
try {
return $callable();
} catch (ClientExceptionInterface $clientException) {
if ($clientException instanceof ClientException) {
$this->throwIfJsonError($clientException->getResponse(), (string) $clientException->getResponse()->getBody());
}
throw new TransporterException($clientException);
}
}
private function throwIfRateLimit(ResponseInterface $response): void
{
if ($response->getStatusCode() !== 429) {
return;
}
throw new RateLimitException($response);
}
private function throwIfJsonError(ResponseInterface $response, string|ResponseInterface $contents): void
{
if ($response->getStatusCode() < 400) {
return;
}
if (! str_contains($response->getHeaderLine('Content-Type'), ContentType::JSON->value)) {
return;
}
if ($contents instanceof ResponseInterface) {
$contents = (string) $contents->getBody();
}
try {
/** @var array{error?: string|array{message: string|array<int, string>, type: string, code: string}} $data */
$data = json_decode($contents, true, flags: JSON_THROW_ON_ERROR);
if (isset($data['error']) || isset($data[0]['error'])) {
throw new ErrorException($data['error'] ?? $data[0]['error'], $response);
}
} catch (JsonException $jsonException) {
throw new UnserializableResponse($jsonException, $response);
}
}
}