package p.studio.app.runtime; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import p.studio.api.project.ProjectLocalStudioSetup; import p.studio.api.project.ProjectReference; import p.studio.api.runtime.RuntimeLogEntry; import p.studio.core.runtime.RuntimeConnection; import p.studio.core.runtime.RuntimeGateway; import java.io.*; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.function.Consumer; public final class ExternalRuntimeGateway implements RuntimeGateway { private static final int DEBUG_PORT = 7777; private final ObjectMapper mapper; private final Executor executor; public ExternalRuntimeGateway(ObjectMapper mapper, Executor executor) { this.mapper = Objects.requireNonNull(mapper, "mapper"); this.executor = Objects.requireNonNull(executor, "executor"); } @Override public RuntimeConnection start(ProjectReference project, ProjectLocalStudioSetup setup, Consumer logs) throws Exception { final Consumer sink = Objects.requireNonNull(logs, "logs"); final Path executable = resolveExecutable(setup); final Process process = new ProcessBuilder(executable.toString(), "debug", "build") .directory(project.rootPath().toFile()).start(); stream(process.getInputStream(), false, sink); stream(process.getErrorStream(), true, sink); try { final Socket socket = connectWithRetry(); final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8)); final JsonNode handshake = mapper.readTree(requireLine(reader, "connection closed during handshake")); if (handshake == null || !"handshake".equals(handshake.path("type").asText())) { throw new IOException("invalid runtime handshake"); } writer.write("{\"type\":\"start\"}"); writer.newLine(); writer.flush(); sink.accept(RuntimeLogEntry.info("Runtime protocol %d (%s)".formatted( handshake.path("protocol_version").asInt(), handshake.path("runtime_version").asText("unknown")))); final var connection = new ProcessRuntimeConnection(process, socket, reader, writer); executor.execute(() -> receive(reader, sink, connection)); return connection; } catch (Exception failure) { process.descendants().forEach(ProcessHandle::destroyForcibly); process.destroyForcibly(); throw failure; } } private static Path resolveExecutable(ProjectLocalStudioSetup setup) throws IOException { if (setup.prometeuRuntimePath() == null) throw new IOException("prometeuRuntimePath is missing"); final Path executable = Path.of(setup.prometeuRuntimePath()).resolve("prometeu").toAbsolutePath().normalize(); if (!Files.isRegularFile(executable)) throw new IOException("runtime not found at " + executable); if (!Files.isExecutable(executable)) throw new IOException("runtime is not executable at " + executable); return executable; } private Socket connectWithRetry() throws IOException { IOException failure = null; for (int attempt = 0; attempt < 20; attempt++) { final Socket socket = new Socket(); try { socket.connect(new InetSocketAddress("127.0.0.1", DEBUG_PORT), 500); socket.setSoTimeout(5_000); return socket; } catch (IOException exception) { failure = exception; closeQuietly(socket); try { Thread.sleep(100L); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException("runtime connection interrupted", interrupted); } } } throw failure == null ? new IOException("runtime connection failed") : failure; } private void stream(InputStream stream, boolean error, Consumer sink) { executor.execute(() -> { try (var reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) sink.accept(error ? RuntimeLogEntry.error(line) : RuntimeLogEntry.info(line)); } catch (IOException ignored) { } }); } private void receive(BufferedReader reader, Consumer sink, ProcessRuntimeConnection connection) { try { String line; while ((line = reader.readLine()) != null) { final JsonNode event = mapper.readTree(line); if (event != null && "log".equals(event.path("event").asText())) { final String source = event.path("source").asText(""); final String message = event.path("msg").asText(""); final String rendered = source.isBlank() ? message : "[" + source + "] " + message; final boolean error = switch (event.path("level").asText("").toUpperCase()) { case "ERROR", "FATAL" -> true; default -> false; }; sink.accept(error ? RuntimeLogEntry.error(rendered) : RuntimeLogEntry.info(rendered)); } } } catch (IOException failure) { if (!connection.closed) sink.accept(RuntimeLogEntry.error("Runtime debug connection lost: " + failure.getMessage())); } } private static String requireLine(BufferedReader reader, String message) throws IOException { final String line = reader.readLine(); if (line == null) throw new IOException(message); return line; } private static void closeQuietly(Closeable closeable) { if (closeable == null) return; try { closeable.close(); } catch (IOException ignored) { } } private static final class ProcessRuntimeConnection implements RuntimeConnection { private final Process process; private final Socket socket; private final Reader reader; private final Writer writer; private volatile boolean closed; private ProcessRuntimeConnection(Process process, Socket socket, Reader reader, Writer writer) { this.process = process; this.socket = socket; this.reader = reader; this.writer = writer; } @Override public CompletableFuture completion() { return process.onExit().thenApply(Process::exitValue); } @Override public void close() { if (closed) return; closed = true; closeQuietly(reader); closeQuietly(writer); closeQuietly(socket); process.descendants().forEach(ProcessHandle::destroyForcibly); process.destroyForcibly(); } } }