diff --git a/CHANGES.md b/CHANGES.md index ab4bb120..5a010ba9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -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` diff --git a/src/main/java/io/github/hapjava/server/impl/HomekitRoot.java b/src/main/java/io/github/hapjava/server/impl/HomekitRoot.java index 36bfeefa..9a95c82b 100644 --- a/src/main/java/io/github/hapjava/server/impl/HomekitRoot.java +++ b/src/main/java/io/github/hapjava/server/impl/HomekitRoot.java @@ -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; @@ -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. + * + *

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. + * + *

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. + * + *

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 startAsync() { + if (started) { + CompletableFuture 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 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 { @@ -178,7 +221,14 @@ public void start() { configurationIndex, authInfo.getSetupId()); } catch (Exception e) { - throw new RuntimeException(e); + throw new CompletionException(e); + } + }) + .whenComplete( + (ignored, error) -> { + if (error != null) { + started = false; + stop(); } }); } diff --git a/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java b/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java index 81d2666e..4b3fe1f7 100644 --- a/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java +++ b/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java @@ -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; @@ -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; @@ -66,6 +72,140 @@ public void testWebHandlerStarts() throws Exception { verify(webHandler).start(any(HomekitClientConnectionFactory.class)); } + @Test + public void testFailedWebHandlerStartIsCleanedUp() throws Exception { + CompletableFuture 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 bind = new CompletableFuture<>(); + when(webHandler.start(any())).thenReturn(bind); + + CompletableFuture 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 bind = new CompletableFuture<>(); + when(webHandler.start(any())).thenReturn(bind); + BindException failure = new BindException("Address not available"); + + CompletableFuture 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 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 bind = new CompletableFuture<>(); + when(webHandler.start(any())).thenReturn(bind); + + CompletableFuture first = root.startAsync(); + CompletableFuture 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 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 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();