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
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
# HAP-Java 2.0.10
* Expose asynchronous HomeKit startup failures through `HomekitRoot.startAsync()` and clean up failed starts
* Synchronous startup exceptions are also reported through the returned future; duplicate starts fail without stopping an existing startup or listener
* Failed startup stops the HTTP listener even when only mDNS registration failed, including when using the existing `start()` method; already-paired controllers can no longer use that listener
* Recovery is not automatic: integrations must create a new server and root for another attempt because the default HTTP handler cannot be restarted
* Add constructors with custom min/max to the window covering tilt angle characteristics [#162](https://github.com/hap-java/HAP-Java/issues/162)
* Add optional Mute characteristic to Doorbell service
* Fix leak of mDNS instances and shutdown hooks when stopping `HomekitRoot`
Expand Down
62 changes: 56 additions & 6 deletions src/main/java/io/github/hapjava/server/impl/HomekitRoot.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser;
import java.io.IOException;
import java.net.InetAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import javax.jmdns.JmDNS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -158,14 +160,55 @@ public void removeAccessory(HomekitAccessory accessory) {
* call this after you have used the {@link #addAccessory(HomekitAccessory)} method to add all the
* initial accessories you plan on advertising, as any later additions will cause the HomeKit
* clients to reconnect.
*
* <p>Startup failures are logged. Use {@link #startAsync()} to handle them in the caller. An
* advertising failure also stops the HTTP listener. Recovery is not automatic and requires a new
* server and root.
*/
public void start() {
startAsync()
.whenComplete(
(ignored, error) -> {
if (error != null) {
logger.error("Could not start HomeKit root {}", label, error);
}
});
}

/**
* Starts handling and advertising the previously added HomeKit accessories.
*
* <p>Startup failures, including exceptions thrown before the HTTP handler returns a future,
* complete the returned future exceptionally after cleanup. If advertising fails after the HTTP
* listener has started, the listener is stopped as well. Recovery requires a new server and root;
* the default HTTP handler cannot be restarted.
*
* <p>A start requested while this root is starting or running fails without stopping the existing
* startup or listener.
*
* @return a future that completes after the HTTP listener has started and the advertiser has
* registered the service, or exceptionally after a failed start has been cleaned up
*/
public CompletableFuture<Void> startAsync() {
if (started) {
CompletableFuture<Void> failure = new CompletableFuture<>();
failure.completeExceptionally(new IllegalStateException("HomeKit root is already started"));
return failure;
}
started = true;
madeChanges = false;
registry.reset();
webHandler
.start(
new HomekitClientConnectionFactoryImpl(authInfo, registry, subscriptions, advertiser))
CompletableFuture<Integer> portFuture;
try {
madeChanges = false;
registry.reset();
portFuture =
webHandler.start(
new HomekitClientConnectionFactoryImpl(
authInfo, registry, subscriptions, advertiser));
} catch (RuntimeException e) {
portFuture = new CompletableFuture<>();
portFuture.completeExceptionally(e);
}
return portFuture
.thenAccept(
port -> {
try {
Expand All @@ -178,7 +221,14 @@ public void start() {
configurationIndex,
authInfo.getSetupId());
} catch (Exception e) {
throw new RuntimeException(e);
throw new CompletionException(e);
}
})
.whenComplete(
Comment thread
yfre marked this conversation as resolved.
Resolved
(ignored, error) -> {
if (error != null) {
started = false;
stop();
}
});
}
Expand Down
140 changes: 140 additions & 0 deletions src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package io.github.hapjava.server.impl;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

Expand All @@ -13,7 +16,10 @@
import io.github.hapjava.server.HomekitWebHandler;
import io.github.hapjava.server.impl.http.HomekitClientConnectionFactory;
import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser;
import java.io.IOException;
import java.net.BindException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
Expand Down Expand Up @@ -66,6 +72,140 @@ public void testWebHandlerStarts() throws Exception {
verify(webHandler).start(any(HomekitClientConnectionFactory.class));
}

@Test
public void testFailedWebHandlerStartIsCleanedUp() throws Exception {
CompletableFuture<Integer> bind = new CompletableFuture<>();
when(webHandler.start(any())).thenReturn(bind);

root.start();
bind.completeExceptionally(new BindException("Address not available"));

verify(webHandler).stop();
verify(advertiser).stop();
root.setConfigurationIndex(2);
verify(advertiser, never()).setConfigurationIndex(2);
}

@Test
public void testStartAsyncWaitsForWebHandler() throws Exception {
CompletableFuture<Integer> bind = new CompletableFuture<>();
when(webHandler.start(any())).thenReturn(bind);

CompletableFuture<Void> start = root.startAsync();

Assert.assertFalse(start.isDone());
verify(advertiser, never()).advertise(any(), anyInt(), any(), anyInt(), anyInt(), any());

bind.complete(PORT);

start.join();
verify(advertiser).advertise(eq(LABEL), eq(1), any(), eq(PORT), eq(1), any());
verify(webHandler, never()).stop();
}

@Test
public void testStartAsyncPropagatesBindFailure() throws Exception {
CompletableFuture<Integer> bind = new CompletableFuture<>();
when(webHandler.start(any())).thenReturn(bind);
BindException failure = new BindException("Address not available");

CompletableFuture<Void> start = root.startAsync();
bind.completeExceptionally(failure);

Assert.assertSame(
failure, Assert.assertThrows(CompletionException.class, start::join).getCause());
verify(webHandler).stop();
verify(advertiser).stop();
verify(advertiser, never()).advertise(any(), anyInt(), any(), anyInt(), anyInt(), any());
root.setConfigurationIndex(2);
verify(advertiser, never()).setConfigurationIndex(2);
}

@Test
public void testStartAsyncPropagatesSynchronousFailure() throws Exception {
RuntimeException failure = new IllegalStateException("HTTP startup failed");
when(webHandler.start(any())).thenThrow(failure);

CompletableFuture<Void> start = root.startAsync();

Assert.assertTrue(start.isCompletedExceptionally());
Assert.assertSame(
failure, Assert.assertThrows(CompletionException.class, start::join).getCause());
verify(webHandler).stop();
verify(advertiser).stop();
verify(advertiser, never()).advertise(any(), anyInt(), any(), anyInt(), anyInt(), any());
root.setConfigurationIndex(2);
verify(advertiser, never()).setConfigurationIndex(2);
}

@Test
public void testStartCleansUpSynchronousFailure() throws Exception {
when(webHandler.start(any())).thenThrow(new IllegalStateException("HTTP startup failed"));

root.start();

verify(webHandler).stop();
verify(advertiser).stop();
root.setConfigurationIndex(2);
verify(advertiser, never()).setConfigurationIndex(2);
}

@Test
public void testDuplicateStartDoesNotStopPendingStartup() throws Exception {
CompletableFuture<Integer> bind = new CompletableFuture<>();
when(webHandler.start(any())).thenReturn(bind);

CompletableFuture<Void> first = root.startAsync();
CompletableFuture<Void> duplicate = root.startAsync();

Assert.assertTrue(duplicate.isCompletedExceptionally());
Assert.assertTrue(
Assert.assertThrows(CompletionException.class, duplicate::join).getCause()
instanceof IllegalStateException);
Assert.assertFalse(first.isDone());
verify(webHandler, times(1)).start(any());
verify(webHandler, never()).stop();
verify(advertiser, never()).stop();

bind.complete(PORT);

Assert.assertTrue(first.isDone());
first.join();
verify(advertiser).advertise(eq(LABEL), eq(1), any(), eq(PORT), eq(1), any());
}

@Test
public void testDuplicateStartDoesNotStopRunningRoot() throws Exception {
root.startAsync().join();

CompletableFuture<Void> duplicate = root.startAsync();

Assert.assertTrue(duplicate.isCompletedExceptionally());
Assert.assertTrue(
Assert.assertThrows(CompletionException.class, duplicate::join).getCause()
instanceof IllegalStateException);
verify(webHandler, times(1)).start(any());
verify(webHandler, never()).stop();
verify(advertiser, never()).stop();
root.setConfigurationIndex(2);
verify(advertiser).setConfigurationIndex(2);
}

@Test
public void testStartAsyncPropagatesAdvertisingFailure() throws Exception {
IOException failure = new IOException("mDNS registration failed");
doThrow(failure).when(advertiser).advertise(any(), anyInt(), any(), anyInt(), anyInt(), any());

CompletableFuture<Void> start = root.startAsync();

Assert.assertSame(
failure, Assert.assertThrows(CompletionException.class, start::join).getCause());
verify(webHandler).stop();
verify(advertiser).stop();
root.setConfigurationIndex(2);
verify(advertiser, never()).setConfigurationIndex(2);
}

@Test
public void testWebHandlerStops() throws Exception {
root.start();
Expand Down
Loading