Repository navigation
Expand file tree
/
Copy pathEnvironmentWorkerTest.java
More file actions
292 lines (252 loc) · 11 KB
/
Copy pathEnvironmentWorkerTest.java
File metadata and controls
292 lines (252 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright (c) 2026 ByteDance Ltd. and/or its affiliates.
// SPDX-License-Identifier: Apache-2.0
package com.volcengine.ark.runtime.selfhosted;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.volcengine.ark.runtime.models.environment.HeartbeatWorkResponse;
import com.volcengine.ark.runtime.models.environment.WorkState;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.junit.Test;
public class EnvironmentWorkerTest {
@Test
public void emptyHeartbeatResponseDoesNotSpin() throws Exception {
NullHeartbeatClient client = new NullHeartbeatClient();
EnvironmentWorker worker = new EnvironmentWorker(
client,
new EnvironmentWorker.Options().workdir(Files.createTempDirectory("ark-java-worker-").toString()));
try {
worker.handleItem(new EnvironmentWorker.HandleItemOptions()
.environmentId("env-1")
.workId("work-1")
.sessionId("session-1"));
} catch (IOException expected) {
assertTrue(expected.getMessage().contains("session response is empty"));
}
assertEquals(1, client.heartbeats.get());
}
@Test
public void heartbeatStopCancelsRunnerBeforeEventPolling() throws Exception {
CountDownLatch heartbeat = new CountDownLatch(1);
AtomicInteger lists = new AtomicInteger();
AtomicInteger stops = new AtomicInteger();
OkHttpClient http = new OkHttpClient.Builder().addInterceptor(chain -> {
Request request = chain.request();
String path = request.url().encodedPath();
if (path.endsWith("/heartbeat")) {
heartbeat.countDown();
return response(request, "{\"state\":\"stopping\",\"lease_extended\":true}");
}
if (path.endsWith("/sessions/session-1")) {
try {
assertTrue(heartbeat.await(2, TimeUnit.SECONDS));
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new IOException(error);
}
return response(request, "{\"id\":\"session-1\"}");
}
if (path.endsWith("/events")) {
lists.incrementAndGet();
return response(request, "{\"data\":[]}");
}
if (path.endsWith("/stop")) {
stops.incrementAndGet();
}
return response(request, "{}");
}).build();
SelfHostedClient client = new SelfHostedClient.Builder()
.apiKey("test-key")
.baseUrl("https://ark.example.com/api/v3")
.httpClient(http)
.build();
EnvironmentWorker worker = new EnvironmentWorker(
client,
new EnvironmentWorker.Options().workdir(Files.createTempDirectory("ark-java-worker-").toString()));
long started = System.nanoTime();
worker.handleItem(new EnvironmentWorker.HandleItemOptions()
.environmentId("env-1")
.workId("work-1")
.sessionId("session-1"));
assertTrue(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started) < 1000L);
assertEquals(0, lists.get());
assertEquals(1, stops.get());
}
@Test
public void leaseLostDoesNotStopWorkOwnedByAnotherWorker() throws Exception {
LeaseLostClient client = new LeaseLostClient();
EnvironmentWorker worker = new EnvironmentWorker(
client,
new EnvironmentWorker.Options()
.workdir(Files.createTempDirectory("ark-java-worker-").toString()));
worker.handleItem(new EnvironmentWorker.HandleItemOptions()
.environmentId("env-1")
.workId("work-1")
.sessionId("session-1"));
assertEquals(0, client.stops.get());
}
@Test
public void leaseNotExtendedWithoutTtlDoesNotStopWorkOwnedByAnotherWorker() throws Exception {
LeaseNotExtendedClient client = new LeaseNotExtendedClient();
EnvironmentWorker worker = new EnvironmentWorker(
client,
new EnvironmentWorker.Options()
.workdir(Files.createTempDirectory("ark-java-worker-").toString()));
worker.handleItem(new EnvironmentWorker.HandleItemOptions()
.environmentId("env-1")
.workId("work-1")
.sessionId("session-1"));
assertEquals(0, client.stops.get());
}
@Test
public void workerToolTimeoutOverridesToolContext() throws Exception {
ToolContext baseContext = new ToolContext(".");
baseContext.setToolTimeoutMillis(5000L);
EnvironmentWorker worker = new EnvironmentWorker(
new SelfHostedClient("test-key"),
new EnvironmentWorker.Options()
.toolContext(baseContext)
.toolTimeoutMillis(20L));
Method method = EnvironmentWorker.class.getDeclaredMethod(
"toolContext", String.class, AtomicBoolean.class);
method.setAccessible(true);
ToolContext context = (ToolContext) method.invoke(worker, ".", new AtomicBoolean(false));
assertEquals(20L, context.getToolTimeoutMillis());
}
@Test
public void workerKeepsToolContextTimeoutWhenUnset() throws Exception {
ToolContext baseContext = new ToolContext(".");
baseContext.setToolTimeoutMillis(5000L);
EnvironmentWorker worker = new EnvironmentWorker(
new SelfHostedClient("test-key"),
new EnvironmentWorker.Options().toolContext(baseContext));
Method method = EnvironmentWorker.class.getDeclaredMethod(
"toolContext", String.class, AtomicBoolean.class);
method.setAccessible(true);
ToolContext context = (ToolContext) method.invoke(worker, ".", new AtomicBoolean(false));
assertEquals(5000L, context.getToolTimeoutMillis());
}
@Test
public void workerKeepsToolContextTimeoutWhenNonpositive() throws Exception {
ToolContext baseContext = new ToolContext(".");
baseContext.setToolTimeoutMillis(5000L);
EnvironmentWorker worker = new EnvironmentWorker(
new SelfHostedClient("test-key"),
new EnvironmentWorker.Options()
.toolContext(baseContext)
.toolTimeoutMillis(-1L));
Method method = EnvironmentWorker.class.getDeclaredMethod(
"toolContext", String.class, AtomicBoolean.class);
method.setAccessible(true);
ToolContext context = (ToolContext) method.invoke(worker, ".", new AtomicBoolean(false));
assertEquals(5000L, context.getToolTimeoutMillis());
}
private static Response response(Request request, String body) throws IOException {
return new Response.Builder()
.request(request)
.protocol(Protocol.HTTP_1_1)
.code(200)
.message("OK")
.body(ResponseBody.create(MediaType.parse("application/json"), body))
.build();
}
private static class NullHeartbeatClient extends SelfHostedClient {
private final CountDownLatch firstHeartbeat = new CountDownLatch(1);
private final AtomicInteger heartbeats = new AtomicInteger();
NullHeartbeatClient() {
super("test-key");
}
@Override
public HeartbeatWorkResponse heartbeatWork(
String environmentId, String workId, String expectedLastHeartbeat, int desiredTTLSeconds) {
heartbeats.incrementAndGet();
firstHeartbeat.countDown();
return null;
}
@Override
public SessionSnapshot getSession(String sessionId) {
try {
assertTrue(firstHeartbeat.await(2, TimeUnit.SECONDS));
Thread.sleep(100L);
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new RuntimeException(error);
}
return null;
}
@Override
public void stopWork(String environmentId, String workId, boolean force) {
}
}
private static class LeaseLostClient extends SelfHostedClient {
private final CountDownLatch heartbeat = new CountDownLatch(1);
private final AtomicInteger stops = new AtomicInteger();
LeaseLostClient() {
super("test-key");
}
@Override
public HeartbeatWorkResponse heartbeatWork(
String environmentId, String workId, String expectedLastHeartbeat, int desiredTTLSeconds) {
heartbeat.countDown();
throw new WorkerAPIException(412, "lease lost", "");
}
@Override
public SessionSnapshot getSession(String sessionId) {
try {
assertTrue(heartbeat.await(2, TimeUnit.SECONDS));
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new RuntimeException(error);
}
SessionSnapshot session = new SessionSnapshot();
session.setId(sessionId);
return session;
}
@Override
public void stopWork(String environmentId, String workId, boolean force) {
stops.incrementAndGet();
}
}
private static class LeaseNotExtendedClient extends SelfHostedClient {
private final CountDownLatch heartbeat = new CountDownLatch(1);
private final AtomicInteger stops = new AtomicInteger();
LeaseNotExtendedClient() {
super("test-key");
}
@Override
public HeartbeatWorkResponse heartbeatWork(
String environmentId, String workId, String expectedLastHeartbeat, int desiredTTLSeconds) {
heartbeat.countDown();
return new HeartbeatWorkResponse()
.state(WorkState.ACTIVE)
.leaseExtended(Boolean.FALSE);
}
@Override
public SessionSnapshot getSession(String sessionId) {
try {
assertTrue(heartbeat.await(2, TimeUnit.SECONDS));
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new RuntimeException(error);
}
SessionSnapshot session = new SessionSnapshot();
session.setId(sessionId);
return session;
}
@Override
public void stopWork(String environmentId, String workId, boolean force) {
stops.incrementAndGet();
}
}
}