Skip to content

Commit 359d270

Browse files
feat!: vendor DriverService and ExternalProcess for the local Appium service
AppiumDriverLocalService and AppiumServiceBuilder no longer extend Selenium's DriverService and DriverService.Builder. The service was already final and overrode start/stop/isRunning/getUrl, so no shared base type is introduced. ExternalProcess is a trimmed copy of selenium-os's, and start() now throws IOException so a failed launch is reported as AppiumServerHasNotBeenStartedLocallyException rather than a raw UncheckedIOException. Free ports come from ServerSocket(0). selenium-os stays on the classpath transitively until the remote-driver dependency is removed. BREAKING CHANGE: AppiumDriverLocalService and AppiumServiceBuilder are no longer DriverService types. Removed getExecutable, setExecutable, sendOutputTo, getDriverProperty, getDriverEnvironmentVariable, score and withLogOutput. AppiumCommandExecutor constructors now take AppiumDriverLocalService instead of DriverService. close() on the service now stops the server. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent dc77ecf commit 359d270

6 files changed

Lines changed: 566 additions & 95 deletions

File tree

Lines changed: 268 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,268 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* See the NOTICE file distributed with this work for additional
5+
* information regarding copyright ownership.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package io.appium.java_client.internal.process;
18+
19+
import org.jspecify.annotations.Nullable;
20+
import org.slf4j.Logger;
21+
import org.slf4j.LoggerFactory;
22+
23+
import java.io.IOException;
24+
import java.io.InputStream;
25+
import java.io.OutputStream;
26+
import java.nio.charset.Charset;
27+
import java.time.Duration;
28+
import java.util.ArrayList;
29+
import java.util.List;
30+
import java.util.Map;
31+
32+
import static java.util.concurrent.TimeUnit.MILLISECONDS;
33+
34+
/**
35+
* A child process whose combined stdout/stderr is forwarded to a stream and
36+
* also retained (last bytes only) for diagnostics. Trimmed from Selenium's
37+
* {@code org.openqa.selenium.os.ExternalProcess} (Apache License 2.0).
38+
*/
39+
public final class ExternalProcess {
40+
private static final Logger LOG = LoggerFactory.getLogger(ExternalProcess.class);
41+
private static final int OUTPUT_BUFFER_SIZE = 32768;
42+
private static final Duration DEFAULT_SHUTDOWN_TIMEOUT = Duration.ofSeconds(4);
43+
44+
private final Process process;
45+
private final TailBuffer output;
46+
private final Thread worker;
47+
48+
private ExternalProcess(Process process, TailBuffer output, Thread worker) {
49+
this.process = process;
50+
this.output = output;
51+
this.worker = worker;
52+
}
53+
54+
public static Builder builder() {
55+
return new Builder();
56+
}
57+
58+
/**
59+
* The last bytes of the combined stdout and stderr.
60+
*
61+
* @return the output decoded with the default charset
62+
*/
63+
public String getOutput() {
64+
return output.toString(Charset.defaultCharset());
65+
}
66+
67+
public boolean isAlive() {
68+
return process.isAlive();
69+
}
70+
71+
/**
72+
* Waits for the process to exit and its output to be fully forwarded.
73+
*
74+
* @param timeout how long to wait
75+
* @return true if the process has exited
76+
*/
77+
public boolean waitFor(Duration timeout) {
78+
boolean exited = awaitExit(timeout);
79+
if (exited) {
80+
stopWorker();
81+
}
82+
return exited;
83+
}
84+
85+
/**
86+
* Terminates the process gracefully, then forcibly if it is still alive after the default timeout.
87+
*/
88+
public void shutdown() {
89+
shutdown(DEFAULT_SHUTDOWN_TIMEOUT);
90+
}
91+
92+
/**
93+
* Terminates the process gracefully, then forcibly if it is still alive after the given timeout.
94+
*
95+
* @param timeout how long to wait for each termination attempt
96+
*/
97+
public void shutdown(Duration timeout) {
98+
try {
99+
// Use the handle to avoid closing the process streams
100+
var handle = process.toHandle();
101+
if (handle.supportsNormalTermination()) {
102+
handle.destroy();
103+
if (awaitExit(timeout)) {
104+
return;
105+
}
106+
}
107+
handle.destroyForcibly();
108+
awaitExit(timeout);
109+
} finally {
110+
stopWorker();
111+
}
112+
}
113+
114+
private boolean awaitExit(Duration timeout) {
115+
try {
116+
return process.waitFor(timeout.toMillis(), MILLISECONDS);
117+
} catch (InterruptedException e) {
118+
Thread.currentThread().interrupt();
119+
return false;
120+
}
121+
}
122+
123+
private void stopWorker() {
124+
try {
125+
worker.join(8000);
126+
} catch (InterruptedException e) {
127+
Thread.currentThread().interrupt();
128+
} finally {
129+
// No-op if the worker has finished, otherwise unblocks it
130+
worker.interrupt();
131+
try {
132+
worker.join(2000);
133+
} catch (InterruptedException e) {
134+
Thread.currentThread().interrupt();
135+
}
136+
}
137+
}
138+
139+
public static final class Builder {
140+
private final ProcessBuilder builder = new ProcessBuilder();
141+
private @Nullable OutputStream copyOutputTo;
142+
143+
private Builder() {
144+
}
145+
146+
/**
147+
* Sets the executable and its arguments.
148+
*
149+
* @param executable the executable path
150+
* @param arguments the executable arguments
151+
* @return this instance
152+
*/
153+
public Builder command(String executable, List<String> arguments) {
154+
var command = new ArrayList<String>(arguments.size() + 1);
155+
command.add(executable);
156+
command.addAll(arguments);
157+
builder.command(command);
158+
return this;
159+
}
160+
161+
public Builder environment(String name, String value) {
162+
builder.environment().put(name, value);
163+
return this;
164+
}
165+
166+
public Builder environment(Map<String, String> environment) {
167+
environment.forEach(this::environment);
168+
return this;
169+
}
170+
171+
/**
172+
* Sets where to forward the combined stdout and stderr.
173+
* The stream is never closed by the process.
174+
*
175+
* @param stream the destination stream
176+
* @return this instance
177+
*/
178+
public Builder copyOutputTo(OutputStream stream) {
179+
copyOutputTo = stream;
180+
return this;
181+
}
182+
183+
/**
184+
* Starts the process.
185+
*
186+
* @return the running process
187+
* @throws IOException if the process cannot be started
188+
*/
189+
public ExternalProcess start() throws IOException {
190+
builder.redirectErrorStream(true);
191+
var process = builder.start();
192+
try {
193+
var buffer = new TailBuffer(OUTPUT_BUFFER_SIZE);
194+
var worker = new Thread(
195+
() -> forwardOutput(process, buffer, copyOutputTo),
196+
"External Process Output Forwarder - " + builder.command().get(0)
197+
);
198+
worker.setDaemon(true);
199+
worker.start();
200+
return new ExternalProcess(process, buffer, worker);
201+
} catch (Throwable t) {
202+
// Do not leak the process if the worker could not be started
203+
process.destroyForcibly();
204+
throw t;
205+
}
206+
}
207+
208+
private static void forwardOutput(Process process, TailBuffer buffer, @Nullable OutputStream target) {
209+
// The process output must always be drained, otherwise the process may block
210+
InputStream input = process.getInputStream();
211+
var chunk = new byte[8192];
212+
try {
213+
int count;
214+
while ((count = input.read(chunk)) != -1) {
215+
buffer.write(chunk, 0, count);
216+
if (target != null) {
217+
target.write(chunk, 0, count);
218+
}
219+
}
220+
} catch (IOException e) {
221+
LOG.warn("Failed to copy the output of process {}", process.pid(), e);
222+
}
223+
LOG.debug("Completed copying the output of process {}", process.pid());
224+
}
225+
}
226+
227+
/**
228+
* Keeps the last N bytes written to it.
229+
*/
230+
private static final class TailBuffer extends OutputStream {
231+
private final byte[] buffer;
232+
private int end;
233+
private boolean filled;
234+
235+
TailBuffer(int size) {
236+
this.buffer = new byte[size];
237+
}
238+
239+
@Override
240+
public synchronized void write(int b) {
241+
if (end == buffer.length) {
242+
filled = true;
243+
end = 0;
244+
}
245+
buffer[end++] = (byte) b;
246+
}
247+
248+
@Override
249+
public synchronized void write(byte[] b, int off, int len) {
250+
// Only the last buffer.length bytes can survive
251+
int skip = Math.max(0, len - buffer.length);
252+
for (int i = off + skip; i < off + len; i++) {
253+
write(b[i]);
254+
}
255+
}
256+
257+
synchronized String toString(Charset encoding) {
258+
if (!filled) {
259+
return new String(buffer, 0, end, encoding);
260+
}
261+
var result = new byte[buffer.length];
262+
int tail = buffer.length - end;
263+
System.arraycopy(buffer, end, result, 0, tail);
264+
System.arraycopy(buffer, 0, result, tail, end);
265+
return new String(result, encoding);
266+
}
267+
}
268+
}

‎src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java‎

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import io.appium.java_client.AppiumClientConfig;
2121
import io.appium.java_client.internal.DirectConnectUrlSafety;
2222
import io.appium.java_client.internal.ReflectionHelpers;
23+
import io.appium.java_client.service.local.AppiumDriverLocalService;
2324
import lombok.Getter;
2425
import org.jspecify.annotations.NullMarked;
2526
import org.jspecify.annotations.Nullable;
@@ -40,7 +41,6 @@
4041
import org.openqa.selenium.remote.http.HttpClient.Factory;
4142
import org.openqa.selenium.remote.http.HttpRequest;
4243
import org.openqa.selenium.remote.http.HttpResponse;
43-
import org.openqa.selenium.remote.service.DriverService;
4444

4545
import java.io.IOException;
4646
import java.net.ConnectException;
@@ -57,21 +57,21 @@
5757
@NullMarked
5858
public class AppiumCommandExecutor extends HttpCommandExecutor {
5959

60-
private final Optional<DriverService> serviceOptional;
60+
private final Optional<AppiumDriverLocalService> serviceOptional;
6161
@Getter
6262
private final AppiumClientConfig appiumClientConfig;
6363

6464
/**
6565
* Create an AppiumCommandExecutor instance.
6666
*
6767
* @param additionalCommands is the map of Appium commands
68-
* @param service take a look at {@link DriverService}
68+
* @param service take a look at {@link AppiumDriverLocalService}
6969
* @param httpClientFactory take a look at {@link Factory}
7070
* @param appiumClientConfig take a look at {@link AppiumClientConfig}
7171
*/
7272
public AppiumCommandExecutor(
7373
Map<String, CommandInfo> additionalCommands,
74-
@Nullable DriverService service,
74+
@Nullable AppiumDriverLocalService service,
7575
@Nullable Factory httpClientFactory,
7676
AppiumClientConfig appiumClientConfig) {
7777
super(additionalCommands,
@@ -83,7 +83,7 @@ public AppiumCommandExecutor(
8383
this.appiumClientConfig = appiumClientConfig;
8484
}
8585

86-
public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service,
86+
public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, AppiumDriverLocalService service,
8787
@Nullable Factory httpClientFactory) {
8888
this(additionalCommands, requireNonNull(service), httpClientFactory,
8989
AppiumClientConfig.defaultConfig().baseUrl(requireNonNull(service).getUrl()));
@@ -110,13 +110,13 @@ public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, URL ad
110110
appiumClientConfig.baseUrl(requireNonNull(addressOfRemoteServer)));
111111
}
112112

113-
public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, DriverService service) {
113+
public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands, AppiumDriverLocalService service) {
114114
this(additionalCommands, service, HttpClient.Factory.createDefault(),
115115
AppiumClientConfig.defaultConfig().baseUrl(service.getUrl()));
116116
}
117117

118118
public AppiumCommandExecutor(Map<String, CommandInfo> additionalCommands,
119-
DriverService service, AppiumClientConfig appiumClientConfig) {
119+
AppiumDriverLocalService service, AppiumClientConfig appiumClientConfig) {
120120
this(additionalCommands, service, HttpClient.Factory.createDefault(), appiumClientConfig);
121121
}
122122

@@ -230,13 +230,7 @@ private void setDirectConnect(Response response) throws SessionNotCreatedExcepti
230230
@Override
231231
public Response execute(Command command) throws WebDriverException {
232232
if (DriverCommand.NEW_SESSION.equals(command.getName())) {
233-
serviceOptional.ifPresent(driverService -> {
234-
try {
235-
driverService.start();
236-
} catch (IOException e) {
237-
throw new WebDriverException(e.getMessage(), e);
238-
}
239-
});
233+
serviceOptional.ifPresent(AppiumDriverLocalService::start);
240234
}
241235

242236
try {
@@ -257,7 +251,7 @@ public Response execute(Command command) throws WebDriverException {
257251
throw new WebDriverException(t);
258252
} finally {
259253
if (DriverCommand.QUIT.equals(command.getName())) {
260-
serviceOptional.ifPresent(DriverService::stop);
254+
serviceOptional.ifPresent(AppiumDriverLocalService::stop);
261255
}
262256
}
263257
}

0 commit comments

Comments
 (0)