diff --git a/README.md b/README.md index 7a8c9d6..a35f5c3 100644 --- a/README.md +++ b/README.md @@ -146,27 +146,59 @@ $client->get_news_count([ To pass a query string or full URL verbatim, use `raw_query`. It is mutually exclusive with every other parameter and is validated against the endpoint's -allowed keys: +allowed keys (for the v1 count endpoints it must also carry `from_date` and +`to_date`): ```php $client->get_latest_news(['raw_query' => 'q=bitcoin&country=us&language=en']); ``` +### Paging: scroll and paginate + +The news and count methods (not the sources ones) can follow the page cursor +for you. Add the control keys to the parameter array — they are not sent to +the API: + +```php +// scroll: one merged response, at most max_result results (optional). +$merged = $client->get_news(['q' => 'bitcoin', 'scroll' => true, 'max_result' => 200]); +count($merged->results); + +// paginate: a generator yielding one response per page, at most max_pages pages (optional). +foreach ($client->get_news(['q' => 'bitcoin', 'paginate' => true, 'max_pages' => 5]) as $page) { + echo count($page->results), PHP_EOL; +} +``` + +`scroll` and `paginate` are mutually exclusive. `scroll` truncates strictly to +`max_result`; `paginate` stops at `max_pages` or when there is no next page. +Version 2 methods follow `next_page` and return `total_results` / `next_page`; +version 1 methods follow `nextPage` and return `totalResults` / `nextPage`. A +version 1 count ends with its aggregate (an object in `results`): `scroll` +returns it under `aggregate`, and `paginate` stops there. Parameters, a +`raw_query` included, are validated once, before the first request. The client +sleeps one second between pages; change it with +`$client->setPaginationDelay($seconds)`. + ## Client-side validation Before any request is sent, parameters are validated and normalized. A `NewsdataValidationError` is raised (without spending API quota) when: - a parameter is not accepted by that endpoint; -- mutually-exclusive parameters are set together — `q`/`qInTitle`/`qInMeta`, - `country`/`excludecountry`, `category`/`excludecategory`, - `language`/`excludelanguage`, `domain`/`domainurl`/`excludedomain`; +- mutually-exclusive parameters are set together — version 1: + `q`/`qInTitle`/`qInMeta`, `country`/`excludecountry`, + `category`/`excludecategory`, `language`/`excludelanguage`, + `domain`/`domainurl`/`excludedomain`/`excludedomainurl`; version 2: + `q`/`q_in_title`/`q_in_meta`, `country`/`exclude_country`, + `category`/`exclude_category`, `language`/`exclude_language`, + `source_url`/`exclude_source_url`; - `size` is outside 1–50; - `sentiment_score` is set without `sentiment`; -- a count endpoint is missing `from_date` or `to_date`. +- a version 1 count endpoint is missing `from_date` or `to_date`. -Booleans (`full_content`, `image`, `video`, `removeduplicate`) are coerced to -`1` / `0`. +Booleans (`full_content`, `image`, `video`, `removeduplicate`, and the version 2 +`content`, `remove_duplicate`) are coerced to `1` / `0`. ## Real-time news (WebSocket) @@ -187,8 +219,9 @@ $registrationId = $registered->results->registration_id; `register()` takes the same filter names as `get_news()` (`q`, `q_in_title`, `country`, `exclude_country`, `source_url`, `content`, `exclude_field`, `timezone`, …) — the date, paging and sorting filters, `id` and `url` don't -apply to a standing query. Registering an identical query twice throws -`NewsdataAPIError` with status 409; the existing id is in the response body. +apply to a standing query, and `news_type` is set by the client. Registering an +identical query twice throws `NewsdataAPIError` with status 409; the existing id +is in the response body. `raw_query` works here too. `fetch()` lists every registered query: `results` is a list with one entry per query, carrying its `registration_id`, the filters it was registered with @@ -223,12 +256,22 @@ rejection — bad API key or unknown `registration_id`, exhausted API credits, or too many simultaneous devices — throws `NewsdataWebSocketAuthError` and is **not** retried. -The server always accepts the handshake and then closes with code **1008** when -the connection is refused, carrying one of three reasons: `invalid credentials -or registration not found`, `api limit reached`, or `device limit reached` (more -than 5 devices on one `registration_id`). Every other close code — including -`1013` (`send timeout`, meaning the client read too slowly) — is transient and -reconnects. +When it refuses a connection, the server accepts the handshake, sends one error +response — `{"status":"error","results":{"message":"…","code":"…"}}` — and +closes. The stream never yields that response: it becomes the thrown error, +whose message is the server's explanation, `getErrorCode()` its code and +`getResponseBody()` the whole response. Close code **1008** is permanent; its +reason is the bare code: `Unauthorized` or `InvalidRequest` (bad key or unknown +`registration_id`), `ApiLimitExceeded` or `ApiKeyLimitExceeded` (credits used +up), `DeviceLimitExceeded` (more than 5 devices on one `registration_id`). +Every other close code — `1011` (server error) and `1013` (the client read too +slowly) included — is transient and reconnects; with `'reconnect' => false` it +throws `NewsdataWebSocketError` carrying the server's message. + +A quiet stream is not a failure: news can be minutes apart. When nothing +arrives for `pingInterval` seconds (default 20) the client sends a ping, and +only when nothing comes back within `pingTimeout` more seconds (default 20) is +the connection treated as dead and reconnected. **Each delivered article consumes 1 API credit per connected device.** @@ -243,7 +286,7 @@ try { // ... } } catch (NewsdataWebSocketAuthError $e) { - echo 'rejected: ', $e->getMessage(), PHP_EOL; + echo 'rejected (', $e->getErrorCode(), '): ', $e->getMessage(), PHP_EOL; } catch (NewsdataWebSocketError $e) { echo 'stream error: ', $e->getMessage(), PHP_EOL; } @@ -257,22 +300,24 @@ $ws = new NewsdataWebSocket($api, [ 'reconnect' => true, // auto-reconnect on transient drops; default true 'reconnectDelay' => 1.0, // seconds before the first reconnect (doubles each retry) 'reconnectDelayMax' => 30.0, // cap on the reconnect delay - 'handshakeTimeout' => 10, // seconds to wait for the opening handshake + 'handshakeTimeout' => 10, // seconds to wait for the opening handshake (only) + 'pingInterval' => 20.0, // seconds of silence before a keepalive ping; null = no keepalive + 'pingTimeout' => 20.0, // seconds to wait for anything after that ping ]); ``` > **Streaming needs one extra package.** PHP has no WebSocket client in core, so > `stream()` requires [`phrity/websocket`](https://packagist.org/packages/phrity/websocket) -> (PHP 8.1+): +> version 4 (PHP 8.1+; tested with 4.1): > > ```bash -> composer require phrity/websocket +> composer require phrity/websocket:^4.1 > ``` > > It is an **optional** dependency — everything else in this SDK, including the > three `websocket/*` management endpoints above, works without it on every -> supported PHP version. `stream()` throws a `NewsdataWebSocketError` telling -> you to install it if it is missing. +> supported PHP version. `stream()` throws a `NewsdataWebSocketError` at once, +> telling you to install it, if it is missing. Runnable example: [`examples/websocket.php`](examples/websocket.php). @@ -314,10 +359,18 @@ NewsdataException (catch-all base) │ │ real-time registration slots, not credits) │ └── NewsdataServerError (5xx) ├── NewsdataNetworkError (cURL / connectivity) -└── NewsdataWebSocketError (real-time stream) +└── NewsdataWebSocketError (real-time stream; getErrorCode(), getResponseBody()) └── NewsdataWebSocketAuthError (policy-violation close 1008) ``` +### Upgrading from 1.x + +`NewsdataIO\NewsdataAPIException`, the single exception class of 1.x, is no longer thrown +(the class still exists, marked deprecated, so old code keeps loading). A +`catch (NewsdataAPIException $e)` block now silently stops catching API errors: +catch `NewsdataException` (everything the SDK throws) or the specific +`NewsdataAPIError` / `NewsdataNetworkError` / … subclasses above instead. + ## Configuration ```php @@ -333,10 +386,12 @@ $client->setProxy([ $client->setLogger($psr3Logger); // API key is redacted from logged URLs ``` -Retries cover network errors, HTTP 429, and 5xx responses. 429 honors the -`Retry-After` header (integer seconds or HTTP-date); otherwise backoff is -exponential (`2s → 4s → 8s …`, capped). Auth and other 4xx errors are never -retried. +Retries cover network errors, HTTP 429, and 5xx responses. A 429 waits for its +`Retry-After` (integer seconds or HTTP-date) plus one second; without the +header, backoff is exponential (`2s → 4s → 8s …`, capped). When `Retry-After` +is longer than `setRetryBackoffMax()` (default 60 s), the call throws +`NewsdataRateLimitError` at once with `getRetryAfter()` set, leaving the wait +to you. Auth and other 4xx errors are never retried. A 429 that waiting cannot fix is never retried. `NewsdataApiLimitExceededError` means the account's whole credit pool is diff --git a/composer.json b/composer.json index 2cf9a8c..0efe7fa 100644 --- a/composer.json +++ b/composer.json @@ -41,7 +41,7 @@ }, "suggest": { "psr/log": "Allows attaching a PSR-3 logger via NewsdataApi::setLogger()", - "phrity/websocket": "Required for real-time streaming via NewsdataWebSocket::stream() (PHP 8.1+)" + "phrity/websocket": "Required for real-time streaming via NewsdataWebSocket::stream(): version ^4.1 (PHP 8.1+), the range this SDK is tested with" }, "autoload": { "psr-4": { diff --git a/examples/websocket.php b/examples/websocket.php index e4b9938..0f463b3 100644 --- a/examples/websocket.php +++ b/examples/websocket.php @@ -5,9 +5,9 @@ * * NEWSDATA_API_KEY= php examples/websocket.php * - * Streaming needs the optional phrity/websocket package (PHP 8.1+): + * Streaming needs the optional phrity/websocket package, version 4 (PHP 8.1+): * - * composer require phrity/websocket + * composer require phrity/websocket:^4.1 * * Articles are matched by a registered query. If NEWSDATA_REGISTRATION_ID is * set, that query is streamed directly; otherwise this registers a demo query @@ -70,7 +70,9 @@ function registerDemoQuery(NewsdataWebSocket $ws): string } } } catch (NewsdataWebSocketAuthError $e) { - fwrite(STDERR, 'rejected: ' . $e->getMessage() . PHP_EOL); + // A refusal is never yielded as news: the server's explanation arrives + // here, with its code (Unauthorized, ApiLimitExceeded, DeviceLimitExceeded, ...). + fwrite(STDERR, 'rejected (' . $e->getErrorCode() . '): ' . $e->getMessage() . PHP_EOL); exit(1); } catch (NewsdataWebSocketError $e) { fwrite(STDERR, 'stream error: ' . $e->getMessage() . PHP_EOL); diff --git a/src/Constants.php b/src/Constants.php index 79da5e0..ab5ce72 100644 --- a/src/Constants.php +++ b/src/Constants.php @@ -8,10 +8,10 @@ * Static configuration for the Newsdata.io client: base URL, endpoint paths, * HTTP defaults, and the per-endpoint accepted-parameter sets. * - * The parameter sets mirror the server-side filter mapping and the official - * Python client surface. All parameter names are lowercase here; user-supplied - * keys are lowercased before validation (the API itself is case-insensitive, - * so `qInTitle` and `qintitle` are equivalent). + * The parameter sets mirror the server-side filter mapping. All parameter + * names are lowercase here; user-supplied keys are lowercased before + * validation (the API itself is case-insensitive, so `qInTitle` and + * `qintitle` are equivalent). */ final class Constants { @@ -52,6 +52,19 @@ final class Constants /** Cap on any single backoff sleep, in seconds. */ public const DEFAULT_RETRY_BACKOFF_MAX = 60.0; + /** Seconds slept between pages in scroll / paginate mode. */ + public const DEFAULT_PAGINATION_DELAY = 1.0; + + /** + * Endpoints that page through results with a `page` cursor, and so accept + * the `scroll` / `paginate` control keys. The version 1 count endpoints + * end with their aggregate as an object in `results`. + */ + public const PAGEABLE_ENDPOINTS = [ + 'latest', 'archive', 'crypto', 'market', 'count', 'crypto_count', 'market_count', + 'news_v2', 'market_v2', 'crypto_v2', 'count_news_v2', 'count_market_v2', 'count_crypto_v2', + ]; + /** Allowed response size bounds (a single account cannot exceed 50). */ public const SIZE_MIN = 1; public const SIZE_MAX = 50; @@ -117,6 +130,30 @@ final class Constants /** Bound on the opening handshake, in seconds. */ public const WS_HANDSHAKE_TIMEOUT = 10; + /** + * Keepalive: after this many seconds without a + * message the client sends a ping... + */ + public const WS_PING_INTERVAL = 20.0; + + /** ...and treats the connection as dead if nothing arrives within this many more. */ + public const WS_PING_TIMEOUT = 20.0; + + /** How long one read waits when keepalive is off (pingInterval null); a timeout just waits again. */ + public const WS_IDLE_READ_TIMEOUT = 300.0; + + /** + * Error codes the stream server sends (in its error frame, and as the + * close reason of close 1008) for a permanent rejection. + */ + public const WS_PERMANENT_CODES = [ + 'Unauthorized', + 'InvalidRequest', + 'ApiLimitExceeded', + 'ApiKeyLimitExceeded', + 'DeviceLimitExceeded', + ]; + /** * Error codes on a 429 that waiting cannot fix, so they are never retried. * `ApiLimitExceeded` and `ApiKeyLimitExceeded` mean the API credits are @@ -303,15 +340,16 @@ final class Constants ], // Real-time query registration. The real-time service is v2 only, so // these are the v2 filter names. No date or paging filters apply — a - // registered query matches news as it is published. `news_type` is set - // by get_websocket_register(), not by the caller. + // registered query matches news as it is published. `news_type` is not + // accepted from the caller: get_websocket_register() adds it after + // validation (so it also works with raw_query). 'websocket_register' => [ 'q', 'q_in_title', 'q_in_meta', 'country', 'exclude_country', 'category', 'exclude_category', 'language', 'exclude_language', 'source_url', 'exclude_source_url', 'source_priority', 'timezone', 'content', 'image', 'video', 'remove_duplicate', 'tag', 'sentiment', 'sentiment_score', 'region', 'organization', 'creator', 'datatype', - 'exclude_field', 'news_type', + 'exclude_field', ], 'websocket_fetch' => [], 'websocket_delete' => ['registration_id'], diff --git a/src/Exception/NewsdataWebSocketError.php b/src/Exception/NewsdataWebSocketError.php index 6cf38d3..3f5c8dd 100644 --- a/src/Exception/NewsdataWebSocketError.php +++ b/src/Exception/NewsdataWebSocketError.php @@ -7,8 +7,49 @@ /** * A real-time WebSocket stream failure. * + * When the server explained the failure in an error response before closing + * (`{"status":"error","results":{"message":...,"code":...}}`), the message is + * the server's explanation, {@see getErrorCode()} its code (for example + * `Unauthorized` or `ServerError`) and {@see getResponseBody()} the whole + * response. + * * @see \NewsdataIO\NewsdataWebSocket */ class NewsdataWebSocketError extends NewsdataException { + /** @var array|null */ + private $responseBody; + + /** @var string|null */ + private $errorCode; + + public function __construct( + string $message = '', + ?array $responseBody = null, + ?string $errorCode = null, + ?\Throwable $previous = null + ) { + parent::__construct($message, 0, $previous); + $this->responseBody = $responseBody; + $this->errorCode = $errorCode; + } + + /** + * The error response the server sent before closing, decoded to an + * array regardless of the client's setDecodeJsonAsArray() setting, or + * null when there was none. + */ + public function getResponseBody(): ?array + { + return $this->responseBody; + } + + /** + * The server's error code (`Unauthorized`, `ApiLimitExceeded`, + * `DeviceLimitExceeded`, `ServerError`, ...), or null when unknown. + */ + public function getErrorCode(): ?string + { + return $this->errorCode; + } } diff --git a/src/NewsdataApi.php b/src/NewsdataApi.php index 5d13359..328b942 100644 --- a/src/NewsdataApi.php +++ b/src/NewsdataApi.php @@ -18,6 +18,15 @@ * * $client = new NewsdataApi(NEWSDATA_API_KEY); * $response = $client->get_latest_news(['q' => 'bitcoin', 'country' => 'us']); + * + * The news and count methods (not the sources ones) also page for you: + * `'scroll' => true` (with an optional `'max_result' => N`) + * follows the page cursor and returns one merged response, and + * `'paginate' => true` (with an optional `'max_pages' => N`) returns a + * generator yielding one response per page. + * + * $merged = $client->get_news(['q' => 'bitcoin', 'scroll' => true, 'max_result' => 200]); + * foreach ($client->get_news(['q' => 'bitcoin', 'paginate' => true, 'max_pages' => 5]) as $page) { ... } */ class NewsdataApi extends NewsdataApiBase { @@ -60,6 +69,14 @@ public function setRetryBackoffMax(float $seconds): void $this->retryBackoffMax = $seconds; } + /** + * Seconds to sleep between pages in scroll / paginate mode (default 1). + */ + public function setPaginationDelay(float $seconds): void + { + $this->paginationDelay = max(0.0, $seconds); + } + /** * Decode JSON responses as associative arrays instead of objects. */ @@ -304,8 +321,9 @@ public function get_count_crypto(array $data = []) */ public function get_websocket_register(array $data = []) { - $data['news_type'] = Constants::WS_NEWS_TYPE; - return $this->request('websocket_register', $data); + // news_type names the feed; the client adds it after validation, so a + // raw_query (which must be the only caller parameter) works too. + return $this->request('websocket_register', $data, ['news_type' => Constants::WS_NEWS_TYPE]); } /** diff --git a/src/NewsdataApiBase.php b/src/NewsdataApiBase.php index 5cfc59e..ab84842 100644 --- a/src/NewsdataApiBase.php +++ b/src/NewsdataApiBase.php @@ -42,6 +42,9 @@ class NewsdataApiBase /** @var float Cap on a single backoff sleep, in seconds. */ protected $retryBackoffMax = Constants::DEFAULT_RETRY_BACKOFF_MAX; + /** @var float Seconds slept between pages in scroll / paginate mode. */ + protected $paginationDelay = Constants::DEFAULT_PAGINATION_DELAY; + /** @var bool Decode JSON responses as associative arrays. */ protected $decodeJsonAsArray = false; @@ -74,21 +77,201 @@ public function getLastResponse(): Response /** * Validate parameters and execute a request against the named endpoint. * - * @param string $endpoint One of {@see Constants::ENDPOINTS}. - * @param array $data Raw user parameters. + * On the endpoints in {@see Constants::PAGEABLE_ENDPOINTS}, `$data` may + * also carry the paging control keys: `'scroll' => true` + * (follow the page cursor and return one merged response, at most + * `max_result` results) or `'paginate' => true` (return a generator + * yielding one response per page, at most `max_pages` pages). They are + * not sent to the API. Parameters are validated once, before the first + * request. + * + * @param string $endpoint One of {@see Constants::ENDPOINTS}. + * @param array $data Raw user parameters. + * @param array $fixed Parameters the client itself adds + * after validation. * - * @return array|object Decoded response body. + * @return array|object|\Generator Decoded response body; the merged + * response (scroll); or a generator (paginate). */ - protected function request(string $endpoint, array $data) + protected function request(string $endpoint, array $data, array $fixed = []) { if (!isset(Constants::ENDPOINTS[$endpoint])) { throw new Exception\NewsdataValidationError("Unknown endpoint: {$endpoint}"); } - $params = ParamValidator::validate($endpoint, $data); + $mode = in_array($endpoint, Constants::PAGEABLE_ENDPOINTS, true) + ? $this->takePagingControls($data) + : ['scroll' => false, 'paginate' => false, 'max_result' => null, 'max_pages' => null]; + + $params = array_merge(ParamValidator::validate($endpoint, $data), $fixed); $baseUrl = Constants::BASE_URL . Constants::ENDPOINTS[$endpoint]; + + if ($mode['scroll']) { + return $this->scrollAll($baseUrl, $params, $endpoint, $mode['max_result']); + } + if ($mode['paginate']) { + return $this->paginatePages($baseUrl, $params, $endpoint, $mode['max_pages']); + } return $this->execute($baseUrl, $params, $endpoint); } + /** + * Remove the scroll / paginate control keys from $data and return them. + * + * @return array{scroll:bool,paginate:bool,max_result:int|null,max_pages:int|null} + * + * @throws Exception\NewsdataValidationError + */ + private function takePagingControls(array &$data): array + { + $mode = ['scroll' => false, 'paginate' => false, 'max_result' => null, 'max_pages' => null]; + foreach ($data as $key => $value) { + $name = strtolower((string) $key); + if (!array_key_exists($name, $mode)) { + continue; + } + unset($data[$key]); + if ($name === 'scroll' || $name === 'paginate') { + if (!is_bool($value)) { + throw new Exception\NewsdataValidationError("{$name} must be a boolean", $name); + } + $mode[$name] = $value; + } elseif ($value !== null) { + if (!is_int($value) || $value < 1) { + throw new Exception\NewsdataValidationError("{$name} must be a positive integer", $name); + } + $mode[$name] = $value; + } + } + if ($mode['scroll'] && $mode['paginate']) { + throw new Exception\NewsdataValidationError('scroll and paginate are mutually exclusive', 'scroll'); + } + return $mode; + } + + /** + * Follow the page cursor and return one merged response (scroll mode). + * + * Version 1 endpoints read and return `totalResults` / `nextPage`, + * version 2 `total_results` / `next_page`. A version 1 count endpoint + * ends with its aggregate as an object in `results`; that is returned + * under `aggregate`. + * + * @param array $params Validated parameters. + * + * @return array|object + */ + private function scrollAll(string $baseUrl, array $params, string $endpoint, ?int $maxResult) + { + [$totalKey, $nextKey] = $this->pagingKeys($endpoint); + $isCount = in_array($endpoint, Constants::REQUIRES_DATE_RANGE, true); + $accumulated = []; + $total = null; + $next = null; + $aggregate = null; + $request = $params; + + while (true) { + $response = $this->execute($baseUrl, $request, $endpoint); + $total = $this->field($response, $totalKey) ?? $total; + $results = $this->field($response, 'results'); + if (is_array($results) && self::isList($results)) { + $accumulated = array_merge($accumulated, $results); + } elseif ($isCount && (is_array($results) || is_object($results))) { + $aggregate = $results; + } + $next = $this->field($response, $nextKey); + + if ($maxResult !== null && count($accumulated) >= $maxResult) { + $accumulated = array_slice($accumulated, 0, $maxResult); + $next = null; + break; + } + if ($next === null || $next === '') { + break; + } + $request['page'] = (string) $next; + $this->sleepSeconds($this->paginationDelay); + } + + $merged = [$totalKey => $total, 'results' => $accumulated, $nextKey => $next]; + if ($aggregate !== null) { + $merged['aggregate'] = $aggregate; + } + return $this->decodeJsonAsArray ? $merged : (object) $merged; + } + + /** + * Yield one response per page, up to $maxPages (paginate mode). + * + * @param array $params Validated parameters. + * + * @return \Generator + */ + private function paginatePages(string $baseUrl, array $params, string $endpoint, ?int $maxPages): \Generator + { + $nextKey = $this->pagingKeys($endpoint)[1]; + $isCount = in_array($endpoint, Constants::REQUIRES_DATE_RANGE, true); + $request = $params; + $pages = 0; + + while (true) { + $response = $this->execute($baseUrl, $request, $endpoint); + yield $response; + $pages++; + + // A version 1 count ends with its aggregate (an object, not a list). + $results = $this->field($response, 'results'); + if ($isCount && $results !== null && !(is_array($results) && self::isList($results))) { + return; + } + if ($maxPages !== null && $pages >= $maxPages) { + return; + } + $next = $this->field($response, $nextKey); + if ($next === null || $next === '') { + return; + } + $request['page'] = (string) $next; + $this->sleepSeconds($this->paginationDelay); + } + } + + /** + * The total and cursor keys of an endpoint's responses. + * + * @return array{0:string,1:string} + */ + private function pagingKeys(string $endpoint): array + { + return substr($endpoint, -3) === '_v2' + ? ['total_results', 'next_page'] + : ['totalResults', 'nextPage']; + } + + /** + * A top-level field of a decoded response, in either decode mode. + * + * @param mixed $body + * + * @return mixed + */ + private function field($body, string $name) + { + if (is_array($body)) { + return $body[$name] ?? null; + } + if (is_object($body)) { + return $body->{$name} ?? null; + } + return null; + } + + /** Whether $value is a list (sequential keys 0..n-1), not a JSON object. */ + private static function isList(array $value): bool + { + return $value === [] || array_keys($value) === range(0, count($value) - 1); + } + /** * Execute a single GET with retries and backoff. * @@ -158,7 +341,9 @@ private function execute(string $baseUrl, array $params, string $endpoint = '') // A 429 covers a burst limit, a rate limit, and exhausted API // credits. Only the first two are worth retrying. $quotaError = $this->quotaExhaustedError($body); - if ($quotaError !== null || $attempt >= $attempts) { + // A wait longer than retryBackoffMax is left to the caller. + $waitTooLong = $retryAfter !== null && $retryAfter > $this->retryBackoffMax; + if ($quotaError !== null || $attempt >= $attempts || $waitTooLong) { $errorClass = $quotaError !== null ? $quotaError : NewsdataRateLimitError::class; throw new $errorClass( @@ -168,8 +353,10 @@ private function execute(string $baseUrl, array $params, string $endpoint = '') $retryAfter ); } - $sleep = $retryAfter !== null ? (float) $retryAfter : $this->backoff($attempt); - $this->log('warning', "429 rate limit; sleeping {$sleep}s"); + // Retry-After is in whole seconds: one second more keeps the + // retry from arriving just before the limit resets. + $sleep = $retryAfter !== null ? (float) $retryAfter + 1.0 : $this->backoff($attempt); + $this->log('warning', "429 rate limit (attempt {$attempt}/{$attempts}); sleeping {$sleep}s"); $this->sleepSeconds($sleep); continue; } @@ -218,7 +405,7 @@ private function execute(string $baseUrl, array $params, string $endpoint = '') * * @throws NewsdataNetworkError */ - private function httpGet(string $url, string $method = 'GET'): array + protected function httpGet(string $url, string $method = 'GET'): array { $ch = curl_init(); curl_setopt_array($ch, $this->curlOptions($url, $method)); @@ -442,7 +629,7 @@ private function backoff(int $attempt): float return min($delay, $this->retryBackoffMax); } - private function sleepSeconds(float $seconds): void + protected function sleepSeconds(float $seconds): void { if ($seconds > 0) { usleep((int) round($seconds * 1000000)); diff --git a/src/NewsdataWebSocket.php b/src/NewsdataWebSocket.php index 4a12404..9750ea0 100644 --- a/src/NewsdataWebSocket.php +++ b/src/NewsdataWebSocket.php @@ -33,9 +33,17 @@ * reconnected automatically with a capped exponential backoff; pass * `'reconnect' => false` to stop on the first disconnect. A permanent * rejection always throws {@see NewsdataWebSocketAuthError} and is never - * retried. + * retried. The error response the server sends with a refusal is never + * yielded: it becomes the thrown error's message, error code and response + * body. * - * Streaming needs the optional `phrity/websocket` package (PHP 8.1+): + * A quiet stream is not a failure: when nothing arrives for `pingInterval` + * seconds the client sends a ping, and only if nothing arrives within + * `pingTimeout` more seconds is the connection treated as dead (and + * reconnected). + * + * Streaming needs the optional `phrity/websocket` package (PHP 8.1+; tested + * with 4.1): * * composer require phrity/websocket * @@ -61,22 +69,37 @@ class NewsdataWebSocket /** @var int */ private $handshakeTimeout; + /** @var float|null Seconds of silence before a keepalive ping; null turns keepalive off. */ + private $pingInterval; + + /** @var float Seconds to wait for anything after a keepalive ping. */ + private $pingTimeout; + /** @var callable|null Injection point for tests. */ private $connector; + /** @var callable|null Injection point for tests: fn(float $seconds). */ + private $sleeper; + /** @var bool */ private $closed = false; /** @var mixed The live connection, while one is open. */ private $connection; + /** @var float How long the next read may wait, in seconds (applied after the handshake). */ + private $readTimeout = Constants::WS_PING_INTERVAL; + /** * @param NewsdataApi $api Supplies the API key and performs the * management HTTP calls. Not closed by this * class. * @param array $options baseUrl, reconnect, reconnectDelay, - * reconnectDelayMax, handshakeTimeout, - * connector (callable, for tests). + * reconnectDelayMax, handshakeTimeout (the + * opening handshake only), pingInterval and + * pingTimeout (keepalive; pingInterval null + * turns it off), connector and sleeper + * (callables, for tests). */ public function __construct(NewsdataApi $api, array $options = []) { @@ -86,7 +109,12 @@ public function __construct(NewsdataApi $api, array $options = []) $this->reconnectDelay = (float) ($options['reconnectDelay'] ?? Constants::WS_RECONNECT_DELAY); $this->reconnectDelayMax = (float) ($options['reconnectDelayMax'] ?? Constants::WS_RECONNECT_DELAY_MAX); $this->handshakeTimeout = (int) ($options['handshakeTimeout'] ?? Constants::WS_HANDSHAKE_TIMEOUT); + $this->pingInterval = array_key_exists('pingInterval', $options) + ? ($options['pingInterval'] === null ? null : (float) $options['pingInterval']) + : Constants::WS_PING_INTERVAL; + $this->pingTimeout = (float) ($options['pingTimeout'] ?? Constants::WS_PING_TIMEOUT); $this->connector = $options['connector'] ?? null; + $this->sleeper = $options['sleeper'] ?? null; } // ---- query management ------------------------------------------------- @@ -167,6 +195,13 @@ public function stream(string $registrationId): \Generator 'registration_id' ); } + // Fail at once, not on every reconnect attempt. + if ($this->connector === null && !self::phrityInstalled()) { + throw new NewsdataWebSocketError( + 'Real-time streaming needs the phrity/websocket package: ' + . 'composer require phrity/websocket' + ); + } $url = $this->url($registrationId); $delay = $this->reconnectDelay; @@ -175,40 +210,97 @@ public function stream(string $registrationId): \Generator try { while (!$this->isClosed()) { $client = null; + // The error response the server sends right before it closes a + // refused connection. Never yielded: raised with that close. + $errorResponse = null; try { $client = $this->connect($url); $this->connection = $client; + // reset after a successful connect, unless the server refuses it + $refusedDelay = $delay; + $delay = $this->reconnectDelay; + + $closeStatus = null; + $closeReason = ''; + $awaitingPong = false; + $this->readTimeout = $this->pingInterval ?? Constants::WS_IDLE_READ_TIMEOUT; while (!$this->isClosed()) { - $message = $client->receive(); + try { + $message = $client->receive(); + } catch (\Exception $e) { + if (!self::isReadTimeout($e)) { + throw $e; + } + // Nothing arrived for a while. That is not a failure; + // check the connection is alive with a ping. + if ($this->pingInterval === null || !method_exists($client, 'ping')) { + continue; + } + if ($awaitingPong) { + throw new NewsdataWebSocketError( + 'connection lost: no reply to the keepalive ping', + null, + null, + $e + ); + } + $client->ping(); + $awaitingPong = true; + $this->readTimeout = $this->pingTimeout; + continue; + } + // Anything at all (a pong included) shows the connection is alive. + $awaitingPong = false; + $this->readTimeout = $this->pingInterval ?? Constants::WS_IDLE_READ_TIMEOUT; + if ($message === null) { break; // connection closed } - $payload = is_string($message) - ? $message - : (is_object($message) && method_exists($message, 'getContent') - ? (string) $message->getContent() - : null); - if ($payload === null) { - continue; // ignore binary / control frames + [$kind, $payload, $status] = self::classify($message); + if ($kind === 'close') { + $closeStatus = $status; + $closeReason = $payload; + break; + } + if ($kind !== 'text') { + continue; // ping / pong / binary } $decoded = $this->decode($payload); - if ($decoded !== null) { - yield $decoded; + if ($decoded === null) { + continue; // skip malformed frames } - $delay = $this->reconnectDelay; // reset after real traffic + if (self::field($decoded, 'status') === 'error') { + // sent right before the server closes the connection: + // raise it with that close, and keep backing off + $errorResponse = self::toArray($decoded); + $delay = $refusedDelay; + continue; + } + yield $decoded; + } + + if ($closeStatus === Constants::WS_POLICY_VIOLATION) { + throw $this->authError($errorResponse, $closeReason); + } + if ($closeStatus !== null && !in_array($closeStatus, [1000, 1001], true)) { + // An abnormal close (1011 server error, 1013 slow client, ...): transient. + throw $this->streamError($errorResponse, "connection closed ({$closeStatus})"); } - } catch (\Throwable $e) { + // A normal close: reconnect, or end the stream when reconnect is off. + } catch (\Exception $e) { + // Only \Exception: a programming error (\Error, \TypeError) is not + // a network problem and is never retried. if ($this->isClosed()) { return; } - $auth = $this->permanentAuthError($e); + $auth = $this->permanentAuthError($e, $errorResponse); if ($auth !== null) { throw $auth; } if (!$this->reconnect) { - throw $this->transientError($e); + throw $this->transientError($e, $errorResponse); } } finally { $this->closeConnection($client); @@ -220,7 +312,7 @@ public function stream(string $registrationId): \Generator if (!$this->reconnect) { return; } - usleep((int) round($delay * 1000000)); + $this->sleepSeconds($delay); $delay = $this->nextDelay($delay); } } finally { @@ -241,23 +333,86 @@ private function connect(string $url) } // Referenced dynamically: phrity/websocket is an optional dependency, - // so the class need not exist for this file to load or analyse. + // so the classes need not exist for this file to load or analyse. $clientClass = 'WebSocket\\Client'; $uriClass = 'Phrity\\Net\\Uri'; - - if (!class_exists($clientClass) || !class_exists($uriClass)) { + $closeHandlerClass = 'WebSocket\\Middleware\\CloseHandler'; + $pingResponderClass = 'WebSocket\\Middleware\\PingResponder'; + $callbackClass = 'WebSocket\\Middleware\\Callback'; + + if ( + !class_exists($clientClass) + || !class_exists($uriClass) + || !class_exists($closeHandlerClass) + || !class_exists($pingResponderClass) + || !class_exists($callbackClass) + ) { throw new NewsdataWebSocketError( - 'Real-time streaming needs the phrity/websocket package: ' + 'Real-time streaming needs the phrity/websocket package (4.x): ' . 'composer require phrity/websocket' ); } $client = new $clientClass(new $uriClass($url)); + // phrity applies this timeout to every read; it is meant for the + // opening handshake only, so reads switch to $this->readTimeout below. $client->setTimeout($this->handshakeTimeout); + // Acknowledge the server's close and answer its pings. + $client->addMiddleware(new $closeHandlerClass()); + $client->addMiddleware(new $pingResponderClass()); + // Runs before each read of a message (not during the handshake), with + // the live connection: that is where the read timeout can be set. + $client->addMiddleware(new $callbackClass(function ($stack, $connection) { + $connection->getStream()->setTimeout($this->readTimeout); + return $stack->handleIncoming(); + })); $client->connect(); return $client; } + private static function phrityInstalled(): bool + { + return class_exists('WebSocket\\Client') && class_exists('Phrity\\Net\\Uri'); + } + + /** Whether $e is phrity's read timeout (no data within the read timeout). */ + private static function isReadTimeout(\Throwable $e): bool + { + return is_a($e, 'WebSocket\\Exception\\ConnectionTimeoutException'); + } + + /** + * Sort a received message into [kind, payload, close status]: kind is + * "text", "close", "ping", "pong", "binary" or "other". + * + * phrity/websocket 4.x returns message objects with an opcode; a plain + * string is a text frame. + * + * @param mixed $message + * + * @return array{0:string,1:string,2:int} + */ + private static function classify($message): array + { + if (is_string($message)) { + return ['text', $message, 0]; + } + if (is_object($message) && method_exists($message, 'getOpcode')) { + $opcode = (string) $message->getOpcode(); + $content = method_exists($message, 'getContent') ? (string) $message->getContent() : ''; + if ($opcode === 'close') { + // 1005: "no status received" + $status = method_exists($message, 'getCloseStatus') ? (int) $message->getCloseStatus() : 1005; + return ['close', $content, $status]; + } + return [$opcode, $content, 0]; + } + if (is_object($message) && method_exists($message, 'getContent')) { + return ['text', (string) $message->getContent(), 0]; + } + return ['other', '', 0]; + } + /** * Decode one frame, returning null when it isn't a JSON object. * @@ -275,39 +430,134 @@ private function decode(string $payload) return $decoded; } + /** + * @param mixed $body + * + * @return mixed + */ + private static function field($body, string $name) + { + if (is_array($body)) { + return $body[$name] ?? null; + } + if (is_object($body)) { + return $body->{$name} ?? null; + } + return null; + } + + /** + * @param array|object $decoded + */ + private static function toArray($decoded): ?array + { + if (is_array($decoded)) { + return $decoded; + } + $array = json_decode((string) json_encode($decoded), true); + return is_array($array) ? $array : null; + } + + /** The human-readable message in a server error response, if any. */ + private static function frameMessage(?array $errorResponse): ?string + { + $results = $errorResponse['results'] ?? null; + if (is_string($results) && $results !== '') { + return $results; + } + $message = is_array($results) ? ($results['message'] ?? null) : null; + return is_string($message) && $message !== '' ? $message : null; + } + + /** The error code in a server error response (e.g. "Unauthorized"), if any. */ + private static function frameCode(?array $errorResponse): ?string + { + $results = $errorResponse['results'] ?? null; + $code = is_array($results) ? ($results['code'] ?? null) : null; + return is_string($code) && $code !== '' ? $code : null; + } + + /** + * The error for a permanent rejection: the server's message and code when + * it sent an error response, else the close reason (the bare code). + */ + private function authError(?array $errorResponse, string $reason, ?\Throwable $previous = null): NewsdataWebSocketAuthError + { + return new NewsdataWebSocketAuthError( + self::frameMessage($errorResponse) ?? ($reason !== '' ? $reason : 'connection rejected'), + $errorResponse, + self::frameCode($errorResponse) ?? ($reason !== '' ? $reason : null), + $previous + ); + } + + /** A transient stream error, carrying the server's error response if any. */ + private function streamError(?array $errorResponse, string $fallback, ?\Throwable $previous = null): NewsdataWebSocketError + { + return new NewsdataWebSocketError( + self::frameMessage($errorResponse) ?? $fallback, + $errorResponse, + self::frameCode($errorResponse), + $previous + ); + } + /** * The auth error to throw if the failure is a permanent rejection, * else null (the caller then treats it as transient and reconnects). * - * Close code 1008 and handshake 401 / 403 are permanent; everything else - * is transient. + * On a refusal the server accepts the handshake, sends one error response + * ({"status":"error","results":{"message":...,"code":...}}) and closes. + * Close 1008 is permanent: bad apikey or unknown registration_id + * (Unauthorized, InvalidRequest), exhausted credits (ApiLimitExceeded, + * ApiKeyLimitExceeded), or too many devices on one registration_id + * (DeviceLimitExceeded); the close reason is that bare code. 1011 + * (server error) and 1013 (the client read too slowly) are transient. A + * handshake 401 / 403 is permanent too. + * + * When the connection drops without a readable close status, an error + * response carrying one of the permanent codes still counts as permanent. */ - private function permanentAuthError(\Throwable $e): ?NewsdataWebSocketAuthError + private function permanentAuthError(\Exception $e, ?array $errorResponse): ?NewsdataWebSocketAuthError { if ($e instanceof NewsdataWebSocketAuthError) { return $e; } - $code = $e->getCode(); - if ($code === Constants::WS_POLICY_VIOLATION) { - $reason = $e->getMessage(); - return new NewsdataWebSocketAuthError( - $reason !== '' ? $reason : 'connection rejected' - ); + if ($e instanceof NewsdataWebSocketError) { + return null; // already classified as transient + } + if ($e->getCode() === Constants::WS_POLICY_VIOLATION) { + return $this->authError($errorResponse, $e->getMessage(), $e); + } + $frameCode = self::frameCode($errorResponse); + if ($frameCode !== null && in_array($frameCode, Constants::WS_PERMANENT_CODES, true)) { + return $this->authError($errorResponse, '', $e); } $message = $e->getMessage(); if (strpos($message, '401') !== false || strpos($message, '403') !== false) { - return new NewsdataWebSocketAuthError('connection rejected'); + return new NewsdataWebSocketAuthError('connection rejected', null, null, $e); } return null; } /** Wrap a transient failure; used only when reconnect is disabled. */ - private function transientError(\Throwable $e): NewsdataWebSocketError + private function transientError(\Exception $e, ?array $errorResponse): NewsdataWebSocketError { if ($e instanceof NewsdataWebSocketError) { return $e; } - return new NewsdataWebSocketError('connection error: ' . $e->getMessage()); + return $this->streamError($errorResponse, 'connection error: ' . $e->getMessage(), $e); + } + + private function sleepSeconds(float $seconds): void + { + if ($this->sleeper !== null) { + ($this->sleeper)($seconds); + return; + } + if ($seconds > 0) { + usleep((int) round($seconds * 1000000)); + } } /** @@ -320,9 +570,15 @@ private function closeConnection($client): void return; } try { + // Already closed (e.g. the server closed it): phrity's close() would + // first reconnect, since sending needs a connection. + if (method_exists($client, 'isConnected') && !$client->isConnected()) { + return; + } if (method_exists($client, 'close')) { $client->close(); - } elseif (method_exists($client, 'disconnect')) { + } + if (method_exists($client, 'disconnect')) { $client->disconnect(); } } catch (\Throwable $ignored) { diff --git a/src/ParamValidator.php b/src/ParamValidator.php index 303bb18..ab2ba1d 100644 --- a/src/ParamValidator.php +++ b/src/ParamValidator.php @@ -8,8 +8,7 @@ /** * Validates and normalizes a user-supplied parameter array for a given - * endpoint, mirroring the client-side checks performed by the official - * Python client: + * endpoint, before the request is sent: * * - keys are lowercased (the API is case-insensitive); * - `null` values are dropped; @@ -63,20 +62,12 @@ public static function validate(string $endpoint, array $data): array 'raw_query' ); } - return self::parseRawQuery($params['raw_query'], $allowed); + $values = self::parseRawQuery($params['raw_query'], $allowed); + self::requireDateRange($endpoint, $values); + return $values; } - // Count endpoints require an explicit date range. - if (in_array($endpoint, Constants::REQUIRES_DATE_RANGE, true)) { - foreach (['from_date', 'to_date'] as $required) { - if (!isset($params[$required]) || $params[$required] === '') { - throw new NewsdataValidationError( - "{$required} is required for the {$endpoint} endpoint", - $required - ); - } - } - } + self::requireDateRange($endpoint, $params); self::checkMutex($params); @@ -107,6 +98,27 @@ public static function validate(string $endpoint, array $data): array return $validated; } + /** + * Count endpoints require an explicit date range, whether the dates are + * passed as parameters or inside raw_query. + * + * @throws NewsdataValidationError + */ + private static function requireDateRange(string $endpoint, array $values): void + { + if (!in_array($endpoint, Constants::REQUIRES_DATE_RANGE, true)) { + return; + } + foreach (['from_date', 'to_date'] as $required) { + if (!isset($values[$required]) || $values[$required] === '') { + throw new NewsdataValidationError( + "{$required} is required for the {$endpoint} endpoint", + $required + ); + } + } + } + /** * @param array $params Lowercased parameter map. * diff --git a/tests/NewsdataWebSocketTest.php b/tests/NewsdataWebSocketTest.php index 03d89ca..9e90844 100644 --- a/tests/NewsdataWebSocketTest.php +++ b/tests/NewsdataWebSocketTest.php @@ -13,10 +13,56 @@ use NewsdataIO\ParamValidator; use PHPUnit\Framework\TestCase; +require_once __DIR__ . '/Support/PhrityStandIns.php'; + +/** + * A message as phrity/websocket 4.x returns it from receive(): an object with + * an opcode ("text", "close", "ping", "pong", ...), its content, and for a + * close its status code. + */ +final class FakeMessage +{ + /** @var string */ + private $opcode; + + /** @var string */ + private $content; + + /** @var int */ + private $status; + + public function __construct(string $opcode, string $content = '', int $status = 1000) + { + $this->opcode = $opcode; + $this->content = $content; + $this->status = $status; + } + + public static function close(int $status, string $reason = ''): self + { + return new self('close', $reason, $status); + } + + public function getOpcode(): string + { + return $this->opcode; + } + + public function getContent(): string + { + return $this->content; + } + + public function getCloseStatus(): int + { + return $this->status; + } +} + /** * A scriptable stand-in for a live WebSocket connection. The script is a list - * of actions: a string is delivered as a frame, null closes the connection, - * and a Throwable is raised. + * of actions: a string is delivered as a text frame, a FakeMessage as that + * message, null closes the connection, and a Throwable is raised. */ final class FakeConnection { @@ -29,6 +75,9 @@ final class FakeConnection /** @var bool */ public $closed = false; + /** @var int Pings the client sent on this connection. */ + public $pings = 0; + public function __construct(array $script, int $connectionNumber) { $this->script = $script; @@ -36,7 +85,7 @@ public function __construct(array $script, int $connectionNumber) } /** - * @return string|null + * @return string|FakeMessage|null */ public function receive() { @@ -47,7 +96,12 @@ public function receive() if ($next instanceof \Throwable) { throw $next; } - return $next; // string frame, or null to close + return $next; // string frame, a message, or null to close + } + + public function ping(): void + { + $this->pings++; } public function close(): void @@ -83,9 +137,12 @@ private function ws(callable $scriptFor, array $options = []): NewsdataWebSocket $this->connections = []; $this->urls = []; - $options['connector'] = function (string $url) use ($scriptFor) { + $attempts = 0; + $options['connector'] = function (string $url) use ($scriptFor, &$attempts) { $this->urls[] = $url; - $n = count($this->connections) + 1; + // Number connection attempts, not connections: $scriptFor may throw + // to simulate a handshake that fails. + $n = ++$attempts; $conn = new FakeConnection($scriptFor($n), $n); $this->connections[] = $conn; return $conn; @@ -243,13 +300,288 @@ public function testBreakingOutOfTheLoopClosesTheConnection(): void $this->assertTrue($this->connections[0]->closed); } + // ---- refusals: the server's error frame -------------------------------- + // On a refusal the server accepts the handshake, sends ONE error frame + // and closes. The frame is never yielded; it is raised with the close. + + private static function errorFrame(string $code, string $message): string + { + return (string) json_encode([ + 'status' => 'error', + 'results' => ['message' => $message, 'code' => $code], + ]); + } + + /** + * The script for the first connection only; any reconnect fails the test + * (so a client that wrongly reconnects cannot loop forever). + */ + private static function firstConnectionOnly(array $script): callable + { + return function (int $n) use ($script): array { + return $n === 1 + ? $script + : [new NewsdataWebSocketAuthError('test guard: the client reconnected')]; + }; + } + + /** Iterate a stream to its end, collecting what it yields. */ + private static function drain(\Generator $stream, array &$yielded): void + { + foreach ($stream as $response) { + $yielded[] = $response; + } + } + + private static function readTimeout(): \Exception + { + return new \WebSocket\Exception\ConnectionTimeoutException(); + } + + public function testRefusedStreamRaisesTheServerMessageOnClose1008(): void + { + $message = 'Your API key is invalid or the registration was not found.'; + // reconnect stays on: a permanent rejection must not be retried. + $ws = $this->ws(self::firstConnectionOnly([ + self::errorFrame('Unauthorized', $message), + FakeMessage::close(1008, 'Unauthorized'), + ])); + + $yielded = []; + try { + self::drain($ws->stream('reg-1'), $yielded); + $this->fail('expected NewsdataWebSocketAuthError'); + } catch (NewsdataWebSocketAuthError $e) { + $this->assertSame($message, $e->getMessage()); + $this->assertSame('Unauthorized', $e->getErrorCode()); + $this->assertSame('error', $e->getResponseBody()['status']); + $this->assertSame($message, $e->getResponseBody()['results']['message']); + } + $this->assertSame([], $yielded, 'the error frame must not be handed over as news'); + $this->assertCount(1, $this->connections); + } + + public function testErrorFrameThenClose1011WithReconnectOffRaisesAStreamError(): void + { + $ws = $this->ws(fn (int $n) => [ + self::errorFrame('ServerError', 'Something went wrong on our side.'), + FakeMessage::close(1011, 'ServerError'), + ], ['reconnect' => false]); + + $yielded = []; + try { + self::drain($ws->stream('reg-1'), $yielded); + $this->fail('expected NewsdataWebSocketError'); + } catch (NewsdataWebSocketError $e) { + $this->assertNotInstanceOf(NewsdataWebSocketAuthError::class, $e, '1011 is transient'); + $this->assertSame('Something went wrong on our side.', $e->getMessage()); + $this->assertSame('ServerError', $e->getErrorCode()); + } + $this->assertSame([], $yielded); + } + + public function testErrorFrameThenNormalCloseEndsQuietlyWithReconnectOff(): void + { + // A clean close is not an error, even after an error frame. + $ws = $this->ws(fn (int $n) => [ + self::errorFrame('ServerError', 'closing'), + FakeMessage::close(1000), + ], ['reconnect' => false]); + + $yielded = []; + self::drain($ws->stream('reg-1'), $yielded); + $this->assertSame([], $yielded); + } + + public function testAPermanentCodeIsAnAuthErrorEvenWithoutACloseCode(): void + { + // The connection drops without a readable close status. + $ws = $this->ws(self::firstConnectionOnly([ + self::errorFrame('DeviceLimitExceeded', 'Too many devices are streaming this registration.'), + new \RuntimeException('connection closed'), + ])); + + try { + foreach ($ws->stream('reg-1') as $response) { + $this->fail('nothing may be yielded'); + } + $this->fail('expected NewsdataWebSocketAuthError'); + } catch (NewsdataWebSocketAuthError $e) { + $this->assertSame('Too many devices are streaming this registration.', $e->getMessage()); + $this->assertSame('DeviceLimitExceeded', $e->getErrorCode()); + } + } + + public function testClose1008WithoutAnErrorFrameUsesTheCloseReason(): void + { + $ws = $this->ws(self::firstConnectionOnly([FakeMessage::close(1008, 'ApiLimitExceeded')])); + + try { + foreach ($ws->stream('reg-1') as $response) { + $this->fail('nothing may be yielded'); + } + $this->fail('expected NewsdataWebSocketAuthError'); + } catch (NewsdataWebSocketAuthError $e) { + $this->assertSame('ApiLimitExceeded', $e->getMessage()); + $this->assertSame('ApiLimitExceeded', $e->getErrorCode()); + } + } + + public function testClose1013IsTransientAndReconnects(): void + { + $ws = $this->ws(fn (int $n) => $n === 1 + ? [FakeMessage::close(1013)] + : [self::articleFrame('a1', 'after-reconnect')]); + + foreach ($ws->stream('reg-1') as $response) { + $this->assertSame('after-reconnect', $response->results[0]->title); + break; + } + $this->assertCount(2, $this->connections); + } + + // ---- quiet streams and keepalive (PHP-2) ------------------------------- + + public function testAReadTimeoutOnAHealthyConnectionPingsAndKeepsStreaming(): void + { + $ws = $this->ws(fn (int $n) => [ + self::readTimeout(), + self::articleFrame('a1', 'arrived later'), + ], ['reconnect' => false]); + + $titles = []; + foreach ($ws->stream('reg-1') as $response) { + $titles[] = $response->results[0]->title; + } + $this->assertSame(['arrived later'], $titles); + $this->assertCount(1, $this->connections, 'a quiet connection is not dropped'); + $this->assertSame(1, $this->connections[0]->pings, 'a keepalive ping was sent'); + } + + public function testNoAnswerToTheKeepalivePingIsATransientFailure(): void + { + $ws = $this->ws(fn (int $n) => [self::readTimeout(), self::readTimeout()], ['reconnect' => false]); + + try { + foreach ($ws->stream('reg-1') as $response) { + $this->fail('nothing may be yielded'); + } + $this->fail('expected NewsdataWebSocketError'); + } catch (NewsdataWebSocketError $e) { + $this->assertNotInstanceOf(NewsdataWebSocketAuthError::class, $e); + } + $this->assertSame(1, $this->connections[0]->pings); + } + + public function testWithKeepaliveOffAQuietStreamJustKeepsWaiting(): void + { + $ws = $this->ws(fn (int $n) => [ + self::readTimeout(), + self::readTimeout(), + self::articleFrame('a1', 'eventually'), + ], ['reconnect' => false, 'pingInterval' => null]); + + $titles = []; + foreach ($ws->stream('reg-1') as $response) { + $titles[] = $response->results[0]->title; + } + $this->assertSame(['eventually'], $titles); + $this->assertSame(0, $this->connections[0]->pings); + } + + public function testServerPingsAndPongsAreNotNews(): void + { + $ws = $this->ws(fn (int $n) => [ + new FakeMessage('ping'), + new FakeMessage('pong'), + self::articleFrame('a1', 'news'), + ], ['reconnect' => false]); + + $titles = []; + foreach ($ws->stream('reg-1') as $response) { + $titles[] = $response->results[0]->title; + } + $this->assertSame(['news'], $titles); + } + + // ---- failures that must not be retried (PHP-3) ------------------------- + + /** + * @group no-phrity + */ + public function testWithoutPhrityStreamFailsAtOnce(): void + { + if (class_exists('WebSocket\\Client')) { + $this->markTestSkipped('phrity/websocket is installed here'); + } + $ws = new NewsdataWebSocket($this->api(), ['reconnectDelay' => 0.001]); + + $started = microtime(true); + try { + $ws->stream('reg-1')->current(); + $this->fail('expected NewsdataWebSocketError'); + } catch (NewsdataWebSocketError $e) { + $this->assertStringContainsString('phrity/websocket', $e->getMessage()); + } + $this->assertLessThan(1.0, microtime(true) - $started); + } + + public function testProgrammingErrorsAreNotRetried(): void + { + $ws = $this->ws(function (int $n): array { + if ($n === 1) { + throw new \TypeError('a bug, not a network problem'); + } + return [new NewsdataWebSocketAuthError('test guard: the client reconnected')]; + }); + + $this->expectException(\TypeError::class); + $ws->stream('reg-1')->current(); + } + + // ---- reconnect delay (PHP-7) ------------------------------------------- + + public function testTheReconnectDelayResetsOnConnectButGrowsWhileTheServerRefuses(): void + { + $sleeps = []; + $serverError = self::errorFrame('ServerError', 'temporarily unavailable'); + $ws = $this->ws(function (int $n) use ($serverError): array { + if ($n <= 2) { + throw new \RuntimeException('handshake failed'); // never connects + } + if ($n === 3) { + return [new \RuntimeException('connection reset')]; // connects, then drops + } + if ($n <= 6) { + return [$serverError, FakeMessage::close(1011, 'ServerError')]; // accept, refuse + } + return [self::articleFrame('a1', 'finally')]; + }, [ + 'reconnectDelay' => 0.25, + 'reconnectDelayMax' => 30.0, + 'sleeper' => function (float $seconds) use (&$sleeps): void { + $sleeps[] = $seconds; + }, + ]); + + foreach ($ws->stream('reg-1') as $response) { + if (($response->status ?? null) === 'success') { + break; + } + } + // 0.25, 0.5: failed handshakes double. 0.25: a connect resets it. + // 0.5, 1, 2: refused connections restore the pre-connect delay and double. + $this->assertSame([0.25, 0.5, 0.25, 0.5, 1.0, 2.0], $sleeps); + } + // ---- query management ------------------------------------------------- - public function testRegisterInjectsNewsTypeIntoFilters(): void + public function testRegisterFiltersLeaveNewsTypeToTheClient(): void { - // websocket_register accepts news_type; validation proves it is set. + // news_type is set by get_websocket_register after validation, so a + // caller cannot pass one (it would be silently overwritten). $filters = Constants::FILTERS['websocket_register']; - $this->assertContains('news_type', $filters); + $this->assertNotContains('news_type', $filters); $this->assertContains('q', $filters); // No date or paging filters on a registered query. $this->assertNotContains('from_date', $filters); diff --git a/tests/PaginationTest.php b/tests/PaginationTest.php new file mode 100644 index 0000000..1dec65b --- /dev/null +++ b/tests/PaginationTest.php @@ -0,0 +1,218 @@ + true` follows the + * page cursor and returns one merged response (truncated to `max_result`); + * `'paginate' => true` returns a generator yielding one response per page + * (up to `max_pages`). Version 1 reads totalResults / nextPage, version 2 + * total_results / next_page; the next page is requested with page=. + */ +class PaginationTest extends TestCase +{ + /** @param array $results */ + private static function v2Page(array $results, ?string $next, int $total = 3): array + { + return [200, [], ['status' => 'success', 'total_results' => $total, 'results' => $results, 'next_page' => $next]]; + } + + /** @param array|array $results */ + private static function v1Page($results, ?string $next, int $total = 3): array + { + return [200, [], ['status' => 'success', 'totalResults' => $total, 'results' => $results, 'nextPage' => $next]]; + } + + public function testScrollFollowsNextPageAndMergesUnderTheV2Keys(): void + { + $api = new ScriptedApi([ + self::v2Page([['id' => 1]], 'p2'), + self::v2Page([['id' => 2]], 'p3'), + self::v2Page([['id' => 3]], null), + ]); + + $merged = $api->get_news(['q' => 'x', 'scroll' => true]); + + $this->assertSame([1, 2, 3], array_map(function ($a) { + return $a->id; + }, $merged->results)); + $this->assertSame(3, $merged->total_results); + $this->assertNull($merged->next_page); + $this->assertCount(3, $api->urls); + $this->assertSame('p2', $api->query(1)['page']); + $this->assertSame('p3', $api->query(2)['page']); + $this->assertArrayNotHasKey('scroll', $api->query(0), 'control keys are not sent'); + $this->assertSame([1.0, 1.0], $api->sleeps, 'one second between pages by default'); + } + + public function testScrollTruncatesExactlyToMaxResult(): void + { + $api = new ScriptedApi([ + self::v2Page([['id' => 1], ['id' => 2]], 'p2'), + self::v2Page([['id' => 3], ['id' => 4]], 'p3'), + ]); + + $merged = $api->get_news(['q' => 'x', 'scroll' => true, 'max_result' => 3]); + + $this->assertCount(3, $merged->results); + $this->assertNull($merged->next_page, 'truncated: no cursor to continue from'); + $this->assertCount(2, $api->urls, 'no page beyond the cap is requested'); + } + + public function testScrollOnVersion1UsesTheVersion1Keys(): void + { + $api = new ScriptedApi([ + self::v1Page([['id' => 1]], 'n2'), + self::v1Page([['id' => 2]], null), + ]); + $api->setDecodeJsonAsArray(true); + + $merged = $api->get_latest_news(['q' => 'x', 'scroll' => true]); + + $this->assertIsArray($merged); + $this->assertSame(['totalResults', 'results', 'nextPage'], array_keys($merged)); + $this->assertCount(2, $merged['results']); + $this->assertSame('n2', $api->query(1)['page']); + } + + public function testScrollOnAVersion1CountKeepsTheAggregate(): void + { + $api = new ScriptedApi([ + self::v1Page([['date' => '2026-01-01', 'count' => 5]], 'n2'), + self::v1Page(['total' => 5], null), + ]); + + $merged = $api->get_news_count([ + 'q' => 'x', 'from_date' => '2026-01-01', 'to_date' => '2026-01-02', 'scroll' => true, + ]); + + $this->assertCount(1, $merged->results); + $this->assertSame(5, $merged->aggregate->total); + } + + public function testPaginateYieldsOneResponsePerPageUpToMaxPages(): void + { + $api = new ScriptedApi([ + self::v2Page([['id' => 1]], 'p2'), + self::v2Page([['id' => 2]], 'p3'), + self::v2Page([['id' => 3]], 'p4'), + ]); + $api->setPaginationDelay(0.25); + + $pages = $api->get_news(['q' => 'x', 'paginate' => true, 'max_pages' => 2]); + $this->assertInstanceOf(\Generator::class, $pages); + + $ids = []; + foreach ($pages as $page) { + $ids[] = $page->results[0]->id; + } + $this->assertSame([1, 2], $ids); + $this->assertCount(2, $api->urls, 'stops at max_pages'); + $this->assertSame([0.25], $api->sleeps); + } + + public function testPaginateStopsWhenThereIsNoNextPage(): void + { + $api = new ScriptedApi([ + self::v2Page([['id' => 1]], 'p2'), + self::v2Page([['id' => 2]], null), + ]); + + $count = 0; + foreach ($api->get_market(['q' => 'x', 'paginate' => true]) as $page) { + $count++; + } + $this->assertSame(2, $count); + } + + public function testPaginateStopsAtAVersion1CountAggregate(): void + { + $api = new ScriptedApi([ + self::v1Page([['count' => 1]], 'n2'), + self::v1Page(['total' => 1], 'n3'), + ]); + + $count = 0; + foreach ($api->get_crypto_count([ + 'from_date' => '2026-01-01', 'to_date' => '2026-01-02', 'paginate' => true, + ]) as $page) { + $count++; + } + $this->assertSame(2, $count, 'the aggregate page is the last one'); + } + + public function testRawQueryIsNotRevalidatedOnLaterPages(): void + { + $api = new ScriptedApi([ + self::v2Page([['id' => 1]], 'p2'), + self::v2Page([['id' => 2]], null), + ]); + + $merged = $api->get_news(['raw_query' => 'q=bitcoin&language=en', 'scroll' => true]); + + $this->assertCount(2, $merged->results); + $second = $api->query(1); + $this->assertSame('bitcoin', $second['q']); + $this->assertSame('en', $second['language']); + $this->assertSame('p2', $second['page']); + } + + public function testScrollAndPaginateAreMutuallyExclusive(): void + { + $api = new ScriptedApi([]); + $this->expectException(NewsdataValidationError::class); + $api->get_news(['q' => 'x', 'scroll' => true, 'paginate' => true]); + } + + public function testInvalidParamsFailBeforeTheFirstPage(): void + { + $api = new ScriptedApi([]); + $this->expectException(NewsdataValidationError::class); + // Validation is eager: the call itself throws. + $api->get_news(['size' => 'abc', 'paginate' => true]); + } + + public function testMaxResultMustBeAPositiveInteger(): void + { + $api = new ScriptedApi([]); + $this->expectException(NewsdataValidationError::class); + $api->get_news(['q' => 'x', 'scroll' => true, 'max_result' => 0]); + } + + public function testSourcesAreSinglePage(): void + { + $api = new ScriptedApi([]); + $this->expectException(NewsdataValidationError::class); + $api->get_sources(['scroll' => true]); + } + + // ---- registration (PHP-6) --------------------------------------------- + + public function testRegisterWithRawQuerySendsItsParamsPlusNewsType(): void + { + $api = new ScriptedApi([ + [200, [], ['status' => 'success', 'results' => ['registration_id' => 'reg-1']]], + ]); + + $api->get_websocket_register(['raw_query' => 'q=bitcoin&language=en']); + + $this->assertSame('POST', $api->methods[0]); + $sent = $api->query(0); + $this->assertSame('bitcoin', $sent['q']); + $this->assertSame('en', $sent['language']); + $this->assertSame('news', $sent['news_type']); + } + + public function testRegisterRejectsACallerSuppliedNewsType(): void + { + $api = new ScriptedApi([]); + $this->expectException(NewsdataValidationError::class); + $api->get_websocket_register(['q' => 'x', 'news_type' => 'market']); + } +} diff --git a/tests/ParamValidatorTest.php b/tests/ParamValidatorTest.php index 5821530..5d10c5b 100644 --- a/tests/ParamValidatorTest.php +++ b/tests/ParamValidatorTest.php @@ -95,6 +95,24 @@ public function testCountWithDatesAccepted(): void $this->assertSame(['from_date' => '2024-01-01', 'to_date' => '2024-01-02'], $out); } + public function testCountRawQueryMustCarryBothDates(): void + { + foreach ([['count', 'q=x&from_date=2024-01-01', 'to_date'], ['crypto_count', 'coin=btc', 'from_date']] as [$endpoint, $raw, $missing]) { + try { + ParamValidator::validate($endpoint, ['raw_query' => $raw]); + $this->fail("expected NewsdataValidationError for {$endpoint}"); + } catch (NewsdataValidationError $e) { + $this->assertSame($missing, $e->getParam()); + } + } + } + + public function testCountRawQueryWithBothDatesAccepted(): void + { + $out = ParamValidator::validate('market_count', ['raw_query' => 'q=x&from_date=2024-01-01&to_date=2024-01-02']); + $this->assertSame(['q' => 'x', 'from_date' => '2024-01-01', 'to_date' => '2024-01-02'], $out); + } + public function testRawQueryParsedAndValidated(): void { $out = ParamValidator::validate('latest', ['raw_query' => 'q=foo&country=us']); diff --git a/tests/RetryTest.php b/tests/RetryTest.php new file mode 100644 index 0000000..112ec19 --- /dev/null +++ b/tests/RetryTest.php @@ -0,0 +1,112 @@ + 'success', 'totalResults' => 1, 'results' => [['title' => 'ok']]]; + + private const SLOW_DOWN = ['status' => 'error', 'results' => ['message' => 'slow down', 'code' => 'RateLimitExceeded']]; + + public function testRetryAfterLongerThanBackoffMaxThrowsAtOnce(): void + { + $api = new ScriptedApi([ + [429, ['retry_after' => '615'], self::SLOW_DOWN], + [200, [], self::SUCCESS], + ]); + $api->setRetries(3, 0.0); // retryBackoffMax stays at its 60 s default + + try { + $api->get_latest_news(['q' => 'x']); + $this->fail('expected NewsdataRateLimitError'); + } catch (NewsdataRateLimitError $e) { + $this->assertSame(615, $e->getRetryAfter()); + } + $this->assertCount(1, $api->urls, 'the 615 s wait is left to the caller'); + $this->assertSame([], $api->sleeps, 'nothing may be slept'); + } + + public function testRetryAfterZeroWaitsOneSecond(): void + { + $api = new ScriptedApi([ + [429, ['retry_after' => '0'], self::SLOW_DOWN], + [200, [], self::SUCCESS], + ]); + $api->setRetries(3, 0.0); + + $response = $api->get_latest_news(['q' => 'x']); + + $this->assertSame('ok', $response->results[0]->title); + $this->assertSame([1.0], $api->sleeps, 'Retry-After plus one second'); + } + + public function testShortRetryAfterIsWaitedOutPlusOneSecond(): void + { + $api = new ScriptedApi([ + [429, ['retry_after' => '2'], self::SLOW_DOWN], + [200, [], self::SUCCESS], + ]); + $api->setRetries(3, 0.0); + + $api->get_latest_news(['q' => 'x']); + + $this->assertSame([3.0], $api->sleeps); + } + + public function testRetryAfterExactlyAtTheCapIsStillWaited(): void + { + $api = new ScriptedApi([ + [429, ['retry_after' => '5'], self::SLOW_DOWN], + [200, [], self::SUCCESS], + ]); + $api->setRetries(3, 0.0); + $api->setRetryBackoffMax(5.0); + + $api->get_latest_news(['q' => 'x']); + + $this->assertSame([6.0], $api->sleeps); + } + + public function testWithoutRetryAfterTheBackoffApplies(): void + { + $api = new ScriptedApi([ + [429, [], self::SLOW_DOWN], + [200, [], self::SUCCESS], + ]); + $api->setRetries(3, 0.5); + + $api->get_latest_news(['q' => 'x']); + + $this->assertSame([0.5], $api->sleeps); + } + + public function testTheLastAttemptThrowsWithRetryAfter(): void + { + $api = new ScriptedApi([ + [429, ['retry_after' => '1'], self::SLOW_DOWN], + [429, ['retry_after' => '7'], self::SLOW_DOWN], + ]); + $api->setRetries(2, 0.0); + + try { + $api->get_latest_news(['q' => 'x']); + $this->fail('expected NewsdataRateLimitError'); + } catch (NewsdataRateLimitError $e) { + $this->assertSame(7, $e->getRetryAfter()); + } + $this->assertCount(2, $api->urls); + $this->assertSame([2.0], $api->sleeps); + } +} diff --git a/tests/Support/PhrityStandIns.php b/tests/Support/PhrityStandIns.php new file mode 100644 index 0000000..8db0823 --- /dev/null +++ b/tests/Support/PhrityStandIns.php @@ -0,0 +1,17 @@ +,2:string}> */ + private $script; + + /** @var array */ + public $urls = []; + + /** @var array */ + public $methods = []; + + /** @var array */ + public $sleeps = []; + + /** + * @param array,2:array|string}> $script + * Bodies given as arrays are JSON-encoded. + */ + public function __construct(array $script) + { + parent::__construct('key'); + $this->setRetries(1, 0.0); // tests that exercise retries set their own + $this->script = array_map(function (array $step): array { + [$status, $headers, $body] = $step; + return [$status, $headers, is_string($body) ? $body : (string) json_encode($body)]; + }, $script); + } + + /** @return array{0:int,1:array,2:string} */ + protected function httpGet(string $url, string $method = 'GET'): array + { + $this->urls[] = $url; + $this->methods[] = $method; + if ($this->script === []) { + throw new \LogicException("unexpected request: {$url}"); + } + return array_shift($this->script); + } + + protected function sleepSeconds(float $seconds): void + { + $this->sleeps[] = $seconds; + } + + /** The query parameters of the n-th request (0-based). */ + public function query(int $n): array + { + parse_str((string) parse_url($this->urls[$n], PHP_URL_QUERY), $params); + return $params; + } +}