Skip to content

Commit a511e5c

Browse files
committed
Merge remote-tracking branch 'origin/master' into sdk-release/next-major
Committed-By-Agent: claude # Conflicts: # lib/ApiRequestor.php # lib/HttpClient/CurlClient.php
2 parents 4715254 + 67af014 commit a511e5c

14 files changed

Lines changed: 596 additions & 72 deletions
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
title: Fix `refreshFrom()` corrupting an object when a removed response field shares a name with an internal property such as `_opts`
3+
semver_level: patch
4+
---
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
title: Report request outcome in client telemetry
3+
semver_level: minor
4+
---
5+
6+
Client telemetry now includes `http_status`, `error`, `request_start_ms`, `retry_count`, and `request_metric_id`, and is also recorded for requests that fail without a response (timeouts and connection errors). `request_id` is omitted when the response has none.
7+
8+
`CurlClient::request()` and `CurlClient::requestStream()` now return the retry count as an optional fourth element of their result.

‎lib/ApiRequestor.php‎

Lines changed: 163 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -71,15 +71,21 @@ public function __construct(
7171
*/
7272
private static function _telemetryJson($requestTelemetry)
7373
{
74+
$metrics = [
75+
'request_id' => $requestTelemetry->requestId,
76+
'http_status' => $requestTelemetry->httpStatus,
77+
'error' => $requestTelemetry->error,
78+
'request_start_ms' => $requestTelemetry->requestStartMs,
79+
'retry_count' => $requestTelemetry->retryCount,
80+
'request_duration_ms' => $requestTelemetry->requestDuration,
81+
'request_metric_id' => $requestTelemetry->requestMetricId,
82+
'usage' => \count($requestTelemetry->usage) > 0 ? $requestTelemetry->usage : null,
83+
];
7484
$payload = [
75-
'last_request_metrics' => [
76-
'request_id' => $requestTelemetry->requestId,
77-
'request_duration_ms' => $requestTelemetry->requestDuration,
78-
],
85+
'last_request_metrics' => \array_filter($metrics, static function ($value) {
86+
return null !== $value;
87+
}),
7988
];
80-
if (\count($requestTelemetry->usage) > 0) {
81-
$payload['last_request_metrics']['usage'] = $requestTelemetry->usage;
82-
}
8389

8490
$result = \json_encode($payload);
8591
if (false !== $result) {
@@ -200,10 +206,18 @@ public function request(
200206
) {
201207
$params = self::protectOAuthParams($url, $params) ?: [];
202208
$headers = $headers ?: [];
203-
list($rbody, $rcode, $rheaders, $myApiKey)
209+
list($rbody, $rcode, $rheaders, $myApiKey, $timing)
204210
= $this->_requestRaw($method, $url, $params, $headers, $apiMode, $usage, $maxNetworkRetries);
205-
$this->_maybeEmitStripeNotice($rheaders);
206-
$json = $this->_interpretResponse($rbody, $rcode, $rheaders, $apiMode);
211+
212+
try {
213+
$this->_maybeEmitStripeNotice($rheaders);
214+
$json = $this->_interpretResponse($rbody, $rcode, $rheaders, $apiMode);
215+
} catch (\Throwable $e) {
216+
$this->_recordRequestTelemetry($timing, $usage, $rcode, $rheaders, self::_classifyResponseError($e));
217+
218+
throw $e;
219+
}
220+
$this->_recordRequestTelemetry($timing, $usage, $rcode, $rheaders);
207221
$resp = new ApiResponse($rbody, $rcode, $rheaders, $json);
208222

209223
return [$resp, Util\Secret::unwrap($myApiKey)];
@@ -235,12 +249,20 @@ public function requestStream(
235249
) {
236250
$params = self::protectOAuthParams($url, $params) ?: [];
237251
$headers = $headers ?: [];
238-
list($rbody, $rcode, $rheaders, $myApiKey)
252+
list($rbody, $rcode, $rheaders, $myApiKey, $timing)
239253
= $this->_requestRawStreaming($method, $url, $params, $headers, $apiMode, $usage, $readBodyChunkCallable, $maxNetworkRetries);
240-
$this->_maybeEmitStripeNotice($rheaders);
241-
if ($rcode >= 300) {
242-
$this->_interpretResponse($rbody, $rcode, $rheaders, $apiMode);
254+
255+
try {
256+
$this->_maybeEmitStripeNotice($rheaders);
257+
if ($rcode >= 300) {
258+
$this->_interpretResponse($rbody, $rcode, $rheaders, $apiMode);
259+
}
260+
} catch (\Throwable $e) {
261+
$this->_recordRequestTelemetry($timing, $usage, $rcode, $rheaders, self::_classifyResponseError($e));
262+
263+
throw $e;
243264
}
265+
$this->_recordRequestTelemetry($timing, $usage, $rcode, $rheaders);
244266
}
245267

246268
/**
@@ -996,29 +1018,24 @@ private function _requestRaw($method, $url, $params, $headers, $apiMode, $usage,
9961018

9971019
$client = self::httpClient();
9981020
$builtIn = HttpClient\CurlClient::class === \get_class($client);
999-
list($rbody, $rcode, $rheaders) = $client->request(
1000-
$method,
1001-
$absUrl,
1002-
$builtIn ? $rawHeaders : \array_map([Util\Secret::class, 'unwrap'], $rawHeaders),
1003-
$builtIn ? $params : self::forExternalClientParams($params),
1004-
$hasFile,
1005-
$apiMode,
1006-
$maxNetworkRetries
1007-
);
1008-
1009-
if (
1010-
isset($rheaders['request-id'])
1011-
&& \is_string($rheaders['request-id'])
1012-
&& '' !== $rheaders['request-id']
1013-
) {
1014-
self::$requestTelemetry = new RequestTelemetry(
1015-
$rheaders['request-id'],
1016-
Util\Util::currentTimeMillis() - $requestStartMs,
1017-
$usage
1021+
1022+
try {
1023+
$response = $client->request(
1024+
$method,
1025+
$absUrl,
1026+
$builtIn ? $rawHeaders : \array_map([Util\Secret::class, 'unwrap'], $rawHeaders),
1027+
$builtIn ? $params : self::forExternalClientParams($params),
1028+
$hasFile,
1029+
$apiMode,
1030+
$maxNetworkRetries
10181031
);
1032+
} catch (\Throwable $e) {
1033+
$this->_recordConnectionFailure($e, $requestStartMs, $usage);
1034+
1035+
throw $e;
10191036
}
10201037

1021-
return [$rbody, $rcode, $rheaders, $myApiKey];
1038+
return self::_withTiming($response, $myApiKey, $requestStartMs);
10221039
}
10231040

10241041
/**
@@ -1044,29 +1061,121 @@ private function _requestRawStreaming($method, $url, $params, $headers, $apiMode
10441061

10451062
$client = self::streamingHttpClient();
10461063
$builtIn = HttpClient\CurlClient::class === \get_class($client);
1047-
list($rbody, $rcode, $rheaders) = $client->requestStream(
1048-
$method,
1049-
$absUrl,
1050-
$builtIn ? $rawHeaders : \array_map([Util\Secret::class, 'unwrap'], $rawHeaders),
1051-
$builtIn ? $params : self::forExternalClientParams($params),
1052-
$hasFile,
1053-
$readBodyChunkCallable,
1054-
$apiMode,
1055-
$maxNetworkRetries
1056-
);
1057-
1058-
if (
1059-
isset($rheaders['request-id'])
1060-
&& \is_string($rheaders['request-id'])
1061-
&& '' !== $rheaders['request-id']
1062-
) {
1063-
self::$requestTelemetry = new RequestTelemetry(
1064-
$rheaders['request-id'],
1065-
Util\Util::currentTimeMillis() - $requestStartMs
1064+
1065+
try {
1066+
$response = $client->requestStream(
1067+
$method,
1068+
$absUrl,
1069+
$builtIn ? $rawHeaders : \array_map([Util\Secret::class, 'unwrap'], $rawHeaders),
1070+
$builtIn ? $params : self::forExternalClientParams($params),
1071+
$hasFile,
1072+
$readBodyChunkCallable,
1073+
$apiMode,
1074+
$maxNetworkRetries
10661075
);
1076+
} catch (\Throwable $e) {
1077+
$this->_recordConnectionFailure($e, $requestStartMs, $usage);
1078+
1079+
throw $e;
10671080
}
10681081

1069-
return [$rbody, $rcode, $rheaders, $myApiKey];
1082+
return self::_withTiming($response, $myApiKey, $requestStartMs);
1083+
}
1084+
1085+
/**
1086+
* Combines an HTTP client response with the request timing used for telemetry.
1087+
*
1088+
* @param array $response the HTTP client's (body, status, headers[, retry count]) tuple
1089+
* @param string $myApiKey
1090+
* @param int $requestStartMs
1091+
*
1092+
* @return array
1093+
*/
1094+
private static function _withTiming($response, $myApiKey, $requestStartMs)
1095+
{
1096+
$timing = [
1097+
'request_start_ms' => $requestStartMs,
1098+
'retry_count' => isset($response[3]) ? $response[3] : null,
1099+
];
1100+
1101+
return [$response[0], $response[1], $response[2], $myApiKey, $timing];
1102+
}
1103+
1104+
/**
1105+
* @param \Throwable $e
1106+
*
1107+
* @return null|'api_error'|'invalid_response'
1108+
*/
1109+
private static function _classifyResponseError($e)
1110+
{
1111+
if ($e instanceof Exception\UnexpectedValueException) {
1112+
return 'invalid_response';
1113+
}
1114+
if ($e instanceof Exception\ApiErrorException) {
1115+
return 'api_error';
1116+
}
1117+
1118+
return null;
1119+
}
1120+
1121+
/**
1122+
* Records the terminal outcome of a request that received no usable response.
1123+
*
1124+
* @param \Throwable $e
1125+
* @param int $requestStartMs
1126+
* @param string[] $usage
1127+
*/
1128+
private function _recordConnectionFailure($e, $requestStartMs, $usage)
1129+
{
1130+
$isTimeout = $e instanceof Exception\ApiConnectionException && $e->isTimeout();
1131+
$retryCount = $e instanceof Exception\ApiConnectionException ? $e->getRetryCount() : null;
1132+
$timing = [
1133+
'request_start_ms' => $requestStartMs,
1134+
'retry_count' => $retryCount,
1135+
];
1136+
$this->_recordRequestTelemetry($timing, $usage, null, null, $isTimeout ? 'timeout' : 'connection_error');
1137+
}
1138+
1139+
/**
1140+
* Stores the telemetry to report with the next request. Never throws:
1141+
* telemetry must not change the result of the API request.
1142+
*
1143+
* @param array $timing
1144+
* @param string[] $usage
1145+
* @param null|int $httpStatus
1146+
* @param null|array|Util\CaseInsensitiveArray $rheaders
1147+
* @param null|string $error
1148+
*/
1149+
private function _recordRequestTelemetry($timing, $usage, $httpStatus = null, $rheaders = null, $error = null)
1150+
{
1151+
if (!Stripe::$enableTelemetry) {
1152+
return;
1153+
}
1154+
1155+
try {
1156+
$requestId = null;
1157+
if (
1158+
null !== $rheaders
1159+
&& isset($rheaders['request-id'])
1160+
&& \is_string($rheaders['request-id'])
1161+
&& '' !== $rheaders['request-id']
1162+
) {
1163+
$requestId = $rheaders['request-id'];
1164+
}
1165+
1166+
self::$requestTelemetry = new RequestTelemetry(
1167+
$requestId,
1168+
Util\Util::currentTimeMillis() - $timing['request_start_ms'],
1169+
$usage,
1170+
$httpStatus ?: null,
1171+
$error,
1172+
$timing['request_start_ms'],
1173+
$timing['retry_count'],
1174+
(new Util\RandomGenerator())->uuid()
1175+
);
1176+
} catch (\Throwable $e) {
1177+
// Intentionally ignored; see above.
1178+
}
10701179
}
10711180

10721181
/**

‎lib/Exception/ApiConnectionException.php‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,47 @@
77
* servers. That can be for a variety of different reasons from a downed
88
* network to a bad TLS certificate.
99
*/
10-
class ApiConnectionException extends ApiErrorException {}
10+
class ApiConnectionException extends ApiErrorException
11+
{
12+
/** @var bool */
13+
protected $timeout = false;
14+
15+
/** @var null|int */
16+
protected $retryCount;
17+
18+
/**
19+
* Whether the request failed because it timed out.
20+
*
21+
* @return bool
22+
*/
23+
public function isTimeout()
24+
{
25+
return $this->timeout;
26+
}
27+
28+
/**
29+
* @param bool $timeout
30+
*/
31+
public function setTimeout($timeout)
32+
{
33+
$this->timeout = $timeout;
34+
}
35+
36+
/**
37+
* The number of retries made before this error was thrown, if known.
38+
*
39+
* @return null|int
40+
*/
41+
public function getRetryCount()
42+
{
43+
return $this->retryCount;
44+
}
45+
46+
/**
47+
* @param null|int $retryCount
48+
*/
49+
public function setRetryCount($retryCount)
50+
{
51+
$this->retryCount = $retryCount;
52+
}
53+
}

‎lib/HttpClient/ClientInterface.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ interface ClientInterface
1515
* @param null|int $maxNetworkRetries
1616
*
1717
* @return array an array whose first element is raw request body, second
18-
* element is HTTP status code and third array of HTTP headers
18+
* element is HTTP status code and third array of HTTP headers. An
19+
* optional fourth element is the number of retries made, reported in
20+
* client telemetry
1921
*
2022
* @throws \Stripe\Exception\ApiConnectionException
2123
* @throws \Stripe\Exception\UnexpectedValueException

0 commit comments

Comments
 (0)