Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion docs/guide/client-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -805,6 +817,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:

Expand Down
75 changes: 48 additions & 27 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/HttpCall.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> 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;
Expand All @@ -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
Expand All @@ -668,29 +701,17 @@ private String problem() {
return null;
}

if (!(parsed instanceof Map)) {
return null;
}

Map<?, ?> members = (Map<?, ?>) parsed;
List<String> 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;
}
}

Expand Down
13 changes: 9 additions & 4 deletions webrtc/src/main/java/dev/onvoid/webrtc/client/HttpIce.java
Original file line number Diff line number Diff line change
Expand Up @@ -271,11 +271,10 @@ private UnaryOperator<String> 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);
Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -408,8 +408,7 @@ private static CompletableFuture<Reply> 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());
});
}

Expand Down Expand Up @@ -451,7 +450,7 @@ private static CompletableFuture<Void> 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());
}

Expand Down Expand Up @@ -611,7 +610,7 @@ private static CompletableFuture<WebRtcException> 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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
* <p>
* 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;
}

}
20 changes: 20 additions & 0 deletions webrtc/src/test/java/dev/onvoid/webrtc/client/HttpCallTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,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) {
Expand All @@ -435,6 +439,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());
}
}

Expand Down Expand Up @@ -1007,6 +1019,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());

Expand Down Expand Up @@ -1542,7 +1555,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");
Expand Down Expand Up @@ -1587,7 +1600,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");
Expand All @@ -1602,7 +1615,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);
Expand Down Expand Up @@ -1953,13 +1966,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;
}
Expand Down
Loading