From 1d2c90f0049cf7d9c3897e3bf949bbb98e4baf5a Mon Sep 17 00:00:00 2001 From: Leo Siepel Date: Fri, 27 Nov 2026 12:15:56 +0100 Subject: [PATCH 1/2] Expose asynchronous HomeKit startup failures Signed-off-by: Leo Siepel --- CHANGES.md | 1 + .../hapjava/server/impl/HomekitRoot.java | 31 ++++++++- .../hapjava/server/impl/HomekitRootTest.java | 69 +++++++++++++++++++ 3 files changed, 99 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index ab4bb1202..353b24cf8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,5 @@ # HAP-Java 2.0.10 +* Expose asynchronous HomeKit startup failures through `HomekitRoot.startAsync()` and clean up failed starts * 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 36bfeefa2..1c9b10b4a 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,12 +160,30 @@ 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. */ 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. + * + * @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() { started = true; madeChanges = false; registry.reset(); - webHandler + return webHandler .start( new HomekitClientConnectionFactoryImpl(authInfo, registry, subscriptions, advertiser)) .thenAccept( @@ -178,7 +198,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 81d2666e5..cde00c04f 100644 --- a/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java +++ b/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java @@ -1,7 +1,9 @@ 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.verify; @@ -13,7 +15,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 +71,70 @@ 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 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(); From 4b88a705cf477831717c4c7a6d836259c1105ff3 Mon Sep 17 00:00:00 2001 From: Leo Siepel Date: Fri, 27 Nov 2026 14:09:15 +0100 Subject: [PATCH 2/2] Handle synchronous startup failures Signed-off-by: Leo Siepel --- CHANGES.md | 3 + .../hapjava/server/impl/HomekitRoot.java | 35 +++++++-- .../hapjava/server/impl/HomekitRootTest.java | 71 +++++++++++++++++++ 3 files changed, 103 insertions(+), 6 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 353b24cf8..5a010ba91 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +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 1c9b10b4a..9a95c82b0 100644 --- a/src/main/java/io/github/hapjava/server/impl/HomekitRoot.java +++ b/src/main/java/io/github/hapjava/server/impl/HomekitRoot.java @@ -161,7 +161,9 @@ public void removeAccessory(HomekitAccessory accessory) { * 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. + *

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() @@ -176,16 +178,37 @@ public void start() { /** * 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(); - return 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 { 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 cde00c04f..4b3fe1f7b 100644 --- a/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java +++ b/src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java @@ -6,6 +6,7 @@ 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; @@ -120,6 +121,76 @@ public void testStartAsyncPropagatesBindFailure() throws Exception { 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");