diff --git a/README.md b/README.md index 1f6f27e..b25e288 100644 --- a/README.md +++ b/README.md @@ -28,18 +28,18 @@ dependency is Jackson for JSON. Thread-safe. io.newsdata newsdataapi - 0.3.0 + 0.4.0 ``` ### Gradle (Kotlin DSL) ```kotlin -implementation("io.newsdata:newsdataapi:0.2.1") +implementation("io.newsdata:newsdataapi:0.4.0") ``` ### Gradle (Groovy DSL) ```groovy -implementation 'io.newsdata:newsdataapi:0.2.1' +implementation 'io.newsdata:newsdataapi:0.4.0' ``` ## Quickstart @@ -141,7 +141,8 @@ for (ArticleV2 a : resp.articlesV2(client.objectMapper())) { | `imageUrl()`, `videoUrl()` | `media().imageUrl()`, `media().videoUrl()` | | `sentiment()`, `sentimentStats()` | `ai().sentiment().label()`, `ai().sentiment().score()` | | `aiTag()`, `aiRegion()`, `aiOrg()` | `ai().tag()`, `ai().region()`, `ai().organization()` | -| — | `ai().summary()`, `fetchedAt()`, `duplicate()`, `coin()`, `marketId()` | +| `aiSummary()` | `ai().summary()` | +| `fetchedAt()`, `duplicate()`, `coin()`, `marketId()` | `fetchedAt()`, `duplicate()`, `coin()`, `marketId()` | A group the API did not send (`source`, `media`, `ai`) is `null`; a list field it did not send is an empty list. `ai().region()` entries are comma-separated @@ -168,6 +169,14 @@ field holds the single notice, and a withheld sentiment carries it in The real-time service is v2 only — there are no v1 WebSocket methods. +v1 articles decode with `resp.articles(client.objectMapper())`. On plans +without the AI add-ons, `ai_tag`, `ai_region` and `ai_org` arrive as the API's +notice string: the list then holds that single notice +(`ArticleV2.isPlanNotice(value)` recognises it), and `sentimentStats()` is +`null`. If the results cannot be decoded at all, `articles()` and +`articlesV2()` throw a `NewsdataException` carrying the decoding error rather +than returning an empty list. + `params` is a `Map`. Use the bundled [`Params`](src/main/java/io/newsdata/api/Params.java) helper for fluent construction — `null` values are dropped automatically so you can chain optional fields without `if`-guards. Values may be `String`, `Number`, `Boolean`, or `Collection` (sent comma-joined). Parameter names are case-insensitive — `qInTitle` and `qintitle` are equivalent. ## Pagination @@ -194,19 +203,19 @@ client.paginate(Endpoint.LATEST, Params.of().with("q", "news")) client.latest(Params.of().with("rawQuery", "q=bitcoin&country=us&language=en")); ``` -`rawQuery` is mutually exclusive with every other parameter and is parsed and validated against the endpoint's allowed keys before the request leaves. +`rawQuery` is mutually exclusive with every other parameter and is parsed and validated against the endpoint's allowed keys before the request leaves; for the v1 count endpoints it must also carry `from_date` and `to_date`. It works with `scrollAll`, `paginate` and `websocketRegister` too: parameters are validated once, and the page cursor (or `news_type`) is added afterwards. ## Client-side validation A `NewsdataValidationException` is thrown — before any HTTP request — 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`. -Booleans for `full_content`, `image`, `video`, and `removeduplicate` are coerced to `"1"`/`"0"`. +Booleans for `full_content`, `image`, `video`, `removeduplicate`, and the version 2 `content` and `remove_duplicate` are coerced to `"1"`/`"0"`. ## Real-time news (WebSocket) @@ -262,12 +271,22 @@ rejection — bad API key or unknown `registration_id`, exhausted API credits, or too many simultaneous devices — throws `NewsdataWebSocketAuthException` 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. That response never reaches your handler: it becomes the exception, +whose message is the server's explanation, `errorCode()` its code and +`responseBody()` the raw 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 `NewsdataWebSocketException` carrying the server's message. + +A quiet stream is not a failure: news can be minutes apart. When nothing +arrives for `pingInterval` (default 20 s) the client sends a ping, and only +when nothing comes back within `pingTimeout` (default 20 s) is the connection +treated as dead and reconnected. **Each delivered article consumes 1 API credit per connected device.** @@ -277,7 +296,7 @@ Catch it like any other client error: try { ws.stream(registrationId, response -> true); } catch (NewsdataWebSocketAuthException e) { - System.err.println("rejected: " + e.getMessage()); + System.err.println("rejected (" + e.errorCode() + "): " + e.getMessage()); } catch (NewsdataWebSocketException e) { System.err.println("stream error: " + e.getMessage()); } @@ -292,6 +311,8 @@ NewsDataApiWebSocket ws = NewsDataApiWebSocket.builder(client) .reconnectDelay(Duration.ofSeconds(1)) // first delay; doubles each retry .reconnectDelayMax(Duration.ofSeconds(30)) // cap on the delay .handshakeTimeout(Duration.ofSeconds(10)) // opening handshake bound + .pingInterval(Duration.ofSeconds(20)) // silence before a keepalive ping; ZERO = off + .pingTimeout(Duration.ofSeconds(20)) // wait for a reply before reconnecting .headers(Map.of("X-Trace", "abc")) // extra handshake headers .build(); ``` @@ -357,7 +378,7 @@ NewsDataApiClient client = NewsDataApiClient.builder() `baseUrl` is the API root **without** a version segment; the default is `https://newsdata.io/api/` and the client adds `1/…` or `2/…` itself. Before 0.3.0 it included the version (`https://newsdata.io/api/1/`), so drop the trailing `1/` if you override it. -Retries cover network errors, HTTP 429, and 5xx. 429 honours the `Retry-After` header (integer seconds or HTTP-date); otherwise backoff is exponential. Auth (401/403) and other 4xx errors are never retried. The API key is redacted from URLs passed to the logger. +Retries cover network errors, HTTP 429, and 5xx. A 429 waits for its `Retry-After` (integer seconds or HTTP-date) plus one second; without the header, backoff is exponential. When `Retry-After` is longer than `retryBackoffMax`, the call throws `NewsdataRateLimitException` at once with `retryAfter()` set, leaving the wait to you. Auth (401/403) and other 4xx errors are never retried. The API key is redacted from URLs passed to the logger and from error messages; a `baseUrl` that is not a valid absolute URL is rejected by `build()`. A 429 that waiting cannot fix is never retried: `NewsdataApiLimitExceededException` means the account's whole credit pool is exhausted, `NewsdataApiKeyLimitExceededException` means this one key hit its own cap while the account may still have credits, and both extend `NewsdataRateLimitException`, so an existing `catch` on that type keeps working. `RegistrationLimitExceeded` is also never retried, but keeps the plain `NewsdataRateLimitException` — it is about real-time registration slots, not credits, and is fixed by deleting a registration. diff --git a/pom.xml b/pom.xml index cedaec5..deec2f2 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ io.newsdata newsdataapi - 0.3.0 + 0.4.0 jar newsdataapi diff --git a/src/main/java/io/newsdata/api/Article.java b/src/main/java/io/newsdata/api/Article.java index e3e4936..beeca44 100644 --- a/src/main/java/io/newsdata/api/Article.java +++ b/src/main/java/io/newsdata/api/Article.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /** * One news article from API v1 of the Newsdata.io API. @@ -16,6 +17,15 @@ * {@code article.getTitle()}. * *

JSON keys use the API's snake_case; component names are camelCase. + * + *

The crypto endpoint fills {@code coin}; the market endpoint fills + * {@code symbol} and {@code marketId}. + * + *

On plans without the AI add-ons the API sends a plain notice string in + * place of some fields: a list field then holds that one notice (see + * {@link ArticleV2#isPlanNotice(String)}) and {@code sentimentStats} is + * {@code null}. A field the API does not send (or sends as {@code null}) is + * {@code null}. */ @JsonIgnoreProperties(ignoreUnknown = true) public record Article( @@ -24,8 +34,8 @@ public record Article( @JsonProperty("link") String link, @JsonProperty("description") String description, @JsonProperty("content") String content, - @JsonProperty("keywords") List keywords, - @JsonProperty("creator") List creator, + @JsonProperty("keywords") @JsonDeserialize(using = NullableStringListDeserializer.class) List keywords, + @JsonProperty("creator") @JsonDeserialize(using = NullableStringListDeserializer.class) List creator, @JsonProperty("video_url") String videoUrl, @JsonProperty("image_url") String imageUrl, @JsonProperty("pubDate") String pubDate, @@ -36,14 +46,37 @@ public record Article( @JsonProperty("source_icon") String sourceIcon, @JsonProperty("source_name") String sourceName, @JsonProperty("language") String language, - @JsonProperty("country") List country, - @JsonProperty("category") List category, - @JsonProperty("ai_tag") List aiTag, - @JsonProperty("ai_region") List aiRegion, - @JsonProperty("ai_org") List aiOrg, + @JsonProperty("country") @JsonDeserialize(using = NullableStringListDeserializer.class) List country, + @JsonProperty("category") @JsonDeserialize(using = NullableStringListDeserializer.class) List category, + @JsonProperty("ai_tag") @JsonDeserialize(using = NullableStringListDeserializer.class) List aiTag, + @JsonProperty("ai_region") @JsonDeserialize(using = NullableStringListDeserializer.class) List aiRegion, + @JsonProperty("ai_org") @JsonDeserialize(using = NullableStringListDeserializer.class) List aiOrg, @JsonProperty("sentiment") String sentiment, - @JsonProperty("sentiment_stats") Map sentimentStats, + @JsonProperty("sentiment_stats") @JsonDeserialize(using = LenientMapDeserializer.class) + Map sentimentStats, @JsonProperty("datatype") String dataType, - @JsonProperty("symbol") List symbol, - @JsonProperty("market_id") List marketId -) {} + @JsonProperty("symbol") @JsonDeserialize(using = NullableStringListDeserializer.class) List symbol, + @JsonProperty("market_id") @JsonDeserialize(using = NullableStringListDeserializer.class) List marketId, + @JsonProperty("fetched_at") String fetchedAt, + @JsonProperty("ai_summary") String aiSummary, + @JsonProperty("duplicate") Boolean duplicate, + @JsonProperty("coin") @JsonDeserialize(using = NullableStringListDeserializer.class) List coin +) { + /** + * The constructor from before {@code fetchedAt}, {@code aiSummary}, + * {@code duplicate} and {@code coin} were added; those four are + * {@code null}. Kept so code that builds articles by hand still compiles. + */ + public Article(String articleId, String title, String link, String description, String content, + List keywords, List creator, String videoUrl, String imageUrl, + String pubDate, String pubDateTZ, String sourceId, Integer sourcePriority, String sourceUrl, + String sourceIcon, String sourceName, String language, List country, + List category, List aiTag, List aiRegion, List aiOrg, + String sentiment, Map sentimentStats, String dataType, List symbol, + List marketId) { + this(articleId, title, link, description, content, keywords, creator, videoUrl, imageUrl, + pubDate, pubDateTZ, sourceId, sourcePriority, sourceUrl, sourceIcon, sourceName, + language, country, category, aiTag, aiRegion, aiOrg, sentiment, sentimentStats, + dataType, symbol, marketId, null, null, null, null); + } +} diff --git a/src/main/java/io/newsdata/api/Constants.java b/src/main/java/io/newsdata/api/Constants.java index 9998f25..4abefb8 100644 --- a/src/main/java/io/newsdata/api/Constants.java +++ b/src/main/java/io/newsdata/api/Constants.java @@ -12,7 +12,7 @@ /** * Static configuration: base URL, endpoint paths, HTTP defaults, and the * per-endpoint accepted-parameter sets. Mirrors the server-side filter - * mapping and the official Python/PHP/Node/Go/Dart clients. + * mapping. * *

Parameter names are stored lowercase here; user-supplied keys are * lowercased before validation (the API is case-insensitive, so @@ -102,6 +102,12 @@ private Constants() {} /** Bound on the opening handshake. */ public static final Duration WS_HANDSHAKE_TIMEOUT = Duration.ofSeconds(10); + /** Keepalive: silence after which the client sends a ping. */ + public static final Duration WS_PING_INTERVAL = Duration.ofSeconds(20); + + /** Keepalive: how long to wait for anything after a ping before the connection counts as dead. */ + public static final Duration WS_PING_TIMEOUT = Duration.ofSeconds(20); + /** * Error codes on a 429 that waiting cannot fix, so they are never retried. * {@code ApiLimitExceeded} and {@code ApiKeyLimitExceeded} mean the API @@ -294,14 +300,15 @@ NewsdataRateLimitException create(String message, int statusCode, String respons // 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 websocketRegister, not by the caller. + // `news_type` is not accepted from the caller: websocketRegister + // adds it after validation (so it also works with rawQuery). Map.entry("websocket_register", Set.of( "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" )), Map.entry("websocket_fetch", Set.of()), Map.entry("websocket_delete", Set.of("registration_id")) diff --git a/src/main/java/io/newsdata/api/LenientMapDeserializer.java b/src/main/java/io/newsdata/api/LenientMapDeserializer.java new file mode 100644 index 0000000..78969f5 --- /dev/null +++ b/src/main/java/io/newsdata/api/LenientMapDeserializer.java @@ -0,0 +1,32 @@ +package io.newsdata.api; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.JsonNode; + +/** + * Reads a JSON object as a {@code Map}, and anything else as {@code null}. + * + *

On plans without the AI add-ons the API replaces object fields such as + * {@code sentiment_stats} with a plain "not in your plan" notice string. Plain + * map deserialization fails on that and loses the whole page; this reads the + * notice as "no data" instead. + * + *

Package-private: it is an implementation detail of {@link Article}. + */ +final class LenientMapDeserializer extends JsonDeserializer> { + + @Override + public Map deserialize(JsonParser parser, DeserializationContext context) + throws IOException { + JsonNode node = parser.readValueAsTree(); + if (node == null || !node.isObject()) return null; + return context.readTreeAsValue(node, + context.getTypeFactory().constructMapType(LinkedHashMap.class, String.class, Object.class)); + } +} diff --git a/src/main/java/io/newsdata/api/NewsDataApiClient.java b/src/main/java/io/newsdata/api/NewsDataApiClient.java index 522c184..ffb7624 100644 --- a/src/main/java/io/newsdata/api/NewsDataApiClient.java +++ b/src/main/java/io/newsdata/api/NewsDataApiClient.java @@ -79,7 +79,7 @@ private NewsDataApiClient(Builder b) { throw new NewsdataValidationException("apiKey must be a non-empty string", "apiKey"); } this.apiKey = b.apiKey; - this.baseUrl = b.baseUrl.endsWith("/") ? b.baseUrl : b.baseUrl + "/"; + this.baseUrl = checkedBaseUrl(b.baseUrl); this.timeout = b.timeout; this.maxRetries = Math.max(1, b.maxRetries); this.retryBackoff = b.retryBackoff; @@ -241,10 +241,13 @@ public NewsdataResponse countCryptoV2(Map params) { * the existing id is in its response body. */ public NewsdataResponse websocketRegister(Map params) { - Map withType = new LinkedHashMap<>( - params == null ? Map.of() : params); - withType.put("news_type", Constants.WS_NEWS_TYPE); - return request(Endpoint.WEBSOCKET_REGISTER.key(), withType); + String endpoint = Endpoint.WEBSOCKET_REGISTER.key(); + // news_type names the feed; it is added after validation, so a + // rawQuery (which must be the only caller parameter) works too. + Map encoded = new LinkedHashMap<>( + Validator.validateAndEncode(endpoint, params == null ? Map.of() : params)); + encoded.put("news_type", Constants.WS_NEWS_TYPE); + return send(endpoint, encoded); } /** @@ -290,12 +293,14 @@ public NewsdataResponse scrollAll(Endpoint endpoint, Map params, throw new NewsdataValidationException( "scrollAll is not supported for the sources endpoint"); } - Map req = new LinkedHashMap<>(params); + // Validated once: later pages only add the cursor (a rawQuery must stay + // the only caller parameter, so it cannot be validated again with it). + Map req = new LinkedHashMap<>(Validator.validateAndEncode(endpoint.key(), params)); ArrayNode merged = objectMapper.createArrayNode(); NewsdataResponse last = null; int total = 0; for (;;) { - NewsdataResponse resp = request(endpoint.key(), req); + NewsdataResponse resp = send(endpoint.key(), req); last = resp; total = resp.totalResults() != 0 ? resp.totalResults() : total; JsonNode results = resp.results(); @@ -329,8 +334,10 @@ public Stream paginate(Endpoint endpoint, Map throw new NewsdataValidationException( "paginate is not supported for the sources endpoint"); } + // Validated once, before the first page; later pages only add the cursor. + Map validated = Validator.validateAndEncode(endpoint.key(), params); Iterator it = new Iterator<>() { - private final Map req = new LinkedHashMap<>(params); + private final Map req = new LinkedHashMap<>(validated); private NewsdataResponse next; private boolean done = false; private boolean primed = false; @@ -355,8 +362,14 @@ public NewsdataResponse next() { return out; } + private boolean fetched = false; + private void advance() { - NewsdataResponse resp = request(endpoint.key(), req); + // Wait between pages, only once the caller asks for the next + // one: a page is handed over as soon as it arrives. + if (fetched) sleep(paginationDelay); + fetched = true; + NewsdataResponse resp = send(endpoint.key(), req); next = resp; // Count endpoints return an object on the final page. JsonNode results = resp.results(); @@ -370,7 +383,6 @@ private void advance() { return; } req.put("page", nextPage); - sleep(paginationDelay); } }; return StreamSupport.stream( @@ -380,9 +392,14 @@ private void advance() { // ---- internals ------------------------------------------------------- - /** Visible for tests. */ + /** Validate {@code params} and send the request. Visible for tests. */ NewsdataResponse request(String endpoint, Map params) { - Map encoded = Validator.validateAndEncode(endpoint, params); + return send(endpoint, Validator.validateAndEncode(endpoint, params)); + } + + /** Send already-validated, encoded parameters, with retries. */ + private NewsdataResponse send(String endpoint, Map validated) { + Map encoded = new LinkedHashMap<>(validated); encoded.put("apikey", apiKey); String path = Constants.ENDPOINT_PATHS.get(endpoint); String url = baseUrl + path + "?" + buildQuery(encoded); @@ -392,10 +409,18 @@ NewsdataResponse request(String endpoint, Map params) { Exception last = null; for (int attempt = 1; attempt <= maxRetries; attempt++) { log("info", method + " " + logUrl + " (attempt " + attempt + "/" + maxRetries + ")"); + URI uri; + try { + uri = URI.create(url); + } catch (IllegalArgumentException e) { + // The message quotes the URL, API key included. + throw new NewsdataValidationException( + "invalid request URL: " + redactApiKey(String.valueOf(e.getMessage())), "baseUrl"); + } HttpResponse resp; try { HttpRequest req = HttpRequest.newBuilder() - .uri(URI.create(url)) + .uri(uri) .timeout(timeout) .header("Accept", "application/json") .method(method, HttpRequest.BodyPublishers.noBody()) @@ -403,10 +428,12 @@ NewsdataResponse request(String endpoint, Map params) { resp = httpClient.send(req, BodyHandlers.ofString()); } catch (IOException e) { last = e; + // e.g. "java.net.ConnectException": some causes carry no message. + String cause = redactApiKey(e.toString()); if (attempt >= maxRetries) { - throw new NewsdataNetworkException("network error after " + maxRetries + " attempts: " + e.getMessage(), e); + throw new NewsdataNetworkException("network error after " + maxRetries + " attempts: " + cause, e); } - log("warn", "network error: " + e.getMessage()); + log("warn", "network error: " + cause); sleep(backoff(attempt)); continue; } catch (InterruptedException e) { @@ -453,11 +480,19 @@ NewsdataResponse request(String endpoint, Map params) { if (quotaError != null) { throw quotaError.create(message, 429, body, retryAfter); } - if (attempt >= maxRetries) { + // A Retry-After longer than retryBackoffMax is left to the caller. + boolean waitTooLong = retryAfter * 1000L > retryBackoffMax.toMillis(); + if (attempt >= maxRetries || waitTooLong) { throw new NewsdataRateLimitException(message, 429, body, retryAfter); } - Duration wait = retryAfter > 0 ? Duration.ofSeconds(retryAfter) : backoff(attempt); - log("warn", "429 rate limit; sleeping " + wait.toMillis() + "ms"); + // Retry-After is in whole seconds: one second more keeps the retry + // from arriving just before the limit resets. Without a usable + // header, the exponential backoff applies. + boolean hasRetryAfter = retryAfter > 0 || resp.headers().firstValue("retry-after") + .map(v -> v.trim().equals("0")).orElse(false); + Duration wait = hasRetryAfter ? Duration.ofSeconds(retryAfter + 1L) : backoff(attempt); + log("warn", "429 rate limit (attempt " + attempt + "/" + maxRetries + "); sleeping " + + wait.toMillis() + "ms"); sleep(wait); continue; } @@ -482,6 +517,19 @@ NewsdataResponse request(String endpoint, Map params) { throw new NewsdataException("request to " + endpoint + " did not complete (maxRetries=" + maxRetries + ", lastError=" + last + ")"); } + /** The base URL, ending with a slash; rejects one that is not an absolute URL. */ + private static String checkedBaseUrl(String baseUrl) { + String normalized = baseUrl == null ? "" : (baseUrl.endsWith("/") ? baseUrl : baseUrl + "/"); + try { + if (!URI.create(normalized).isAbsolute()) { + throw new IllegalArgumentException("not an absolute URL: " + normalized); + } + } catch (IllegalArgumentException e) { + throw new NewsdataValidationException("invalid baseUrl: " + e.getMessage(), "baseUrl"); + } + return normalized; + } + private Duration backoff(int attempt) { long ms = retryBackoff.toMillis() * (long) Math.pow(2, attempt - 1); long capped = ms > retryBackoffMax.toMillis() || ms <= 0 ? retryBackoffMax.toMillis() : ms; diff --git a/src/main/java/io/newsdata/api/NewsDataApiWebSocket.java b/src/main/java/io/newsdata/api/NewsDataApiWebSocket.java index 5c4f199..e865d6b 100644 --- a/src/main/java/io/newsdata/api/NewsDataApiWebSocket.java +++ b/src/main/java/io/newsdata/api/NewsDataApiWebSocket.java @@ -6,6 +6,7 @@ import java.net.http.HttpClient; import java.net.http.WebSocket; import java.net.http.WebSocketHandshakeException; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.Map; @@ -14,6 +15,7 @@ import java.util.concurrent.CompletionStage; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Predicate; @@ -34,7 +36,7 @@ * wrapped {@link NewsDataApiClient}: * *

{@code
- * NewsDataApiClient client = NewsDataApiClient.builder(apiKey).build();
+ * NewsDataApiClient client = NewsDataApiClient.builder().apiKey(apiKey).build();
  * try (NewsDataApiWebSocket ws = new NewsDataApiWebSocket(client)) {
  *     NewsdataResponse registered = ws.websocketRegister(Params.of().with("q", "bitcoin"));
  *     String id = registered.results().path("registration_id").asText();
@@ -53,10 +55,17 @@
  * reconnected automatically with a capped exponential backoff; build with
  * {@code reconnect(false)} to stop on the first disconnect. A permanent
  * rejection always throws {@link NewsdataWebSocketAuthException} and is never
- * retried.
+ * retried. The error response the server sends with a refusal never reaches
+ * the handler: it becomes the exception's message, {@code errorCode()} and
+ * {@code responseBody()}.
+ *
+ * 

A quiet stream is not a failure: when nothing arrives for + * {@code pingInterval} the client sends a ping, and only when nothing comes + * back within {@code pingTimeout} is the connection treated as dead and + * reconnected. * *

Closing the instance (or leaving the try-with-resources block) stops an - * in-flight {@link #stream}. + * in-flight {@link #stream} at once, from any thread. * *

A single {@code stream} call must not be shared between threads. */ @@ -65,16 +74,26 @@ public final class NewsDataApiWebSocket implements AutoCloseable { /** Sentinel queued when the connection closes normally. */ private static final String NORMAL_CLOSE = new String("__normal_close__"); + /** Sentinel queued when the server answers a ping. */ + private static final Object PONG = new Object(); + + /** Sentinel queued by {@link #close()} to wake a waiting stream. */ + private static final Object STOP = new Object(); + private final NewsDataApiClient client; private final String baseUrl; private final boolean reconnect; private final Duration reconnectDelay; private final Duration reconnectDelayMax; private final Duration handshakeTimeout; + private final Duration pingInterval; + private final Duration pingTimeout; private final Map headers; private final AtomicBoolean closed = new AtomicBoolean(false); private volatile WebSocket active; + /** The queue the in-flight stream reads; {@link #close()} wakes it. */ + private volatile LinkedBlockingQueue activeQueue; /** Construct with the defaults; equivalent to {@code builder(client).build()}. */ public NewsDataApiWebSocket(NewsDataApiClient client) { @@ -91,6 +110,8 @@ private NewsDataApiWebSocket(Builder b) { this.reconnectDelay = b.reconnectDelay; this.reconnectDelayMax = b.reconnectDelayMax; this.handshakeTimeout = b.handshakeTimeout; + this.pingInterval = b.pingInterval; + this.pingTimeout = b.pingTimeout; this.headers = Map.copyOf(b.headers); } @@ -107,6 +128,8 @@ public static final class Builder { private Duration reconnectDelay = Constants.WS_RECONNECT_DELAY; private Duration reconnectDelayMax = Constants.WS_RECONNECT_DELAY_MAX; private Duration handshakeTimeout = Constants.WS_HANDSHAKE_TIMEOUT; + private Duration pingInterval = Constants.WS_PING_INTERVAL; + private Duration pingTimeout = Constants.WS_PING_TIMEOUT; private Map headers = Map.of(); private Builder(NewsDataApiClient client) { @@ -128,6 +151,18 @@ private Builder(NewsDataApiClient client) { /** Bound on the opening handshake. */ public Builder handshakeTimeout(Duration v) { this.handshakeTimeout = v; return this; } + /** + * Keepalive: after this long without a message the client sends a + * ping. Default 20 seconds; {@link Duration#ZERO} turns keepalive off. + */ + public Builder pingInterval(Duration v) { this.pingInterval = v; return this; } + + /** + * Keepalive: how long to wait for anything after a ping before the + * connection counts as dead and is reconnected. Default 20 seconds. + */ + public Builder pingTimeout(Duration v) { this.pingTimeout = v; return this; } + /** Extra HTTP headers for the opening handshake. */ public Builder headers(Map v) { this.headers = v; return this; } @@ -193,24 +228,23 @@ public void stream(String registrationId, Predicate handler) { try { while (!closed.get()) { - boolean closedNormally; + Outcome outcome; try { - closedNormally = runOnce(url, logUrl, handler); + outcome = runOnce(url, logUrl, handler); } catch (StopStream stop) { return; } if (closed.get()) return; - if (closedNormally && !reconnect) return; if (!reconnect) return; + // A connection the server did not refuse resets the delay; a + // refused one keeps backing off. + if (outcome == Outcome.ACCEPTED) delay = reconnectDelay; // Transient failure, or a normal close with reconnect enabled: // wait (capped exponential backoff) and reconnect. - try { - Thread.sleep(delay.toMillis()); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } + client.logFromWebSocket("warn", + "reconnecting to " + logUrl + " in " + delay.toMillis() + "ms"); + if (!pause(delay)) return; delay = nextDelay(delay); } } finally { @@ -218,102 +252,206 @@ public void stream(String registrationId, Predicate handler) { } } + /** How one connection ended, for the reconnect delay. */ + private enum Outcome { + /** The handshake failed. */ + NOT_OPENED, + /** The connection opened and the server did not refuse it. */ + ACCEPTED, + /** The connection opened, then the server sent an error response. */ + REFUSED + } + + /** + * Sleep before a reconnect; {@link #close()} or an interrupt ends the wait + * early. + * + * @return {@code false} when the stream should stop instead + */ + private boolean pause(Duration delay) { + LinkedBlockingQueue wake = new LinkedBlockingQueue<>(); + activeQueue = wake; + if (closed.get()) return false; + try { + return wake.poll(delay.toMillis(), TimeUnit.MILLISECONDS) == null && !closed.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + /** * Hold a single connection open until it drops or the handler stops it. * - * @return {@code true} when the connection closed normally - * @throws StopStream when the handler asked to stop + * @return how the connection ended + * @throws StopStream when the handler or {@link #close()} stopped the stream */ - private boolean runOnce(String url, String logUrl, Predicate handler) { + private Outcome runOnce(String url, String logUrl, Predicate handler) { LinkedBlockingQueue queue = new LinkedBlockingQueue<>(); + activeQueue = queue; + if (closed.get()) throw new StopStream(); + WebSocket socket; try { - HttpClient http = client.httpClient(); - WebSocket.Builder wsBuilder = http.newWebSocketBuilder() - .connectTimeout(handshakeTimeout); - headers.forEach(wsBuilder::header); - socket = wsBuilder.buildAsync(URI.create(url), new Listener(queue)) - .get(handshakeTimeout.toMillis() + 1_000, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new StopStream(); + socket = openSocket(url, queue); + } catch (StopStream stop) { + throw stop; } catch (Exception e) { - handleFailure(unwrap(e), logUrl); - return false; + if (closed.get()) throw new StopStream(); + handleFailure(unwrap(e), logUrl, null); + return Outcome.NOT_OPENED; } active = socket; + if (closed.get()) { // close() raced the end of the handshake + socket.abort(); + throw new StopStream(); + } client.logFromWebSocket("info", "connected to " + logUrl); socket.request(1); + boolean keepalive = isPositive(pingInterval); + boolean awaitingPong = false; + // The error response the server sends right before it closes a refused + // connection. Never handed to the handler: raised with that close. + Refusal refusal = null; + while (true) { Object item; try { - item = queue.take(); + if (!keepalive) { + item = queue.take(); + } else { + Duration wait = awaitingPong && isPositive(pingTimeout) ? pingTimeout : pingInterval; + item = queue.poll(wait.toMillis(), TimeUnit.MILLISECONDS); + } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new StopStream(); } - if (closed.get()) throw new StopStream(); + if (closed.get() || item == STOP) throw new StopStream(); + + if (item == null) { + // Nothing arrived for a while. That is not a failure; check the + // connection is alive with a ping. + if (awaitingPong) { + socket.abort(); + handleFailure(new KeepaliveTimeout(), logUrl, refusal); + return refusal != null ? Outcome.REFUSED : Outcome.ACCEPTED; + } + socket.sendPing(ByteBuffer.allocate(0)); + awaitingPong = true; + continue; + } + // Anything at all (a pong included) shows the connection is alive. + awaitingPong = false; + if (item == PONG) continue; if (item == NORMAL_CLOSE) { - return true; + return refusal != null ? Outcome.REFUSED : Outcome.ACCEPTED; } if (item instanceof Throwable) { - handleFailure((Throwable) item, logUrl); - return false; + handleFailure((Throwable) item, logUrl, refusal); + return refusal != null ? Outcome.REFUSED : Outcome.ACCEPTED; + } + + String text = (String) item; + JsonNode node = parse(text); + if (node == null) continue; // skip malformed frames + if ("error".equals(node.path("status").asText(null))) { + refusal = new Refusal(text, node); + continue; + } + if (!handler.test(toResponse(node))) { + throw new StopStream(); } + } + } - NewsdataResponse response = parse((String) item); - if (response == null) continue; // skip malformed frames - if (!handler.test(response)) { + /** + * Open one connection, waiting at most the handshake timeout. The wait + * checks {@link #close()} often, so a close during the handshake returns + * at once (a socket that opens later is aborted). + */ + private WebSocket openSocket(String url, LinkedBlockingQueue queue) throws Exception { + HttpClient http = client.httpClient(); + WebSocket.Builder wsBuilder = http.newWebSocketBuilder() + .connectTimeout(handshakeTimeout); + headers.forEach(wsBuilder::header); + CompletableFuture pending = wsBuilder.buildAsync(URI.create(url), new Listener(queue)); + + long deadline = System.nanoTime() + handshakeTimeout.toNanos() + TimeUnit.SECONDS.toNanos(1); + while (true) { + if (closed.get()) { + pending.thenAccept(WebSocket::abort); + throw new StopStream(); + } + try { + return pending.get(50, TimeUnit.MILLISECONDS); + } catch (TimeoutException e) { + if (System.nanoTime() > deadline) { + pending.thenAccept(WebSocket::abort); + throw new TimeoutException("handshake timed out"); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + pending.thenAccept(WebSocket::abort); throw new StopStream(); } } } /** Parse one frame, returning null when it isn't a JSON object. */ - private NewsdataResponse parse(String message) { + private JsonNode parse(String message) { try { JsonNode node = client.objectMapper().readTree(message); - if (node == null || !node.isObject()) return null; - return new NewsdataResponse( - node.path("status").asText(null), - NewsDataApiClient.totalResultsOf(node), - node.get("results"), - NewsDataApiClient.nextPageOf(node), - null); + return node != null && node.isObject() ? node : null; } catch (IOException e) { return null; } } + private static NewsdataResponse toResponse(JsonNode node) { + return new NewsdataResponse( + node.path("status").asText(null), + NewsDataApiClient.totalResultsOf(node), + node.get("results"), + NewsDataApiClient.nextPageOf(node), + null); + } + + private static boolean isPositive(Duration d) { + return d != null && !d.isZero() && !d.isNegative(); + } + /** * Classify a connection failure. * - *

The server always accepts the handshake and then closes with code - * 1008 on a permanent failure — {@code invalid credentials or registration - * not found}, {@code api limit reached}, or {@code device limit reached}. - * Those always throw. Every other close code, including 1013 - * ({@code send timeout} — this client read too slowly), is transient: it - * throws only when reconnect is disabled, otherwise it is logged so the - * caller backs off and retries. The handshake-status check is defensive, - * for proxies in front of the documented server. + *

On a refusal the server accepts the handshake, sends one error + * response ({@code {"status":"error","results":{"message":...,"code":...}}}) + * and closes. Close 1008 is permanent: bad API key or unknown + * registration_id ({@code Unauthorized}, {@code InvalidRequest}), exhausted + * credits ({@code ApiLimitExceeded}, {@code ApiKeyLimitExceeded}), or too + * many devices on one registration_id ({@code DeviceLimitExceeded}); the + * close reason is that bare code. Those always throw. Every other close + * code — 1011 (server error), 1013 (the client read too slowly) — is + * transient: it throws only when reconnect is disabled, otherwise it is + * logged so the caller backs off and retries. The handshake-status check + * is defensive, for proxies in front of the server. */ - private void handleFailure(Throwable err, String logUrl) { - NewsdataWebSocketAuthException auth = permanentAuthError(err); + private void handleFailure(Throwable err, String logUrl, Refusal refusal) { + NewsdataWebSocketAuthException auth = permanentAuthError(err, refusal); if (auth != null) throw auth; - if (!reconnect) throw transientError(err); - client.logFromWebSocket("warn", - "connection to " + logUrl + " failed (" + err + "); reconnecting"); + if (!reconnect) throw transientError(err, refusal); + client.logFromWebSocket("warn", "connection to " + logUrl + " failed (" + + (refusal != null && refusal.message != null ? refusal.message : err) + ")"); } /** * The auth error to throw if {@code err} is permanent, else null. Close - * code 1008 is the documented permanent signal; the handshake check is - * defensive. + * code 1008 is the permanent signal; the handshake check is defensive. */ - private static NewsdataWebSocketAuthException permanentAuthError(Throwable err) { + private static NewsdataWebSocketAuthException permanentAuthError(Throwable err, Refusal refusal) { if (err instanceof WebSocketHandshakeException) { int status = ((WebSocketHandshakeException) err).getResponse().statusCode(); if (status == 401 || status == 403) { @@ -322,13 +460,24 @@ private static NewsdataWebSocketAuthException permanentAuthError(Throwable err) return null; } if (err instanceof PolicyViolation) { - return new NewsdataWebSocketAuthException(err.getMessage(), err); + String reason = ((PolicyViolation) err).reason; + String message = refusal != null && refusal.message != null ? refusal.message + : (reason.isEmpty() ? "connection rejected" : reason); + String code = refusal != null && refusal.code != null ? refusal.code + : (reason.isEmpty() ? null : reason); + return new NewsdataWebSocketAuthException(message, err, + refusal != null ? refusal.raw : null, code); } return null; } /** Wrap a transient failure; used only when reconnect is disabled. */ - private static NewsdataWebSocketException transientError(Throwable err) { + private static NewsdataWebSocketException transientError(Throwable err, Refusal refusal) { + if (refusal != null) { + return new NewsdataWebSocketException( + refusal.message != null ? refusal.message : "connection closed", + err, refusal.raw, refusal.code); + } if (err instanceof WebSocketHandshakeException) { int status = ((WebSocketHandshakeException) err).getResponse().statusCode(); return new NewsdataWebSocketException("handshake failed (HTTP " + status + ")", err); @@ -336,6 +485,9 @@ private static NewsdataWebSocketException transientError(Throwable err) { if (err instanceof AbnormalClose) { return new NewsdataWebSocketException("connection closed", err); } + if (err instanceof KeepaliveTimeout) { + return new NewsdataWebSocketException(err.getMessage(), err); + } return new NewsdataWebSocketException("connection error: " + err, err); } @@ -360,15 +512,39 @@ private void closeActive() { } } - /** Close the active connection, ending any in-flight {@link #stream}. */ + /** + * Close the active connection, ending any in-flight {@link #stream} at + * once — from any thread, also while it connects or waits to reconnect. + */ @Override public void close() { closed.set(true); + LinkedBlockingQueue queue = activeQueue; + if (queue != null) queue.offer(STOP); WebSocket socket = active; if (socket != null) socket.abort(); active = null; } + /** The server's error response, kept until the close that follows it. */ + private static final class Refusal { + final String raw; + final String message; + final String code; + + Refusal(String raw, JsonNode node) { + this.raw = raw; + JsonNode results = node.path("results"); + this.message = results.isTextual() ? results.asText() + : textOrNull(results.path("message")); + this.code = textOrNull(results.path("code")); + } + + private static String textOrNull(JsonNode node) { + return node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + } + /** Bridges the callback listener onto the blocking queue the stream reads. */ private final class Listener implements WebSocket.Listener { private final LinkedBlockingQueue queue; @@ -389,13 +565,19 @@ public CompletionStage onText(WebSocket webSocket, CharSequence data, boolean return null; } + @Override + public CompletionStage onPong(WebSocket webSocket, ByteBuffer message) { + queue.offer(PONG); + webSocket.request(1); + return null; + } + @Override public CompletionStage onClose(WebSocket webSocket, int statusCode, String reason) { if (statusCode == WebSocket.NORMAL_CLOSURE) { queue.offer(NORMAL_CLOSE); } else if (statusCode == Constants.WS_POLICY_VIOLATION) { - queue.offer(new PolicyViolation( - reason == null || reason.isEmpty() ? "connection rejected" : reason)); + queue.offer(new PolicyViolation(reason == null ? "" : reason)); } else { queue.offer(new AbnormalClose("connection closed (" + statusCode + ")")); } @@ -408,11 +590,16 @@ public void onError(WebSocket webSocket, Throwable error) { } } - /** Close code 1008 — a permanent rejection. */ + /** Close code 1008 — a permanent rejection; the reason is the bare error code. */ private static final class PolicyViolation extends RuntimeException { private static final long serialVersionUID = 1L; - PolicyViolation(String message) { super(message); } + final String reason; + + PolicyViolation(String reason) { + super(reason.isEmpty() ? "connection rejected" : reason); + this.reason = reason; + } } /** Any other non-normal close — transient. */ @@ -422,6 +609,13 @@ private static final class AbnormalClose extends RuntimeException { AbnormalClose(String message) { super(message); } } + /** Nothing came back after a keepalive ping: the connection is dead. Transient. */ + private static final class KeepaliveTimeout extends RuntimeException { + private static final long serialVersionUID = 1L; + + KeepaliveTimeout() { super("connection lost: no reply to the keepalive ping"); } + } + /** Internal control-flow marker: the handler (or close()) stopped the stream. */ private static final class StopStream extends RuntimeException { private static final long serialVersionUID = 1L; diff --git a/src/main/java/io/newsdata/api/NewsdataResponse.java b/src/main/java/io/newsdata/api/NewsdataResponse.java index 33796c7..d6a5f0a 100644 --- a/src/main/java/io/newsdata/api/NewsdataResponse.java +++ b/src/main/java/io/newsdata/api/NewsdataResponse.java @@ -6,9 +6,12 @@ import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.newsdata.api.exception.NewsdataException; + /** * Top-level envelope returned by every endpoint. * @@ -16,7 +19,8 @@ * varies by endpoint: *
    *
  • news endpoints (latest, archive, crypto, market) return an array of articles; - *
  • count endpoints return an aggregate object on the final page. + *
  • the count endpoints return one aggregate object when called without an + * {@code interval}, and an array of per-interval counts with one. *
* Use {@link #articles(ObjectMapper)} / {@link #articlesV2(ObjectMapper)} / * {@link #aggregate(ObjectMapper)} to decode it into a typed shape. @@ -62,13 +66,16 @@ public NewsdataResponse(String status, int totalResults, JsonNode results, Strin * Decode {@code results} as a list of articles. Returns an empty list * when {@code results} is empty or not an array (e.g. a count endpoint's * aggregate page). + * + * @throws NewsdataException when the articles cannot be decoded; the + * decoding error is the cause */ public List
articles(ObjectMapper mapper) { if (results == null || !results.isArray()) return Collections.emptyList(); try { return mapper.treeToValue(results, mapper.getTypeFactory().constructCollectionType(List.class, Article.class)); - } catch (Exception e) { - return Collections.emptyList(); + } catch (JsonProcessingException | IllegalArgumentException e) { + throw new NewsdataException("could not decode the articles: " + e.getMessage(), e); } } @@ -84,13 +91,15 @@ public List
articles(ObjectMapper mapper) { * * @param mapper the mapper to decode with * @return the articles, never {@code null} + * @throws NewsdataException when the articles cannot be decoded; the + * decoding error is the cause */ public List articlesV2(ObjectMapper mapper) { if (results == null || !results.isArray()) return Collections.emptyList(); try { return mapper.treeToValue(results, mapper.getTypeFactory().constructCollectionType(List.class, ArticleV2.class)); - } catch (Exception e) { - return Collections.emptyList(); + } catch (JsonProcessingException | IllegalArgumentException e) { + throw new NewsdataException("could not decode the articles: " + e.getMessage(), e); } } diff --git a/src/main/java/io/newsdata/api/NullableStringListDeserializer.java b/src/main/java/io/newsdata/api/NullableStringListDeserializer.java new file mode 100644 index 0000000..e599725 --- /dev/null +++ b/src/main/java/io/newsdata/api/NullableStringListDeserializer.java @@ -0,0 +1,34 @@ +package io.newsdata.api; + +import java.io.IOException; +import java.util.List; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; + +/** + * Reads a {@code List} that the API may also send as a single string, + * like {@link StringListDeserializer}, but leaves an absent or {@code null} + * field {@code null}. + * + *

Used by the v1 {@link Article}, whose list fields have always been + * {@code null} when the API does not send them. On plans without the AI + * add-ons the API replaces fields such as {@code ai_tag} with a "not in your + * plan" notice string; that becomes a one-element list, which + * {@link ArticleV2#isPlanNotice(String)} recognises. + * + *

Package-private: it is an implementation detail of {@link Article}. + */ +final class NullableStringListDeserializer extends JsonDeserializer> { + + private static final StringListDeserializer LISTS = new StringListDeserializer(); + + @Override + public List deserialize(JsonParser parser, DeserializationContext context) + throws IOException { + return LISTS.deserialize(parser, context); + } + + // getNullValue is not overridden: an absent or null field stays null. +} diff --git a/src/main/java/io/newsdata/api/Validator.java b/src/main/java/io/newsdata/api/Validator.java index e8a7630..8823d26 100644 --- a/src/main/java/io/newsdata/api/Validator.java +++ b/src/main/java/io/newsdata/api/Validator.java @@ -13,8 +13,8 @@ import io.newsdata.api.exception.NewsdataValidationException; /** - * Client-side parameter validation and normalization, mirroring the official - * Python/PHP/Node/Go/Dart clients: + * Client-side parameter validation and normalization, before a request is + * sent: * *

    *
  • keys are lowercased (the API is case-insensitive); @@ -65,21 +65,13 @@ static Map validateAndEncode(String endpoint, Map(); @@ -114,6 +106,22 @@ static Map validateAndEncode(String endpoint, Map values) { + if (!Constants.REQUIRES_DATE_RANGE.contains(endpoint)) return; + for (var required : List.of("from_date", "to_date")) { + var v = values.get(required); + if (v == null || (v instanceof String s && s.isEmpty())) { + throw new NewsdataValidationException( + required + " is required for the " + endpoint + " endpoint", + required); + } + } + } + private static String coerce(String name, Object value) { if (Constants.BOOL_PARAMS.contains(name)) return coerceBool(name, value); if (Constants.INT_PARAMS.contains(name)) return coerceInt(name, value); diff --git a/src/main/java/io/newsdata/api/exception/NewsdataWebSocketAuthException.java b/src/main/java/io/newsdata/api/exception/NewsdataWebSocketAuthException.java index 86513d1..781c192 100644 --- a/src/main/java/io/newsdata/api/exception/NewsdataWebSocketAuthException.java +++ b/src/main/java/io/newsdata/api/exception/NewsdataWebSocketAuthException.java @@ -16,4 +16,15 @@ public NewsdataWebSocketAuthException(String message) { public NewsdataWebSocketAuthException(String message, Throwable cause) { super(message, cause); } + + /** + * @param message the server's explanation, or the close reason + * @param cause the underlying failure, or {@code null} + * @param responseBody the raw error response the server sent, or {@code null} + * @param errorCode the server's error code, or {@code null} + */ + public NewsdataWebSocketAuthException(String message, Throwable cause, String responseBody, + String errorCode) { + super(message, cause, responseBody, errorCode); + } } diff --git a/src/main/java/io/newsdata/api/exception/NewsdataWebSocketException.java b/src/main/java/io/newsdata/api/exception/NewsdataWebSocketException.java index 8dca957..70a54e3 100644 --- a/src/main/java/io/newsdata/api/exception/NewsdataWebSocketException.java +++ b/src/main/java/io/newsdata/api/exception/NewsdataWebSocketException.java @@ -3,15 +3,51 @@ /** * A real-time WebSocket stream failure * (see {@code io.newsdata.api.NewsDataApiWebSocket}). + * + *

    When the server explained the failure in an error response before + * closing ({@code {"status":"error","results":{"message":...,"code":...}}}), + * the message is the server's explanation, {@link #errorCode()} its code + * (for example {@code Unauthorized} or {@code ServerError}) and + * {@link #responseBody()} the raw response. */ public class NewsdataWebSocketException extends NewsdataException { private static final long serialVersionUID = 1L; + private final String responseBody; + private final String errorCode; + public NewsdataWebSocketException(String message) { - super(message); + this(message, null, null, null); } public NewsdataWebSocketException(String message, Throwable cause) { + this(message, cause, null, null); + } + + /** + * @param message the server's explanation, or a description of the failure + * @param cause the underlying failure, or {@code null} + * @param responseBody the raw error response the server sent, or {@code null} + * @param errorCode the server's error code, or {@code null} + */ + public NewsdataWebSocketException(String message, Throwable cause, String responseBody, + String errorCode) { super(message, cause); + this.responseBody = responseBody; + this.errorCode = errorCode; + } + + /** The raw error response the server sent before closing, or {@code null} when none. */ + public String responseBody() { + return responseBody; + } + + /** + * The server's error code ({@code Unauthorized}, {@code ApiLimitExceeded}, + * {@code DeviceLimitExceeded}, {@code ServerError}, ...), or {@code null} + * when unknown. + */ + public String errorCode() { + return errorCode; } } diff --git a/src/test/java/io/newsdata/api/ArticleTest.java b/src/test/java/io/newsdata/api/ArticleTest.java new file mode 100644 index 0000000..968f04a --- /dev/null +++ b/src/test/java/io/newsdata/api/ArticleTest.java @@ -0,0 +1,146 @@ +package io.newsdata.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.newsdata.api.exception.NewsdataException; + +/** + * Decoding v1 articles. On plans without the AI add-ons the API sends a plain + * notice string in place of {@code ai_tag}, {@code ai_region}, {@code ai_org} + * (normally lists) and {@code sentiment_stats} (normally an object); the model + * must accept both shapes and never drop the page. + */ +class ArticleTest { + + private static final String NOTICE = "ONLY AVAILABLE IN PROFESSIONAL AND CORPORATE PLANS"; + + private final ObjectMapper mapper = new ObjectMapper(); + + private NewsdataResponse response(String resultsJson) throws Exception { + return new NewsdataResponse("success", 1, mapper.readTree(resultsJson), null, null); + } + + @Test + void planGatedFieldsSentAsStringsStillDecodeEveryArticle() throws Exception { + String gated = "{\"article_id\":\"%s\",\"title\":\"%s\"," + + "\"ai_tag\":\"" + NOTICE + "\",\"ai_region\":\"" + NOTICE + "\"," + + "\"ai_org\":\"" + NOTICE + "\",\"sentiment_stats\":\"" + NOTICE + "\"}"; + var resp = response("[" + String.format(gated, "a1", "one") + "," + + String.format(gated, "a2", "two") + "]"); + + List

    articles = resp.articles(mapper); + + assertEquals(2, articles.size(), "no article may be dropped"); + Article first = articles.get(0); + assertEquals("one", first.title()); + // Same as ArticleV2: the notice becomes a one-element list. + assertEquals(List.of(NOTICE), first.aiTag()); + assertTrue(ArticleV2.isPlanNotice(first.aiRegion().get(0))); + assertEquals(List.of(NOTICE), first.aiOrg()); + assertNull(first.sentimentStats(), "a notice string is not sentiment statistics"); + } + + @Test + void theNormalShapesStillDecode() throws Exception { + var resp = response("[{\"article_id\":\"a1\",\"ai_tag\":[\"politics\",\"economy\"]," + + "\"sentiment_stats\":{\"positive\":0.2,\"neutral\":0.7,\"negative\":0.1}}]"); + + Article article = resp.articles(mapper).get(0); + + assertEquals(List.of("politics", "economy"), article.aiTag()); + Map stats = article.sentimentStats(); + assertEquals(0.7, ((Number) stats.get("neutral")).doubleValue()); + } + + @Test + void otherListFieldsAcceptAPlainStringToo() throws Exception { + var resp = response("[{\"article_id\":\"a1\",\"keywords\":\"election\"," + + "\"creator\":\"Jane Doe\",\"country\":\"india\",\"category\":\"politics\"}]"); + + Article article = resp.articles(mapper).get(0); + + assertEquals(List.of("election"), article.keywords()); + assertEquals(List.of("Jane Doe"), article.creator()); + assertEquals(List.of("india"), article.country()); + assertEquals(List.of("politics"), article.category()); + } + + @Test + void absentAndNullListFieldsStayNull() throws Exception { + var resp = response("[{\"article_id\":\"a1\",\"keywords\":null}]"); + + Article article = resp.articles(mapper).get(0); + + assertNull(article.keywords(), "explicit null"); + assertNull(article.aiTag(), "absent"); + } + + @Test + void fetchedAtSummaryDuplicateAndCoinAreKept() throws Exception { + var resp = response("[{\"article_id\":\"a1\",\"fetched_at\":\"2026-11-29 10:15:00\"," + + "\"ai_summary\":\"A short summary.\",\"duplicate\":true,\"coin\":[\"btc\",\"eth\"]}]"); + + Article article = resp.articles(mapper).get(0); + + assertEquals("2026-11-29 10:15:00", article.fetchedAt()); + assertEquals("A short summary.", article.aiSummary()); + assertEquals(Boolean.TRUE, article.duplicate()); + assertEquals(List.of("btc", "eth"), article.coin()); + } + + @Test + void theAddedFieldsFollowTheRulesOfTheOthers() throws Exception { + var resp = response("[{\"article_id\":\"a1\"}," + + "{\"article_id\":\"a2\",\"duplicate\":false,\"coin\":\"btc\"}]"); + + List
    articles = resp.articles(mapper); + + Article absent = articles.get(0); + assertNull(absent.fetchedAt()); + assertNull(absent.aiSummary()); + assertNull(absent.duplicate()); + assertNull(absent.coin(), "an absent list stays null"); + Article second = articles.get(1); + assertEquals(Boolean.FALSE, second.duplicate()); + assertEquals(List.of("btc"), second.coin(), "a plain string becomes a one-element list"); + } + + @Test + void theEarlierConstructorStillBuildsAnArticle() { + Article article = new Article("a1", "title", null, null, null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, null, null, + null, null, null); + + assertEquals("a1", article.articleId()); + assertEquals("title", article.title()); + assertNull(article.fetchedAt()); + assertNull(article.aiSummary()); + assertNull(article.duplicate()); + assertNull(article.coin()); + } + + @Test + void aDecodeFailureThrowsInsteadOfReturningAnEmptyList() throws Exception { + var resp = response("[{\"article_id\":\"a1\",\"source_priority\":\"not a number\"}]"); + + var err = assertThrows(NewsdataException.class, () -> resp.articles(mapper)); + assertTrue(err.getCause() != null, "the decode failure is kept as the cause"); + } + + @Test + void aVersion2DecodeFailureThrowsToo() throws Exception { + var resp = response("[{\"id\":\"a1\",\"media\":12345}]"); + + assertThrows(NewsdataException.class, () -> resp.articlesV2(mapper)); + } +} diff --git a/src/test/java/io/newsdata/api/ExampleUsage.java b/src/test/java/io/newsdata/api/ExampleUsage.java index 55da937..50586e6 100644 --- a/src/test/java/io/newsdata/api/ExampleUsage.java +++ b/src/test/java/io/newsdata/api/ExampleUsage.java @@ -78,10 +78,12 @@ static void countEndpoint() { .apiKey(System.getenv("NEWSDATA_API_KEY")) .build(); + // Without an interval the count is one aggregate object; with one + // ("day", "hour", ...) results is a list of per-interval counts and + // aggregate() returns null. NewsdataResponse resp = client.count(Params.of() .with("from_date", "2024-01-01") .with("to_date", "2024-01-31") - .with("interval", "day") .with("q", "election")); System.out.println(resp.aggregate(client.objectMapper())); diff --git a/src/test/java/io/newsdata/api/MockWebSocketServer.java b/src/test/java/io/newsdata/api/MockWebSocketServer.java index 12b5283..9eb313d 100644 --- a/src/test/java/io/newsdata/api/MockWebSocketServer.java +++ b/src/test/java/io/newsdata/api/MockWebSocketServer.java @@ -20,8 +20,8 @@ /** * A minimal RFC 6455 server for tests — enough to accept the handshake and * push text / close frames at the client. Server-to-client frames are unmasked, - * which keeps the writer trivial; inbound frames are drained and ignored apart - * from noticing the socket closing. + * which keeps the writer trivial. Inbound frames are ignored unless a session + * calls {@link Session#answerPings()}, which answers the client's pings. * *

    Not a general-purpose implementation: no fragmentation, no extensions, no * payloads over 65535 bytes. @@ -33,6 +33,7 @@ final class MockWebSocketServer implements AutoCloseable { private final ServerSocket serverSocket; private final Thread acceptor; private final AtomicInteger connections = new AtomicInteger(); + private final AtomicInteger pings = new AtomicInteger(); private final List queries = new CopyOnWriteArrayList<>(); private volatile boolean running = true; @@ -73,6 +74,11 @@ int connectionCount() { return connections.get(); } + /** Pings received from the client, over all sessions that answer them. */ + int pingsReceived() { + return pings.get(); + } + /** Query strings seen on each handshake, in order. */ List queries() { return new ArrayList<>(queries); @@ -118,7 +124,7 @@ private void serve(Socket socket, BiConsumer onConnect, int n) .getBytes(StandardCharsets.UTF_8)); out.flush(); - onConnect.accept(new Session(out), n); + onConnect.accept(new Session(in, out, pings), n); } catch (IOException ignored) { // client went away } @@ -146,10 +152,58 @@ public void close() { /** Write side of one accepted connection. */ static final class Session { + private final InputStream in; private final OutputStream out; + private final AtomicInteger pings; - Session(OutputStream out) { + Session(InputStream in, OutputStream out, AtomicInteger pings) { + this.in = in; this.out = out; + this.pings = pings; + } + + /** + * Answer the client's pings with pongs, in the background, as a live + * server does. Reads (masked) client frames until the client closes. + */ + void answerPings() { + Thread reader = new Thread(() -> { + try { + while (true) { + int b0 = in.read(); + int b1 = in.read(); + if (b0 < 0 || b1 < 0) return; + int opcode = b0 & 0x0F; + long length = b1 & 0x7F; + if (length == 126) { + length = (in.read() << 8) | in.read(); + } else if (length == 127) { + length = 0; + for (int i = 0; i < 8; i++) length = (length << 8) | in.read(); + } + byte[] mask = (b1 & 0x80) != 0 ? in.readNBytes(4) : null; + byte[] payload = in.readNBytes((int) length); + if (mask != null) { + for (int i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4]; + } + if (opcode == 0x9) { + pings.incrementAndGet(); + synchronized (out) { + out.write(0x8A); // FIN + pong + out.write(payload.length); + out.write(payload); + out.flush(); + } + } else if (opcode == 0x8) { + return; // client closed + } + } + } catch (IOException ignored) { + // connection gone + } + }); + reader.setDaemon(true); + reader.start(); } /** Send one unmasked text frame. */ diff --git a/src/test/java/io/newsdata/api/NewsDataApiClientTest.java b/src/test/java/io/newsdata/api/NewsDataApiClientTest.java index 2792ed2..e4610d5 100644 --- a/src/test/java/io/newsdata/api/NewsDataApiClientTest.java +++ b/src/test/java/io/newsdata/api/NewsDataApiClientTest.java @@ -1,6 +1,7 @@ package io.newsdata.api; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -10,16 +11,20 @@ import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; +import java.net.ServerSocket; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; @@ -28,6 +33,7 @@ import io.newsdata.api.exception.NewsdataApiException; import io.newsdata.api.exception.NewsdataAuthException; import io.newsdata.api.exception.NewsdataException; +import io.newsdata.api.exception.NewsdataNetworkException; import io.newsdata.api.exception.NewsdataRateLimitException; import io.newsdata.api.exception.NewsdataValidationException; @@ -207,6 +213,34 @@ void paginateLimitStopsEarly() { // are acceptable, so we don't assert on calls here. } + @Test + void paginateWaitsOnlyBetweenPages() { + String[] pages = { + "{\"status\":\"success\",\"nextPage\":\"p2\",\"results\":[{\"article_id\":\"1\"}]}", + "{\"status\":\"success\",\"nextPage\":\"p3\",\"results\":[{\"article_id\":\"2\"}]}", + "{\"status\":\"success\",\"nextPage\":\"p4\",\"results\":[{\"article_id\":\"3\"}]}" + }; + AtomicInteger calls = new AtomicInteger(); + handle("latest", exchange -> respond(exchange, 200, pages[calls.getAndIncrement()])); + var client = defaultBuilder().paginationDelay(Duration.ofMillis(1500)).build(); + + List handedOverAt = new ArrayList<>(); + long start = System.nanoTime(); + client.paginate(Endpoint.LATEST, Params.of().with("q", "x")) + .limit(2) + .forEach(resp -> handedOverAt.add((System.nanoTime() - start) / 1_000_000)); + long totalMs = (System.nanoTime() - start) / 1_000_000; + + assertEquals(2, handedOverAt.size()); + assertTrue(handedOverAt.get(0) < 1000, + "the first page is handed over at once, not after the delay: " + handedOverAt.get(0) + " ms"); + assertTrue(handedOverAt.get(1) >= 1400, + "the delay still separates the pages: " + handedOverAt.get(1) + " ms"); + assertTrue(totalMs < 2500, + "no wait after the last page taken: " + totalMs + " ms"); + assertEquals(2, calls.get(), "only the pages taken are fetched"); + } + @Test void emptyApiKeyRejected() { assertThrows(NewsdataValidationException.class, @@ -345,4 +379,132 @@ void parseRetryAfterAcceptsIntegerSeconds() { assertEquals(0, NewsDataApiClient.parseRetryAfter("")); assertEquals(0, NewsDataApiClient.parseRetryAfter(null)); } + + // ---- 429 Retry-After -------------------------------------------------- + + private static final String SLOW_DOWN = + "{\"status\":\"error\",\"results\":{\"message\":\"slow down\",\"code\":\"RateLimitExceeded\"}}"; + + @Test + @Timeout(10) + void retryAfterLongerThanRetryBackoffMaxThrowsAtOnce() { + AtomicInteger calls = new AtomicInteger(); + handle("latest", exchange -> { + calls.incrementAndGet(); + respond(exchange, 429, SLOW_DOWN, "Retry-After", "615"); + }); + // retryBackoffMax stays at its 60 s default. + var client = defaultBuilder().maxRetries(3).retryBackoff(Duration.ofMillis(1)).build(); + + long started = System.nanoTime(); + var err = assertThrows(NewsdataRateLimitException.class, + () -> client.latest(Params.of().with("q", "x"))); + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started); + + assertEquals(615, err.retryAfter()); + assertEquals(1, calls.get(), "the 615 s wait is left to the caller"); + assertTrue(elapsedMs < 2_000, "took " + elapsedMs + " ms"); + } + + @Test + @Timeout(10) + void retryAfterZeroWaitsOneSecondBeforeRetrying() { + AtomicInteger calls = new AtomicInteger(); + handle("latest", exchange -> { + if (calls.incrementAndGet() == 1) { + respond(exchange, 429, SLOW_DOWN, "Retry-After", "0"); + } else { + respond(exchange, 200, successBody("[{\"title\":\"recovered\"}]")); + } + }); + var client = defaultBuilder().maxRetries(3).retryBackoff(Duration.ofMillis(1)).build(); + + long started = System.nanoTime(); + var resp = client.latest(Params.of().with("q", "x")); + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started); + + assertEquals("recovered", resp.results().get(0).path("title").asText()); + assertEquals(2, calls.get()); + assertTrue(elapsedMs >= 990, "retried after " + elapsedMs + " ms; Retry-After + 1 s expected"); + } + + // ---- rawQuery across pages -------------------------------------------- + + /** Two v2 pages: the first points at cursor p2, the second ends. */ + private List twoV2Pages() { + List queries = new CopyOnWriteArrayList<>(); + handlePath("2/news", exchange -> { + queries.add(exchange.getRequestURI().getQuery()); + if (queries.size() == 1) { + respond(exchange, 200, "{\"status\":\"success\",\"total_results\":2," + + "\"results\":[{\"id\":\"a\"}],\"next_page\":\"p2\"}"); + } else { + respond(exchange, 200, "{\"status\":\"success\",\"total_results\":2," + + "\"results\":[{\"id\":\"b\"}],\"next_page\":null}"); + } + }); + return queries; + } + + @Test + void scrollAllWithRawQueryFollowsThePageCursor() { + List queries = twoV2Pages(); + var client = defaultBuilder().paginationDelay(Duration.ZERO).build(); + + var merged = client.scrollAll(Endpoint.NEWS_V2, + Params.of().with("rawQuery", "q=bitcoin&language=en"), 0); + + assertEquals(2, merged.results().size()); + assertEquals(2, queries.size()); + assertTrue(queries.get(1).contains("page=p2"), queries.get(1)); + assertTrue(queries.get(1).contains("q=bitcoin"), queries.get(1)); + } + + @Test + void paginateWithRawQueryFollowsThePageCursor() { + List queries = twoV2Pages(); + var client = defaultBuilder().paginationDelay(Duration.ZERO).build(); + + long pages; + try (var stream = client.paginate(Endpoint.NEWS_V2, + Params.of().with("rawQuery", "q=bitcoin&language=en"))) { + pages = stream.count(); + } + + assertEquals(2, pages); + assertTrue(queries.get(1).contains("page=p2"), queries.get(1)); + assertTrue(queries.get(1).contains("language=en"), queries.get(1)); + } + + // ---- error messages never carry the API key ---------------------------- + + @Test + void aMalformedBaseUrlIsRejectedWithoutTheKey() { + var err = assertThrows(NewsdataValidationException.class, () -> NewsDataApiClient.builder() + .apiKey("SECRET-KEY-123") + .baseUrl("https://newsdata.io/api /") + .build()); + assertFalse(err.getMessage().contains("SECRET-KEY-123"), err.getMessage()); + } + + @Test + @Timeout(10) + void networkErrorsNameTheCauseWithoutTheKey() throws IOException { + int port; + try (ServerSocket unused = new ServerSocket(0)) { + port = unused.getLocalPort(); // nothing listens here once closed + } + var client = NewsDataApiClient.builder() + .apiKey("SECRET-KEY-123") + .baseUrl("http://127.0.0.1:" + port + "/api/") + .maxRetries(1) + .build(); + + var err = assertThrows(NewsdataNetworkException.class, + () -> client.latest(Params.of().with("q", "x"))); + + assertFalse(err.getMessage().endsWith("null"), err.getMessage()); + assertTrue(err.getMessage().contains("ConnectException"), err.getMessage()); + assertFalse(err.getMessage().contains("SECRET-KEY-123"), err.getMessage()); + } } diff --git a/src/test/java/io/newsdata/api/NewsDataApiWebSocketTest.java b/src/test/java/io/newsdata/api/NewsDataApiWebSocketTest.java index 2b98ef1..9ed97bc 100644 --- a/src/test/java/io/newsdata/api/NewsDataApiWebSocketTest.java +++ b/src/test/java/io/newsdata/api/NewsDataApiWebSocketTest.java @@ -1,18 +1,25 @@ package io.newsdata.api; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.OutputStream; +import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.ServerSocket; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; @@ -245,6 +252,261 @@ void rejectsNullHandler() { assertThrows(NewsdataValidationException.class, () -> ws.stream("reg-1", null)); } + // ---- refusals: the server's error frame ---------------------------------- + // On a refusal the server accepts the handshake, sends ONE error frame and + // closes. The frame never reaches the handler; it is raised with the close. + + private static String errorFrame(String code, String message) { + return "{\"status\":\"error\",\"results\":{\"message\":\"" + message + + "\",\"code\":\"" + code + "\"}}"; + } + + @Test + @Timeout(20) + void aRefusedStreamRaisesTheServerMessageAndNeverCallsTheHandler() throws Exception { + String message = "Your API key is invalid or the registration was not found."; + try (MockWebSocketServer server = new MockWebSocketServer(101, (session, n) -> { + try { + session.sendText(errorFrame("Unauthorized", message)); + session.sendClose(1008, "Unauthorized"); + session.hold(200); + } catch (IOException ignored) { + // client closed + } + })) { + // reconnect stays on: a permanent rejection must not be retried. + var ws = NewsDataApiWebSocket.builder(client()) + .baseUrl(server.url()) + .reconnectDelay(Duration.ofMillis(5)) + .build(); + AtomicInteger handled = new AtomicInteger(); + + var err = assertThrows(NewsdataWebSocketAuthException.class, + () -> ws.stream("reg-1", response -> { + handled.incrementAndGet(); + return true; + })); + + assertEquals(message, err.getMessage()); + assertEquals("Unauthorized", err.errorCode()); + assertTrue(err.responseBody() != null && err.responseBody().contains("\"Unauthorized\""), + "responseBody: " + err.responseBody()); + assertEquals(0, handled.get(), "the error frame must not be handed over as news"); + assertEquals(1, server.connectionCount()); + } + } + + @Test + @Timeout(20) + void anErrorFrameThenClose1011WithReconnectOffRaisesAStreamError() throws Exception { + try (MockWebSocketServer server = new MockWebSocketServer(101, (session, n) -> { + try { + session.sendText(errorFrame("ServerError", "Something went wrong on our side.")); + session.sendClose(1011, "ServerError"); + session.hold(200); + } catch (IOException ignored) { + // client closed + } + })) { + var ws = NewsDataApiWebSocket.builder(client()) + .baseUrl(server.url()) + .reconnect(false) + .build(); + AtomicInteger handled = new AtomicInteger(); + + var err = assertThrows(NewsdataWebSocketException.class, + () -> ws.stream("reg-1", response -> { + handled.incrementAndGet(); + return true; + })); + + assertFalse(err instanceof NewsdataWebSocketAuthException, "1011 is transient"); + assertEquals("Something went wrong on our side.", err.getMessage()); + assertEquals("ServerError", err.errorCode()); + assertEquals(0, handled.get()); + } + } + + @Test + @Timeout(20) + void anErrorFrameThenANormalCloseEndsQuietlyWithReconnectOff() throws Exception { + // A clean close is not an error, even after an error frame. + try (MockWebSocketServer server = new MockWebSocketServer(101, (session, n) -> { + try { + session.sendText(errorFrame("ServerError", "closing")); + session.sendClose(1000, ""); + session.hold(200); + } catch (IOException ignored) { + // client closed + } + })) { + var ws = NewsDataApiWebSocket.builder(client()) + .baseUrl(server.url()) + .reconnect(false) + .build(); + AtomicInteger handled = new AtomicInteger(); + + ws.stream("reg-1", response -> { + handled.incrementAndGet(); + return true; + }); + + assertEquals(0, handled.get()); + } + } + + // ---- reconnect delay -------------------------------------------------------- + + private static final Pattern RECONNECTING_IN = Pattern.compile("reconnecting .* in (\\d+)ms"); + + @Test + @Timeout(30) + void theReconnectDelayResetsOnConnectButGrowsWhileTheServerRefuses() throws Exception { + List delays = new CopyOnWriteArrayList<>(); + NewsDataApiClient logging = NewsDataApiClient.builder() + .apiKey("key").baseUrl(baseUrl) + .logger((level, message) -> { + Matcher m = RECONNECTING_IN.matcher(message); + if (m.find()) delays.add(Long.parseLong(m.group(1))); + }) + .build(); + try (MockWebSocketServer server = new MockWebSocketServer(101, (session, n) -> { + try { + if (n <= 3) { // accept, refuse, close 1011 + session.sendText(errorFrame("ServerError", "temporarily unavailable")); + session.sendClose(1011, "ServerError"); + } else if (n == 4) { // a healthy connection that drops + session.sendClose(1011, "restart"); + } else { + session.sendText(articleFrame("a1", "finally")); + } + session.hold(300); + } catch (IOException ignored) { + // client closed + } + })) { + var ws = NewsDataApiWebSocket.builder(logging) + .baseUrl(server.url()) + .reconnectDelay(Duration.ofMillis(20)) + .reconnectDelayMax(Duration.ofSeconds(5)) + .build(); + + ws.stream("reg-1", response -> !"success".equals(response.status())); + + // 20, 40, 80: refused connections keep backing off. 20: a connection + // the server did not refuse resets the delay. + assertEquals(List.of(20L, 40L, 80L, 20L), delays); + } + } + + // ---- close() from another thread ---------------------------------------- + + /** Run {@code ws.stream} on a daemon thread; the latch opens when it returns. */ + private static CountDownLatch streamInBackground(NewsDataApiWebSocket ws) { + CountDownLatch done = new CountDownLatch(1); + Thread t = new Thread(() -> { + try { + ws.stream("reg-1", response -> true); + } catch (RuntimeException ignored) { + // the outcome is checked through the latch + } finally { + done.countDown(); + } + }); + t.setDaemon(true); + t.start(); + return done; + } + + @Test + @Timeout(30) + void closeFromAnotherThreadEndsAnIdleStream() throws Exception { + try (MockWebSocketServer server = new MockWebSocketServer(101, (session, n) -> session.hold(15_000))) { + var ws = NewsDataApiWebSocket.builder(client()).baseUrl(server.url()).build(); + CountDownLatch done = streamInBackground(ws); + for (int i = 0; i < 100 && server.connectionCount() == 0; i++) Thread.sleep(20); + Thread.sleep(200); // connected and idle + + ws.close(); + + assertTrue(done.await(1, TimeUnit.SECONDS), "stream() was still blocked 1 s after close()"); + } + } + + @Test + @Timeout(30) + void closeDuringTheHandshakeEndsTheStream() throws Exception { + // Accepts the TCP connection but never answers the upgrade request. + try (ServerSocket silent = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) { + var ws = NewsDataApiWebSocket.builder(client()) + .baseUrl("ws://127.0.0.1:" + silent.getLocalPort() + "/ws/event") + .handshakeTimeout(Duration.ofSeconds(10)) + .build(); + CountDownLatch done = streamInBackground(ws); + Thread.sleep(300); // handshake in progress + + ws.close(); + + assertTrue(done.await(1, TimeUnit.SECONDS), "stream() was still blocked 1 s after close()"); + } + } + + // ---- keepalive -------------------------------------------------------------- + + @Test + @Timeout(30) + void aConnectionThatStopsAnsweringIsDroppedByTheKeepalive() throws Exception { + // The server goes silent and never answers pings: a half-open connection. + try (MockWebSocketServer server = new MockWebSocketServer(101, (session, n) -> session.hold(10_000))) { + var ws = NewsDataApiWebSocket.builder(client()) + .baseUrl(server.url()) + .reconnect(false) + .pingInterval(Duration.ofMillis(200)) + .pingTimeout(Duration.ofMillis(200)) + .build(); + + long started = System.nanoTime(); + var err = assertThrows(NewsdataWebSocketException.class, + () -> ws.stream("reg-1", response -> true)); + long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started); + + assertFalse(err instanceof NewsdataWebSocketAuthException); + assertTrue(elapsedMs < 5_000, "dead connection noticed after " + elapsedMs + " ms"); + } + } + + @Test + @Timeout(30) + void aQuietConnectionThatAnswersPingsKeepsStreaming() throws Exception { + try (MockWebSocketServer server = new MockWebSocketServer(101, (session, n) -> { + session.answerPings(); + session.hold(1_000); // quiet for longer than pingInterval + pingTimeout + try { + session.sendText(articleFrame("a1", "late news")); + } catch (IOException ignored) { + // client closed + } + session.hold(500); + })) { + var ws = NewsDataApiWebSocket.builder(client()) + .baseUrl(server.url()) + .reconnect(false) + .pingInterval(Duration.ofMillis(200)) + .pingTimeout(Duration.ofMillis(200)) + .build(); + AtomicReference got = new AtomicReference<>(); + + ws.stream("reg-1", response -> { + got.set(response.results().get(0).path("title").asText()); + return false; + }); + + assertEquals("late news", got.get()); + assertEquals(1, server.connectionCount(), "a quiet connection is not dropped"); + assertTrue(server.pingsReceived() >= 2, "pings sent: " + server.pingsReceived()); + } + } + // ---- query management ------------------------------------------------- @Test @@ -266,6 +528,35 @@ void websocketRegisterPostsWithNewsType() { assertEquals("reg-9", response.results().path("registration_id").asText()); } + @Test + void websocketRegisterWithRawQuerySendsItsParametersPlusNewsType() { + AtomicReference query = new AtomicReference<>(); + handleV2("websocket/register", exchange -> { + query.set(exchange.getRequestURI().getQuery()); + respond(exchange, 200, + "{\"status\":\"success\",\"results\":{\"registration_id\":\"reg-9\"}}"); + }); + + client().websocketRegister(Params.of().with("rawQuery", "q=bitcoin&language=en")); + + assertTrue(query.get().contains("q=bitcoin"), query.get()); + assertTrue(query.get().contains("language=en"), query.get()); + assertTrue(query.get().contains("news_type=news"), query.get()); + } + + @Test + void websocketRegisterRejectsACallerSuppliedNewsType() { + AtomicInteger calls = new AtomicInteger(); + handleV2("websocket/register", exchange -> { + calls.incrementAndGet(); + respond(exchange, 200, "{\"status\":\"success\",\"results\":{}}"); + }); + + assertThrows(NewsdataValidationException.class, + () -> client().websocketRegister(Params.of().with("q", "x").with("news_type", "market"))); + assertEquals(0, calls.get(), "nothing may be sent"); + } + @Test void websocketRegisterDoesNotMutateCallerParams() { handleV2("websocket/register", exchange -> diff --git a/src/test/java/io/newsdata/api/ValidatorTest.java b/src/test/java/io/newsdata/api/ValidatorTest.java index eb72f26..0b1d392 100644 --- a/src/test/java/io/newsdata/api/ValidatorTest.java +++ b/src/test/java/io/newsdata/api/ValidatorTest.java @@ -115,6 +115,25 @@ void countWithDatesAccepted() { assertEquals("2024-01-02", out.get("to_date")); } + @Test + void countRawQueryMustCarryBothDates() { + var noTo = assertThrows(NewsdataValidationException.class, + () -> Validator.validateAndEncode("count", m("rawQuery", "q=x&from_date=2024-01-01"))); + assertEquals("to_date", noTo.param()); + var noFrom = assertThrows(NewsdataValidationException.class, + () -> Validator.validateAndEncode("crypto_count", m("rawQuery", "coin=btc"))); + assertEquals("from_date", noFrom.param()); + } + + @Test + void countRawQueryWithBothDatesAccepted() { + var out = Validator.validateAndEncode("market_count", + m("rawQuery", "q=x&from_date=2024-01-01&to_date=2024-01-02")); + assertEquals("2024-01-01", out.get("from_date")); + assertEquals("2024-01-02", out.get("to_date")); + assertEquals("x", out.get("q")); + } + @Test void rawQueryParsedAndValidated() { var out = Validator.validateAndEncode("latest", m("rawQuery", "q=foo&country=us"));