|
| 1 | +package io.github.easy4j.opencli.center.ws; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.JsonNode; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import io.github.easy4j.opencli.OpenCliProperties; |
| 6 | +import io.github.easy4j.opencli.contract.ContractProbe; |
| 7 | +import java.io.File; |
| 8 | +import java.io.IOException; |
| 9 | +import java.net.InetSocketAddress; |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | +import java.util.Arrays; |
| 12 | +import java.util.Base64; |
| 13 | +import java.util.List; |
| 14 | +import java.util.Objects; |
| 15 | +import java.util.concurrent.BlockingQueue; |
| 16 | +import java.util.concurrent.CountDownLatch; |
| 17 | +import java.util.concurrent.LinkedBlockingQueue; |
| 18 | +import java.util.concurrent.TimeUnit; |
| 19 | +import java.util.concurrent.atomic.AtomicReference; |
| 20 | +import java.util.stream.Collectors; |
| 21 | +import org.java_websocket.WebSocket; |
| 22 | +import org.java_websocket.handshake.ClientHandshake; |
| 23 | +import org.java_websocket.server.WebSocketServer; |
| 24 | +import org.junit.jupiter.api.Test; |
| 25 | + |
| 26 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 27 | +import static org.junit.jupiter.api.Assertions.assertFalse; |
| 28 | +import static org.junit.jupiter.api.Assertions.assertNotNull; |
| 29 | +import static org.junit.jupiter.api.Assertions.assertNotSame; |
| 30 | +import static org.junit.jupiter.api.Assertions.assertNull; |
| 31 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 32 | + |
| 33 | +class OpenCliWsReverseAgentSessionTest { |
| 34 | + |
| 35 | + private static final ObjectMapper MAPPER = new ObjectMapper(); |
| 36 | + private static final String AGENT_URL = "http://127.0.0.1:19823"; |
| 37 | + |
| 38 | + @Test |
| 39 | + void exchangesRegistrationAndCollectResultsAndReconnectsAfterRemoteClose() throws Exception { |
| 40 | + try (LocalCenter center = new LocalCenter()) { |
| 41 | + OpenCliWsAgentConnectionProperties connection = center.agentProperties(); |
| 42 | + connection.setMode(""); |
| 43 | + connection.setNodeType(""); |
| 44 | + connection.setLabel(null); |
| 45 | + try (OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient(probe(ContractProbe.class.getName()), connection)) { |
| 46 | + agent.start(); |
| 47 | + WireMessage registration = center.receive("register"); |
| 48 | + assertEquals(AGENT_URL, registration.body.path("agent_url").asText()); |
| 49 | + assertEquals("cdp", registration.body.path("mode").asText()); |
| 50 | + assertEquals("shell", registration.body.path("node_type").asText()); |
| 51 | + assertTrue(registration.body.path("label").asText().isEmpty()); |
| 52 | + |
| 53 | + registration.socket.send("{\"type\":\"registered\"}"); |
| 54 | + agent.start(); |
| 55 | + registration.socket.send("malformed-json"); |
| 56 | + registration.socket.send("{\"type\":\"pong\"}"); |
| 57 | + registration.socket.send("{\"type\":\"ping\"}"); |
| 58 | + center.receive("pong"); |
| 59 | + |
| 60 | + registration.socket.send("{\"type\":\"collect\",\"request_id\":\"valid\"," |
| 61 | + + "\"site\":\"demo\",\"command\":\"echo\",\"format\":\"text\"," |
| 62 | + + "\"positional_args\":[\" kept \",null,42],\"args\":{" |
| 63 | + + "\"flag\":null,\"boolean\":false,\"count\":7,\"long\":2147483648," |
| 64 | + + "\"double\":1.5,\"text\":\"a b\",\"structured\":{\"key\":1}}}"); |
| 65 | + JsonNode result = center.receive("result").body; |
| 66 | + assertEquals("valid", result.path("request_id").asText()); |
| 67 | + assertTrue(result.path("success").asBoolean()); |
| 68 | + assertTrue(result.path("error").isNull()); |
| 69 | + List<String> argv = Arrays.stream(result.path("items").get(0).path("content").asText().split("\\R")) |
| 70 | + .filter(line -> line.startsWith("arg:")) |
| 71 | + .map(line -> new String(Base64.getDecoder().decode(line.substring(4)), StandardCharsets.UTF_8)) |
| 72 | + .collect(Collectors.toList()); |
| 73 | + assertEquals(Arrays.asList("demo", "echo", " kept ", "42", "--flag", "--boolean", |
| 74 | + "false", "--count", "7", "--long", "2147483648", "--double", "1.5", "--text", |
| 75 | + "a b", "--structured", "{\"key\":1}", "-f", "text"), argv); |
| 76 | + |
| 77 | + registration.socket.send("{\"type\":\"collect\",\"request_id\":\"invalid\",\"command\":\"echo\"}"); |
| 78 | + JsonNode invalid = center.receive("result").body; |
| 79 | + assertEquals("invalid", invalid.path("request_id").asText()); |
| 80 | + assertFalse(invalid.path("success").asBoolean()); |
| 81 | + assertTrue(invalid.path("items").isEmpty()); |
| 82 | + assertEquals("collect execution failed", invalid.path("error").asText()); |
| 83 | + |
| 84 | + registration.socket.close(); |
| 85 | + WireMessage retry = center.receive("register"); |
| 86 | + assertNotSame(registration.socket, retry.socket); |
| 87 | + assertEquals(registration.body, retry.body); |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + @Test |
| 93 | + void retriesAfterHandshakeCloseAndReturnsChildFailureToCenter() throws Exception { |
| 94 | + try (LocalCenter center = new LocalCenter(); |
| 95 | + OpenCliWsReverseAgentClient agent = new OpenCliWsReverseAgentClient( |
| 96 | + probe("io.github.easy4j.opencli.contract.MissingFixture"), center.agentProperties())) { |
| 97 | + agent.start(); |
| 98 | + WireMessage first = center.receive("register"); |
| 99 | + first.socket.close(); |
| 100 | + WireMessage second = center.receive("register"); |
| 101 | + assertNotSame(first.socket, second.socket); |
| 102 | + second.socket.send("{\"type\":\"registered\"}"); |
| 103 | + second.socket.send("{\"type\":\"collect\",\"request_id\":\"child-failure\"," |
| 104 | + + "\"site\":\"demo\",\"command\":\"echo\"}"); |
| 105 | + JsonNode result = center.receive("result").body; |
| 106 | + assertEquals("child-failure", result.path("request_id").asText()); |
| 107 | + assertFalse(result.path("success").asBoolean()); |
| 108 | + assertTrue(result.path("items").isEmpty()); |
| 109 | + assertTrue(result.path("error").asText().contains("io.github.easy4j.opencli.contract.MissingFixture")); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + private static OpenCliProperties probe(String mainClass) { |
| 114 | + OpenCliProperties properties = new OpenCliProperties(); |
| 115 | + String executable = System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java"; |
| 116 | + properties.setExecutable(new File(new File(System.getProperty("java.home"), "bin"), executable).getAbsolutePath()); |
| 117 | + properties.setLeadingArguments(Arrays.asList("-cp", |
| 118 | + System.getProperty("surefire.test.class.path", System.getProperty("java.class.path")), mainClass)); |
| 119 | + properties.setCommandTimeoutMillis(5_000); |
| 120 | + return properties; |
| 121 | + } |
| 122 | + |
| 123 | + private static final class WireMessage { |
| 124 | + private final WebSocket socket; |
| 125 | + private final JsonNode body; |
| 126 | + |
| 127 | + private WireMessage(WebSocket socket, JsonNode body) { |
| 128 | + this.socket = socket; |
| 129 | + this.body = body; |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + private static final class LocalCenter extends WebSocketServer implements AutoCloseable { |
| 134 | + private final CountDownLatch started = new CountDownLatch(1); |
| 135 | + private final BlockingQueue<WireMessage> messages = new LinkedBlockingQueue<>(); |
| 136 | + private final AtomicReference<Exception> failure = new AtomicReference<>(); |
| 137 | + |
| 138 | + private LocalCenter() throws Exception { |
| 139 | + super(new InetSocketAddress("127.0.0.1", 0), 1); |
| 140 | + start(); |
| 141 | + if (!started.await(5, TimeUnit.SECONDS) || Objects.nonNull(failure.get())) { |
| 142 | + stop(1_000); |
| 143 | + throw new IllegalStateException("WebSocket test server failed to start", failure.get()); |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + private OpenCliWsAgentConnectionProperties agentProperties() { |
| 148 | + OpenCliWsAgentConnectionProperties properties = new OpenCliWsAgentConnectionProperties(); |
| 149 | + properties.setCentralApiBaseUrl("http://127.0.0.1:" + getPort()); |
| 150 | + properties.setAgentAdvertiseUrl(AGENT_URL); |
| 151 | + properties.setMinReconnectDelayMillis(25); |
| 152 | + properties.setMaxReconnectDelayMillis(50); |
| 153 | + properties.setHandshakeTimeoutMillis(5_000); |
| 154 | + return properties; |
| 155 | + } |
| 156 | + |
| 157 | + private WireMessage receive(String type) throws InterruptedException { |
| 158 | + WireMessage message = messages.poll(8, TimeUnit.SECONDS); |
| 159 | + assertNull(failure.get()); |
| 160 | + assertNotNull(message, "Expected WebSocket " + type + " response"); |
| 161 | + assertEquals(type, message.body.path("type").asText()); |
| 162 | + return message; |
| 163 | + } |
| 164 | + |
| 165 | + @Override |
| 166 | + public void onOpen(WebSocket socket, ClientHandshake handshake) { } |
| 167 | + |
| 168 | + @Override |
| 169 | + public void onClose(WebSocket socket, int code, String reason, boolean remote) { } |
| 170 | + |
| 171 | + @Override |
| 172 | + public void onMessage(WebSocket socket, String payload) { |
| 173 | + try { |
| 174 | + messages.add(new WireMessage(socket, MAPPER.readTree(payload))); |
| 175 | + } catch (IOException e) { |
| 176 | + failure.compareAndSet(null, e); |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + @Override |
| 181 | + public void onError(WebSocket socket, Exception error) { |
| 182 | + failure.compareAndSet(null, error); |
| 183 | + started.countDown(); |
| 184 | + } |
| 185 | + |
| 186 | + @Override |
| 187 | + public void onStart() { |
| 188 | + started.countDown(); |
| 189 | + } |
| 190 | + |
| 191 | + @Override |
| 192 | + public void close() throws InterruptedException { |
| 193 | + stop(1_000); |
| 194 | + } |
| 195 | + } |
| 196 | +} |
0 commit comments