From dc114d89a0e7c0deb657aedefd4848ea1abcaf87 Mon Sep 17 00:00:00 2001 From: Alex Andres Date: Thu, 29 Oct 2026 19:39:28 +0100 Subject: [PATCH] feat: give WHIP and WHEP errors their status and problem details An endpoint's error status now fails with HttpStatusException, a WebRtcException whose status(), title(), detail() and problemType() give the status and the problem details (RFC 9457) the endpoint sent, for the offer, a counter-offer's answer, ICE restarts, and as the cause for the deletion and trickled candidates. The messages stay as they were. --- docs/guide/client-api.md | 15 ++- .../dev/onvoid/webrtc/client/HttpCall.java | 75 +++++++++------ .../dev/onvoid/webrtc/client/HttpIce.java | 13 ++- .../dev/onvoid/webrtc/client/HttpSession.java | 7 +- .../webrtc/client/HttpStatusException.java | 91 +++++++++++++++++++ .../onvoid/webrtc/client/HttpCallTests.java | 20 ++++ .../webrtc/client/HttpSessionTests.java | 25 ++++- 7 files changed, 205 insertions(+), 41 deletions(-) create mode 100644 webrtc/src/main/java/dev/onvoid/webrtc/client/HttpStatusException.java diff --git a/docs/guide/client-api.md b/docs/guide/client-api.md index 53ae492c0..f3c911d85 100644 --- a/docs/guide/client-api.md +++ b/docs/guide/client-api.md @@ -681,7 +681,19 @@ Whip.Session live = Whip.to(URI.create("https://example.com/live/whip")) .get(15, TimeUnit.SECONDS); ``` -A normal SDP answer must have status 201, a nonempty session `Location`, and Content-Type `application/sdp` (parameters are allowed). Invalid responses fail the session; a resource already named by the server is deleted even when its SDP response cannot be used. The message of a failure an endpoint answered with an error names the status, and what the endpoint says of it: the title and detail of problem details (RFC 9457, `application/problem+json`), as in `status 403: Forbidden: The stream key has expired`, or else the start of the body. +A normal SDP answer must have status 201, a nonempty session `Location`, and Content-Type `application/sdp` (parameters are allowed). Invalid responses fail the session; a resource already named by the server is deleted even when its SDP response cannot be used. The message of a failure an endpoint answered with an error names the status, and what the endpoint says of it: the title and detail of problem details (RFC 9457, `application/problem+json`), as in `status 403: Forbidden: The stream key has expired`, or else the start of the body. The failure is an `HttpStatusException`, whose `status()`, `title()`, `detail()` and `problemType()` give the same to a program; for a deletion or for candidates, it is the cause of the failure reported. As RFC 9725 asks, read no specific cause into a status beyond its class, since endpoints use them differently: + +```java +try { + session = Whip.to(url).bearerToken(key).track(camera).publish(rtc).get(15, TimeUnit.SECONDS); +} +catch (ExecutionException e) { + if (e.getCause() instanceof HttpStatusException) { + HttpStatusException refused = (HttpStatusException) e.getCause(); + System.err.println("Refused, " + refused.status() + ": " + refused.detail()); + } +} +``` When the connection fails, or stays disconnected for two seconds, the session restarts ICE: the peer gathers new candidates, and only the new ICE username fragment and password go to the session, by `PATCH` with `If-Match: *`, while the media go on as negotiated. The session's answer, with status 200 and Content-Type `application/trickle-ice-sdpfrag`, brings its own ICE information and a new `ETag`. Its candidate set replaces the old one completely, including when it is empty. Three restarts in a row that do not bring the connection back, or an endpoint that takes no restarts, end the attempts, which the error handler hears of. `session.restartIce()` restarts ICE at once, say after the network changed; a restart that fails leaves the ICE session before as it was. Restarts also work after a WHEP counter-offer; the player keeps its answerer role and updates only the ICE information. @@ -803,6 +815,7 @@ Failures arrive as exceptions, thrown or as the cause of a failed future, all of | `MediaException` | A device is missing, busy, refused access, or already open with other options. | | `ConfigurationException` | A call does not fit how the runtime was built, or WebRTC refused a configuration. | | `BlockingCallException` | A future was waited on from an event thread. | +| `HttpStatusException` | A WHIP or WHEP endpoint answered with an error status, which `status()` gives, with the `title()`, `detail()` and `problemType()` of the problem details it sent, if any. | Failures that no caller waits for, such as a remote description rejected during automatic negotiation, go to the peer's `onError` handlers: diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java index 98f4511b3..f7f1bc595 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java @@ -633,10 +633,26 @@ String header(String name) { */ String describe() { String description = "status " + status; - String problem = problem(); + Map problem = problemDetails(); if (problem != null) { - return problem.isEmpty() ? description : description + ": " + problem; + List parts = new ArrayList<>(); + String title = member(problem, "title"); + String detail = member(problem, "detail"); + String type = member(problem, "type"); + + if (title != null) { + parts.add(title); + } + if (detail != null) { + parts.add(detail); + } + // RFC 9457, 4.2.1: about:blank says no more than the status. + if (parts.isEmpty() && type != null && !"about:blank".equals(type)) { + parts.add(type); + } + + return parts.isEmpty() ? description : description + ": " + String.join(": ", parts); } if (body == null || body.isEmpty()) { return description; @@ -646,11 +662,28 @@ String describe() { } /** - * @return what the problem details of the body say, empty if no more - * than the status, or null if the body has none, or none that can be - * read. + * @param message what failed, which describes the response, as {@link + * #describe()} does. + * + * @return an exception with the message, the status of the response + * and what its problem details say. + */ + HttpStatusException error(String message) { + Map problem = problemDetails(); + + if (problem == null) { + return new HttpStatusException(message, status, null, null, null); + } + + return new HttpStatusException(message, status, member(problem, "type"), member(problem, "title"), + member(problem, "detail")); + } + + /** + * @return the members of the problem details of the body (RFC 9457), + * or null if the body has none, or none that can be read. */ - private String problem() { + private Map problemDetails() { String type = header("Content-Type"); if (body == null || type == null @@ -668,29 +701,17 @@ private String problem() { return null; } - if (!(parsed instanceof Map)) { - return null; - } - - Map members = (Map) parsed; - List parts = new ArrayList<>(); - - for (String name : List.of("title", "detail")) { - Object value = members.get(name); - - if (value instanceof String && !((String) value).trim().isEmpty()) { - parts.add(((String) value).trim()); - } - } - - Object problemType = members.get("type"); + return parsed instanceof Map ? (Map) parsed : null; + } - // RFC 9457, 4.2.1: about:blank says no more than the status. - if (parts.isEmpty() && problemType instanceof String && !"about:blank".equals(problemType)) { - parts.add((String) problemType); - } + /** + * @return the string member of the name, trimmed, or null if there is + * none, or one that is not a string or is blank. + */ + private static String member(Map members, String name) { + Object value = members.get(name); - return String.join(": ", parts); + return value instanceof String && !((String) value).trim().isEmpty() ? ((String) value).trim() : null; } } diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java index c64f751bb..6f50772f1 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java @@ -271,11 +271,10 @@ private UnaryOperator answered(HttpCall request, HttpCall.Response respo restartsRefused = true; } - throw new WebRtcException("The session " + target + " takes no ICE restarts: " + response.describe()); + throw response.error("The session " + target + " takes no ICE restarts: " + response.describe()); } if (response.status / 100 != 2) { - throw new WebRtcException("The session " + target + " answered the ICE restart with " - + response.describe()); + throw response.error("The session " + target + " answered the ICE restart with " + response.describe()); } HttpSession.requireContentType(response, FRAGMENT_TYPE); @@ -379,10 +378,16 @@ private void flush() { } if (report) { + // An error status is the cause, for its status. + Throwable cause = error != null + ? error + : response.error("The session " + target + " answered the candidates with " + + response.describe()); + rtc.reportError(new WebRtcException("Sending ICE candidates to the session " + target + " failed, and no more are sent: " + (error != null ? error.getMessage() - : response.describe()), error)); + : response.describe()), cause)); } flush(); diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java index 36b469aca..ea7293a69 100644 --- a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpSession.java @@ -408,8 +408,7 @@ private static CompletableFuture post(HttpCall request, URI endpoint, Str protocol); } - throw new WebRtcException("The endpoint " + endpoint + " answered the offer with " - + response.describe()); + throw response.error("The endpoint " + endpoint + " answered the offer with " + response.describe()); }); } @@ -451,7 +450,7 @@ private static CompletableFuture answerCounterOffer(WebRtc rtc, HttpClient + error.getMessage(), error); } if (response.status / 100 != 2) { - throw new WebRtcException("The endpoint answered the answer for " + throw response.error("The endpoint answered the answer for " + reply.session + " with " + response.describe()); } @@ -611,7 +610,7 @@ private static CompletableFuture discard(WebRtc rtc, URI resour Throwable failure = error; if (failure == null && response.status / 100 != 2) { - failure = new WebRtcException("The endpoint answered the deletion of " + resource + failure = response.error("The endpoint answered the deletion of " + resource + " with " + response.describe()); } if (failure == null) { diff --git a/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpStatusException.java b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpStatusException.java new file mode 100644 index 000000000..e86dcfd8e --- /dev/null +++ b/webrtc/src/main/java/dev/onvoid/webrtc/client/HttpStatusException.java @@ -0,0 +1,91 @@ +/* + * Copyright 2026 Alex Andres + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dev.onvoid.webrtc.client; + +/** + * A WHIP or WHEP endpoint answered a request with an error: its status, and + * what problem details (RFC 9457) it sent with it say, where it sent any. + *

+ * The status tells the class of the error, such as a client error for 4xx. + * RFC 9725 (4.1) asks clients not to read a specific cause into a status + * beyond that, since endpoints use them differently; the title and the detail + * are meant for people, the problem type for programs. + */ +public class HttpStatusException extends WebRtcException { + + private static final long serialVersionUID = 1L; + + private final int status; + + private final String problemType; + + private final String title; + + private final String detail; + + + /** + * Creates the exception with a message that says what went wrong. + * + * @param message the detail message. + * @param status the status of the response. + * @param problemType the type of the problem details, or null. + * @param title the title of the problem details, or null. + * @param detail the detail of the problem details, or null. + */ + public HttpStatusException(String message, int status, String problemType, String title, String detail) { + super(message); + + this.status = status; + this.problemType = problemType; + this.title = title; + this.detail = detail; + } + + /** + * @return the status of the response, such as 403. + */ + public int status() { + return status; + } + + /** + * @return the URI that identifies the type of the problem, as the + * problem details give it, such as {@code + * https://example.com/probs/stream-key}; null if the endpoint sent none. + */ + public String problemType() { + return problemType; + } + + /** + * @return the short summary of the problem the endpoint sent, such as + * {@code Forbidden}, or null. + */ + public String title() { + return title; + } + + /** + * @return the explanation of this occurrence of the problem the endpoint + * sent, such as {@code The stream key has expired}, or null. + */ + public String detail() { + return detail; + } + +} diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java index b847dc8ca..df05b402d 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java @@ -100,6 +100,26 @@ void problemDetailsDescribed() { response(502, "text/html", "a".repeat(5000)).describe().length()); } + @Test + void problemDetailsOfError() { + // The status and the problem details, for a program to read. + HttpStatusException typed = response(409, "application/problem+json", + "{\"type\":\"https://example.com/probs/busy\",\"title\":\" Busy \"}").error("refused"); + + assertEquals("refused", typed.getMessage()); + assertEquals(409, typed.status()); + assertEquals("https://example.com/probs/busy", typed.problemType()); + assertEquals("Busy", typed.title()); + assertNull(typed.detail()); + + HttpStatusException plain = response(404, "text/plain", "not found").error("gone"); + + assertEquals(404, plain.status()); + assertNull(plain.problemType()); + assertNull(plain.title()); + assertNull(plain.detail()); + } + @Test void oversizedAnswerRefused() throws Exception { try (TestHttpEndpoint endpoint = new TestHttpEndpoint(offer -> ANSWER, 201)) { diff --git a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java index 550b782fa..0cc0945d6 100644 --- a/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java +++ b/webrtc/src/test/java/dev/onvoid/webrtc/client/HttpSessionTests.java @@ -359,6 +359,10 @@ void refusedOfferLeavesNothing() throws Exception { assertInstanceOf(WebRtcException.class, failed.getCause()); assertTrue(failed.getCause().getMessage().contains("403"), failed.getCause().getMessage()); + // Without problem details, the status alone. + HttpStatusException refused = assertInstanceOf(HttpStatusException.class, failed.getCause()); + assertEquals(403, refused.status()); + assertNull(refused.title()); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (!rtc.peers().isEmpty() && System.nanoTime() < deadline) { @@ -382,6 +386,14 @@ void refusalProblemDescribed() throws Exception { assertTrue(failed.getCause().getMessage().endsWith( "answered the offer with status 403: Forbidden: The stream key has expired"), failed.getCause().getMessage()); + + // The same, for a program to read. + HttpStatusException refused = assertInstanceOf(HttpStatusException.class, failed.getCause()); + + assertEquals(403, refused.status()); + assertEquals("Forbidden", refused.title()); + assertEquals("The stream key has expired", refused.detail()); + assertNull(refused.problemType()); } } @@ -954,6 +966,7 @@ void refusedIceRestartKeepsSession() throws Exception { assertTrue(failed.getCause().getMessage().contains("takes no ICE restarts"), failed.getCause().getMessage()); + assertEquals(405, assertInstanceOf(HttpStatusException.class, failed.getCause()).status()); assertEquals(offered, HttpIce.Fragment.of(local).ufrag); assertEquals(PeerState.CONNECTED, session.peer().state()); @@ -1489,7 +1502,7 @@ void failedDeleteReported() throws Exception { Whip.Session session = await(Whip.to(endpoint.uri()).track(video).publish(rtc)); - assertCloseFails(session, "500"); + assertCloseFails(session, 500); // Closed all the same. assertEquals(PeerState.CLOSED, session.peer().state()); assertDeleteReported("500"); @@ -1534,7 +1547,7 @@ void failedPeerCloseFails() throws Exception { HttpSession both = new Whep.Session(rtc, failingToClose(peerError), endpoint.uri().resolve("/live/session/1"), Map.of(), null, SESSION_TIMEOUT, null); - Throwable error = assertCloseFails(both, "500"); + Throwable error = assertCloseFails(both, 500); assertEquals(Arrays.asList(peerError), Arrays.asList(error.getSuppressed())); assertDeleteReported("500"); @@ -1549,7 +1562,7 @@ void redirectNotFollowed() throws Exception { Whip.Session session = await(Whip.to(endpoint.uri()).bearerToken("secret").track(video).publish(rtc)); - assertCloseFails(session, "307"); + assertCloseFails(session, 307); assertDeleteReported("307"); assertFalse(endpoint.requests.stream().anyMatch(request -> request.path.equals(endpoint.redirect)), () -> "Requests: " + endpoint.requests); @@ -1900,13 +1913,15 @@ private TestHttpEndpoint receivingEndpoint() throws Exception { * * @return the failure. */ - private static Throwable assertCloseFails(HttpSession session, String status) { + private static Throwable assertCloseFails(HttpSession session, int status) { ExecutionException failed = assertThrows(ExecutionException.class, () -> await(session.closeAsync())); Throwable error = failed.getCause(); assertInstanceOf(WebRtcException.class, error); assertTrue(error.getMessage().contains("Deleting the session"), error::getMessage); - assertTrue(error.getCause().getMessage().contains(status), () -> error.getCause().getMessage()); + assertTrue(error.getCause().getMessage().contains("status " + status), () -> error.getCause().getMessage()); + // The status of the deletion's answer, for a program to read. + assertEquals(status, assertInstanceOf(HttpStatusException.class, error.getCause()).status()); return error; }