Skip to content

Commit b0269a1

Browse files
authored
Merge pull request #218 from lsiepel/fix/async-start-failures
Expose asynchronous HomeKit startup failures
2 parents a162ea5 + 4b88a70 commit b0269a1

3 files changed

Lines changed: 200 additions & 6 deletions

File tree

‎CHANGES.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
# HAP-Java 2.0.10
2+
* Expose asynchronous HomeKit startup failures through `HomekitRoot.startAsync()` and clean up failed starts
3+
* Synchronous startup exceptions are also reported through the returned future; duplicate starts fail without stopping an existing startup or listener
4+
* 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
5+
* Recovery is not automatic: integrations must create a new server and root for another attempt because the default HTTP handler cannot be restarted
26
* Add constructors with custom min/max to the window covering tilt angle characteristics [#162](https://github.com/hap-java/HAP-Java/issues/162)
37
* Add optional Mute characteristic to Doorbell service
48
* Fix leak of mDNS instances and shutdown hooks when stopping `HomekitRoot`

‎src/main/java/io/github/hapjava/server/impl/HomekitRoot.java‎

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser;
1111
import java.io.IOException;
1212
import java.net.InetAddress;
13+
import java.util.concurrent.CompletableFuture;
14+
import java.util.concurrent.CompletionException;
1315
import javax.jmdns.JmDNS;
1416
import org.slf4j.Logger;
1517
import org.slf4j.LoggerFactory;
@@ -158,14 +160,55 @@ public void removeAccessory(HomekitAccessory accessory) {
158160
* call this after you have used the {@link #addAccessory(HomekitAccessory)} method to add all the
159161
* initial accessories you plan on advertising, as any later additions will cause the HomeKit
160162
* clients to reconnect.
163+
*
164+
* <p>Startup failures are logged. Use {@link #startAsync()} to handle them in the caller. An
165+
* advertising failure also stops the HTTP listener. Recovery is not automatic and requires a new
166+
* server and root.
161167
*/
162168
public void start() {
169+
startAsync()
170+
.whenComplete(
171+
(ignored, error) -> {
172+
if (error != null) {
173+
logger.error("Could not start HomeKit root {}", label, error);
174+
}
175+
});
176+
}
177+
178+
/**
179+
* Starts handling and advertising the previously added HomeKit accessories.
180+
*
181+
* <p>Startup failures, including exceptions thrown before the HTTP handler returns a future,
182+
* complete the returned future exceptionally after cleanup. If advertising fails after the HTTP
183+
* listener has started, the listener is stopped as well. Recovery requires a new server and root;
184+
* the default HTTP handler cannot be restarted.
185+
*
186+
* <p>A start requested while this root is starting or running fails without stopping the existing
187+
* startup or listener.
188+
*
189+
* @return a future that completes after the HTTP listener has started and the advertiser has
190+
* registered the service, or exceptionally after a failed start has been cleaned up
191+
*/
192+
public CompletableFuture<Void> startAsync() {
193+
if (started) {
194+
CompletableFuture<Void> failure = new CompletableFuture<>();
195+
failure.completeExceptionally(new IllegalStateException("HomeKit root is already started"));
196+
return failure;
197+
}
163198
started = true;
164-
madeChanges = false;
165-
registry.reset();
166-
webHandler
167-
.start(
168-
new HomekitClientConnectionFactoryImpl(authInfo, registry, subscriptions, advertiser))
199+
CompletableFuture<Integer> portFuture;
200+
try {
201+
madeChanges = false;
202+
registry.reset();
203+
portFuture =
204+
webHandler.start(
205+
new HomekitClientConnectionFactoryImpl(
206+
authInfo, registry, subscriptions, advertiser));
207+
} catch (RuntimeException e) {
208+
portFuture = new CompletableFuture<>();
209+
portFuture.completeExceptionally(e);
210+
}
211+
return portFuture
169212
.thenAccept(
170213
port -> {
171214
try {
@@ -178,7 +221,14 @@ public void start() {
178221
configurationIndex,
179222
authInfo.getSetupId());
180223
} catch (Exception e) {
181-
throw new RuntimeException(e);
224+
throw new CompletionException(e);
225+
}
226+
})
227+
.whenComplete(
228+
(ignored, error) -> {
229+
if (error != null) {
230+
started = false;
231+
stop();
182232
}
183233
});
184234
}

‎src/test/java/io/github/hapjava/server/impl/HomekitRootTest.java‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
package io.github.hapjava.server.impl;
22

33
import static org.mockito.Matchers.any;
4+
import static org.mockito.Matchers.anyInt;
45
import static org.mockito.Matchers.eq;
6+
import static org.mockito.Mockito.doThrow;
57
import static org.mockito.Mockito.mock;
68
import static org.mockito.Mockito.never;
9+
import static org.mockito.Mockito.times;
710
import static org.mockito.Mockito.verify;
811
import static org.mockito.Mockito.when;
912

@@ -13,7 +16,10 @@
1316
import io.github.hapjava.server.HomekitWebHandler;
1417
import io.github.hapjava.server.impl.http.HomekitClientConnectionFactory;
1518
import io.github.hapjava.server.impl.jmdns.JmdnsHomekitAdvertiser;
19+
import java.io.IOException;
20+
import java.net.BindException;
1621
import java.util.concurrent.CompletableFuture;
22+
import java.util.concurrent.CompletionException;
1723
import org.junit.Assert;
1824
import org.junit.Before;
1925
import org.junit.Test;
@@ -66,6 +72,140 @@ public void testWebHandlerStarts() throws Exception {
6672
verify(webHandler).start(any(HomekitClientConnectionFactory.class));
6773
}
6874

75+
@Test
76+
public void testFailedWebHandlerStartIsCleanedUp() throws Exception {
77+
CompletableFuture<Integer> bind = new CompletableFuture<>();
78+
when(webHandler.start(any())).thenReturn(bind);
79+
80+
root.start();
81+
bind.completeExceptionally(new BindException("Address not available"));
82+
83+
verify(webHandler).stop();
84+
verify(advertiser).stop();
85+
root.setConfigurationIndex(2);
86+
verify(advertiser, never()).setConfigurationIndex(2);
87+
}
88+
89+
@Test
90+
public void testStartAsyncWaitsForWebHandler() throws Exception {
91+
CompletableFuture<Integer> bind = new CompletableFuture<>();
92+
when(webHandler.start(any())).thenReturn(bind);
93+
94+
CompletableFuture<Void> start = root.startAsync();
95+
96+
Assert.assertFalse(start.isDone());
97+
verify(advertiser, never()).advertise(any(), anyInt(), any(), anyInt(), anyInt(), any());
98+
99+
bind.complete(PORT);
100+
101+
start.join();
102+
verify(advertiser).advertise(eq(LABEL), eq(1), any(), eq(PORT), eq(1), any());
103+
verify(webHandler, never()).stop();
104+
}
105+
106+
@Test
107+
public void testStartAsyncPropagatesBindFailure() throws Exception {
108+
CompletableFuture<Integer> bind = new CompletableFuture<>();
109+
when(webHandler.start(any())).thenReturn(bind);
110+
BindException failure = new BindException("Address not available");
111+
112+
CompletableFuture<Void> start = root.startAsync();
113+
bind.completeExceptionally(failure);
114+
115+
Assert.assertSame(
116+
failure, Assert.assertThrows(CompletionException.class, start::join).getCause());
117+
verify(webHandler).stop();
118+
verify(advertiser).stop();
119+
verify(advertiser, never()).advertise(any(), anyInt(), any(), anyInt(), anyInt(), any());
120+
root.setConfigurationIndex(2);
121+
verify(advertiser, never()).setConfigurationIndex(2);
122+
}
123+
124+
@Test
125+
public void testStartAsyncPropagatesSynchronousFailure() throws Exception {
126+
RuntimeException failure = new IllegalStateException("HTTP startup failed");
127+
when(webHandler.start(any())).thenThrow(failure);
128+
129+
CompletableFuture<Void> start = root.startAsync();
130+
131+
Assert.assertTrue(start.isCompletedExceptionally());
132+
Assert.assertSame(
133+
failure, Assert.assertThrows(CompletionException.class, start::join).getCause());
134+
verify(webHandler).stop();
135+
verify(advertiser).stop();
136+
verify(advertiser, never()).advertise(any(), anyInt(), any(), anyInt(), anyInt(), any());
137+
root.setConfigurationIndex(2);
138+
verify(advertiser, never()).setConfigurationIndex(2);
139+
}
140+
141+
@Test
142+
public void testStartCleansUpSynchronousFailure() throws Exception {
143+
when(webHandler.start(any())).thenThrow(new IllegalStateException("HTTP startup failed"));
144+
145+
root.start();
146+
147+
verify(webHandler).stop();
148+
verify(advertiser).stop();
149+
root.setConfigurationIndex(2);
150+
verify(advertiser, never()).setConfigurationIndex(2);
151+
}
152+
153+
@Test
154+
public void testDuplicateStartDoesNotStopPendingStartup() throws Exception {
155+
CompletableFuture<Integer> bind = new CompletableFuture<>();
156+
when(webHandler.start(any())).thenReturn(bind);
157+
158+
CompletableFuture<Void> first = root.startAsync();
159+
CompletableFuture<Void> duplicate = root.startAsync();
160+
161+
Assert.assertTrue(duplicate.isCompletedExceptionally());
162+
Assert.assertTrue(
163+
Assert.assertThrows(CompletionException.class, duplicate::join).getCause()
164+
instanceof IllegalStateException);
165+
Assert.assertFalse(first.isDone());
166+
verify(webHandler, times(1)).start(any());
167+
verify(webHandler, never()).stop();
168+
verify(advertiser, never()).stop();
169+
170+
bind.complete(PORT);
171+
172+
Assert.assertTrue(first.isDone());
173+
first.join();
174+
verify(advertiser).advertise(eq(LABEL), eq(1), any(), eq(PORT), eq(1), any());
175+
}
176+
177+
@Test
178+
public void testDuplicateStartDoesNotStopRunningRoot() throws Exception {
179+
root.startAsync().join();
180+
181+
CompletableFuture<Void> duplicate = root.startAsync();
182+
183+
Assert.assertTrue(duplicate.isCompletedExceptionally());
184+
Assert.assertTrue(
185+
Assert.assertThrows(CompletionException.class, duplicate::join).getCause()
186+
instanceof IllegalStateException);
187+
verify(webHandler, times(1)).start(any());
188+
verify(webHandler, never()).stop();
189+
verify(advertiser, never()).stop();
190+
root.setConfigurationIndex(2);
191+
verify(advertiser).setConfigurationIndex(2);
192+
}
193+
194+
@Test
195+
public void testStartAsyncPropagatesAdvertisingFailure() throws Exception {
196+
IOException failure = new IOException("mDNS registration failed");
197+
doThrow(failure).when(advertiser).advertise(any(), anyInt(), any(), anyInt(), anyInt(), any());
198+
199+
CompletableFuture<Void> start = root.startAsync();
200+
201+
Assert.assertSame(
202+
failure, Assert.assertThrows(CompletionException.class, start::join).getCause());
203+
verify(webHandler).stop();
204+
verify(advertiser).stop();
205+
root.setConfigurationIndex(2);
206+
verify(advertiser, never()).setConfigurationIndex(2);
207+
}
208+
69209
@Test
70210
public void testWebHandlerStops() throws Exception {
71211
root.start();

0 commit comments

Comments
 (0)