Repository navigation
Expand file tree
/
Copy pathClientBuilder.php
More file actions
358 lines (297 loc) · 10.1 KB
/
Copy pathClientBuilder.php
File metadata and controls
358 lines (297 loc) · 10.1 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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
<?php
declare(strict_types=1);
namespace GetStream;
use Dotenv\Dotenv;
use GetStream\Exceptions\StreamException;
use GetStream\Http\GuzzleHttpClient;
use GetStream\Http\HttpClientInterface;
use GetStream\Http\PoolConfig;
use GetStream\Http\RetryConfig;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Builder class for creating GetStream clients with environment variable support.
*/
class ClientBuilder
{
private string $apiKey;
private string $apiSecret;
private string $baseUrl = 'https://chat.stream-io-api.com';
private ?HttpClientInterface $httpClient = null;
private bool $loadEnv = true;
private ?string $envPath = null;
private PoolConfig $pool;
private ?LoggerInterface $logger = null;
private bool $logBodies = false;
private ?RetryConfig $retry = null;
public function __construct()
{
$this->pool = new PoolConfig();
}
/**
* Set the API key.
*/
public function apiKey(string $apiKey): self
{
$this->apiKey = $apiKey;
return $this;
}
/**
* Set the API secret.
*/
public function apiSecret(string $apiSecret): self
{
$this->apiSecret = $apiSecret;
return $this;
}
/**
* Set the base URL.
*/
public function baseUrl(string $baseUrl): self
{
$this->baseUrl = $baseUrl;
return $this;
}
/**
* Set the HTTP client.
*/
public function httpClient(HttpClientInterface $httpClient): self
{
$this->httpClient = $httpClient;
return $this;
}
/**
* Max concurrent connections per host. Default: 100. Ignored when httpClient() is used.
* Sets CURLMOPT_MAX_HOST_CONNECTIONS and CURLMOPT_MAXCONNECTS on the client's shared curl multi handle, so extra
* requests wait for a free connection. Takes effect only while the client is reused within one long-running process.
*/
public function maxConnsPerHost(int $n): self
{
$this->pool = $this->pool->withMaxConnsPerHost($n);
return $this;
}
/**
* Idle connection lifetime in seconds. Default: 55.
* No-op under PHP-FPM (curl handle dies with the request); honored in long-running runtimes.
* Ignored when httpClient() is used.
*/
public function idleTimeout(int $seconds): self
{
$this->pool = $this->pool->withIdleTimeout($seconds);
return $this;
}
/** TCP + TLS handshake cap in seconds (Guzzle `connect_timeout`). Default: 10. Ignored when httpClient() is used. */
public function connectTimeout(int $seconds): self
{
$this->pool = $this->pool->withConnectTimeout($seconds);
return $this;
}
/**
* Default per-request timeout in seconds (Guzzle `timeout`). Default: 30.
* Per-call override: pass `['timeout' => N]` as the 5th arg of HttpClientInterface::request().
* Ignored when httpClient() is used.
*/
public function requestTimeout(int $seconds): self
{
$this->pool = $this->pool->withRequestTimeout($seconds);
return $this;
}
/**
* Inject a PSR-3 logger for structured `client.initialized` / `http.request.*` /
* `http.response.*` events. Default when none is set: `Psr\Log\NullLogger` (no-op).
* The SDK never sets the logger's level; that is the caller's responsibility.
*/
public function logger(LoggerInterface $logger): self
{
$this->logger = $logger;
return $this;
}
/**
* Include (key-redacted) request/response bodies in the `http.request.sent` /
* `http.response.received` log events. Off by default. Enabling this emits one
* WARN at construction time.
*/
public function logBodies(bool $on): self
{
$this->logBodies = $on;
return $this;
}
/**
* Opt-in auto-retry policy (default: disabled, no retries; the client
* performs exactly one attempt and surfaces errors unchanged). When
* enabled, retries only GET/HEAD requests that fail with HTTP 429 or a
* transport error.
*/
public function retry(RetryConfig $retry): self
{
$this->retry = $retry;
return $this;
}
/**
* Disable loading from environment variables.
*/
public function skipEnvLoad(): self
{
$this->loadEnv = false;
return $this;
}
/**
* Set custom path for .env file (default is current directory).
*/
public function envPath(string $path): self
{
$this->envPath = $path;
return $this;
}
/**
* Create a client from environment variables.
*/
public static function fromEnv(?string $envPath = null): self
{
$builder = new self();
if ($envPath !== null) {
$builder->envPath($envPath);
}
return $builder;
}
/**
* Build the client.
*
* @throws StreamException
*/
public function build(): Client
{
$this->loadCreds();
return new Client($this->apiKey, $this->apiSecret, $this->baseUrl, $this->resolveHttpClient());
}
/**
* @throws StreamException
*/
public function buildFeedsClient(): FeedsV3Client
{
$this->loadCreds();
return new FeedsV3Client($this->apiKey, $this->apiSecret, $this->baseUrl, $this->resolveHttpClient());
}
/**
* @throws StreamException
*/
public function buildChatClient(): ChatClient
{
$this->loadCreds();
return new ChatClient($this->apiKey, $this->apiSecret, $this->baseUrl, $this->resolveHttpClient());
}
/**
* @throws StreamException
*/
public function buildVideoClient(): VideoClient
{
$this->loadCreds();
return new VideoClient($this->apiKey, $this->apiSecret, $this->baseUrl, $this->resolveHttpClient());
}
/**
* @throws StreamException
*/
public function buildModerationClient(): ModerationClient
{
$this->loadCreds();
return new ModerationClient($this->apiKey, $this->apiSecret, $this->baseUrl, $this->resolveHttpClient());
}
public function loadCreds(): void
{
// Load environment variables if enabled
if ($this->loadEnv) {
$this->loadEnvironmentVariables();
}
// Get credentials from environment if not set
$apiKey = $this->apiKey ?? $this->getEnvVar('STREAM_API_KEY');
$apiSecret = $this->apiSecret ?? $this->getEnvVar('STREAM_API_SECRET');
$baseUrl = $this->baseUrl;
// Override baseUrl with environment variable if not explicitly set and env var exists
if ($this->baseUrl === 'https://chat.stream-io-api.com') {
$envBaseUrl = $this->getEnvVar('STREAM_BASE_URL');
if ($envBaseUrl !== null) {
$baseUrl = $envBaseUrl;
}
}
if (empty($apiKey)) {
throw new StreamException(
'API key not provided. Set STREAM_API_KEY environment variable or call apiKey() method.'
);
}
if (empty($apiSecret)) {
throw new StreamException(
'API secret not provided. Set STREAM_API_SECRET environment variable or call apiSecret() method.'
);
}
$this->apiKey = $apiKey;
$this->apiSecret = $apiSecret;
$this->baseUrl = $baseUrl;
}
/**
* Load environment variables from .env file.
*/
private function loadEnvironmentVariables(): void
{
try {
$path = $this->envPath ?? getcwd();
if ($path !== false && file_exists($path . '/.env')) {
$dotenv = Dotenv::createImmutable($path);
$dotenv->load();
}
} catch (\Exception $e) {
// Silently ignore if .env file doesn't exist or can't be loaded
// Environment variables might be set through other means
}
}
/**
* Get environment variable value.
*/
private function getEnvVar(string $name): ?string
{
$value = $_ENV[$name] ?? $_SERVER[$name] ?? getenv($name);
return $value !== false ? $value : null;
}
/**
* Resolve the HttpClient.
* If the user supplied one via httpClient(), return it as-is (escape hatch).
* Otherwise build a GuzzleHttpClient with the configured PoolConfig. Either way,
* emit one `client.initialized` INFO event through the injected PSR-3 logger.
*/
private function resolveHttpClient(): HttpClientInterface
{
$logger = $this->logger ?? new NullLogger();
$user = $this->httpClient;
if ($user !== null) {
$logger->info('client.initialized', $this->clientInitializedContext(userHttpClient: true));
$this->warnIfLogBodies($logger);
return $user;
}
$client = new GuzzleHttpClient([], 3, $this->pool, $logger, $this->logBodies, $this->retry);
$logger->info('client.initialized', $this->clientInitializedContext(userHttpClient: false));
$this->warnIfLogBodies($logger);
return $client;
}
private function warnIfLogBodies(LoggerInterface $logger): void
{
if ($this->logBodies) {
$logger->warning(
'HTTP request/response bodies will be logged. Auth headers and known-secret fields are still redacted, but other sensitive data (messages, PII) may appear in logs. Disable for production.'
);
}
}
/** @return array<string, scalar> */
private function clientInitializedContext(bool $userHttpClient): array
{
return [
'stream.sdk.name' => 'getstream-php',
'stream.sdk.version' => Constant::VERSION,
'stream.client.max_conns_per_host' => $this->pool->maxConnsPerHost,
'stream.client.idle_timeout_seconds' => $this->pool->idleTimeout,
'stream.client.connect_timeout_seconds' => $this->pool->connectTimeout,
'stream.client.request_timeout_seconds' => $this->pool->requestTimeout,
'stream.client.gzip_enabled' => true,
'stream.client.user_http_client' => $userHttpClient,
'stream.client.log_bodies' => $this->logBodies,
];
}
}