|
| 1 | +/* |
| 2 | + * Copyright 2025 the original author or authors. |
| 3 | + * <p> |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * <p> |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * <p> |
| 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 | +package org.openrewrite.maven.rpc; |
| 17 | + |
| 18 | +import com.fasterxml.jackson.core.JsonGenerator; |
| 19 | +import com.fasterxml.jackson.core.JsonParser; |
| 20 | +import com.fasterxml.jackson.databind.DeserializationContext; |
| 21 | +import com.fasterxml.jackson.databind.JsonDeserializer; |
| 22 | +import com.fasterxml.jackson.databind.JsonSerializer; |
| 23 | +import com.fasterxml.jackson.databind.SerializerProvider; |
| 24 | +import com.fasterxml.jackson.databind.module.SimpleModule; |
| 25 | +import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; |
| 26 | +import io.moderne.jsonrpc.JsonRpc; |
| 27 | +import io.moderne.jsonrpc.formatter.JsonMessageFormatter; |
| 28 | +import io.moderne.jsonrpc.handler.HeaderDelimitedMessageHandler; |
| 29 | +import io.moderne.jsonrpc.handler.MessageHandler; |
| 30 | +import io.moderne.jsonrpc.handler.TraceMessageHandler; |
| 31 | +import org.jspecify.annotations.Nullable; |
| 32 | +import org.openrewrite.HttpSenderExecutionContextView; |
| 33 | +import org.openrewrite.InMemoryExecutionContext; |
| 34 | +import org.openrewrite.ipc.http.HttpUrlConnectionSender; |
| 35 | +import org.openrewrite.marketplace.RecipeBundleResolver; |
| 36 | +import org.openrewrite.marketplace.RecipeClassLoader; |
| 37 | +import org.openrewrite.marketplace.RecipeMarketplace; |
| 38 | +import org.openrewrite.marketplace.RecipeMarketplaceReader; |
| 39 | +import org.openrewrite.maven.MavenExecutionContextView; |
| 40 | +import org.openrewrite.maven.cache.LocalMavenArtifactCache; |
| 41 | +import org.openrewrite.maven.marketplace.MavenRecipeBundleResolver; |
| 42 | +import org.openrewrite.maven.utilities.MavenArtifactDownloader; |
| 43 | +import org.openrewrite.rpc.RewriteRpc; |
| 44 | + |
| 45 | +import java.io.IOException; |
| 46 | +import java.io.PrintStream; |
| 47 | +import java.nio.file.Files; |
| 48 | +import java.nio.file.Path; |
| 49 | +import java.nio.file.Paths; |
| 50 | +import java.nio.file.StandardOpenOption; |
| 51 | +import java.util.ArrayList; |
| 52 | +import java.util.List; |
| 53 | + |
| 54 | +/** |
| 55 | + * A standalone RPC server application that communicates via stdin/stdout. |
| 56 | + * <p> |
| 57 | + * This application is designed to be spawned as a subprocess by Python, JavaScript, |
| 58 | + * or any other language that needs to use Java-based OpenRewrite recipes. |
| 59 | + * <p> |
| 60 | + * Usage: |
| 61 | + * <pre> |
| 62 | + * java -cp <classpath> org.openrewrite.maven.rpc.JavaRewriteRpc [options] |
| 63 | + * </pre> |
| 64 | + * <p> |
| 65 | + * Options: |
| 66 | + * <ul> |
| 67 | + * <li>--marketplace=<path> - Path to marketplace CSV file (required)</li> |
| 68 | + * <li>--log-file=<path> - Log file for debugging</li> |
| 69 | + * <li>--trace - Enable RPC message tracing</li> |
| 70 | + * </ul> |
| 71 | + * <p> |
| 72 | + * The marketplace CSV must contain columns for recipe metadata and bundle information. |
| 73 | + * Required columns: name, ecosystem, packageName, version |
| 74 | + * <p> |
| 75 | + * Example marketplace.csv: |
| 76 | + * <pre> |
| 77 | + * name,displayName,ecosystem,packageName,version |
| 78 | + * org.openrewrite.java.ChangeType,Change type,maven,org.openrewrite:rewrite-java,8.73.0 |
| 79 | + * </pre> |
| 80 | + */ |
| 81 | +public class JavaRewriteRpc { |
| 82 | + |
| 83 | + public static void main(String[] args) { |
| 84 | + @Nullable Path marketplaceCsv = null; |
| 85 | + @Nullable Path logFile = null; |
| 86 | + boolean trace = false; |
| 87 | + |
| 88 | + // Parse command line arguments |
| 89 | + for (String arg : args) { |
| 90 | + if (arg.startsWith("--marketplace=")) { |
| 91 | + marketplaceCsv = Paths.get(arg.substring("--marketplace=".length())); |
| 92 | + } else if (arg.startsWith("--log-file=")) { |
| 93 | + logFile = Paths.get(arg.substring("--log-file=".length())); |
| 94 | + } else if (arg.equals("--trace")) { |
| 95 | + trace = true; |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + if (marketplaceCsv == null) { |
| 100 | + System.err.println("Error: --marketplace=<path> is required"); |
| 101 | + System.err.println("Usage: java org.openrewrite.maven.rpc.JavaRewriteRpc --marketplace=<csv> [--log-file=<path>] [--trace]"); |
| 102 | + System.exit(1); |
| 103 | + } |
| 104 | + |
| 105 | + if (!Files.exists(marketplaceCsv)) { |
| 106 | + System.err.println("Error: Marketplace CSV file not found: " + marketplaceCsv); |
| 107 | + System.exit(1); |
| 108 | + } |
| 109 | + |
| 110 | + // Redirect stderr to log file if specified (to avoid interfering with RPC on stdout) |
| 111 | + PrintStream logStream = null; |
| 112 | + if (logFile != null) { |
| 113 | + try { |
| 114 | + logStream = new PrintStream(Files.newOutputStream(logFile, |
| 115 | + StandardOpenOption.CREATE, StandardOpenOption.APPEND)); |
| 116 | + System.setErr(logStream); |
| 117 | + } catch (IOException e) { |
| 118 | + System.err.println("Failed to open log file: " + e.getMessage()); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + try { |
| 123 | + run(marketplaceCsv, trace, logStream); |
| 124 | + } catch (Exception e) { |
| 125 | + System.err.println("RPC server error: " + e.getMessage()); |
| 126 | + e.printStackTrace(System.err); |
| 127 | + System.exit(1); |
| 128 | + } finally { |
| 129 | + if (logStream != null) { |
| 130 | + logStream.close(); |
| 131 | + } |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + private static void run(Path marketplaceCsv, boolean trace, @Nullable PrintStream logStream) { |
| 136 | + // Load the recipe marketplace from CSV |
| 137 | + RecipeMarketplaceReader reader = new RecipeMarketplaceReader(); |
| 138 | + RecipeMarketplace marketplace = reader.fromCsv(marketplaceCsv); |
| 139 | + |
| 140 | + if (logStream != null) { |
| 141 | + logStream.println("Loaded marketplace with " + marketplace.getAllRecipes().size() + " recipes from " + marketplaceCsv); |
| 142 | + logStream.flush(); |
| 143 | + } |
| 144 | + |
| 145 | + // Set up execution context |
| 146 | + PrintStream errorHandler = logStream != null ? logStream : System.err; |
| 147 | + InMemoryExecutionContext ctx = new InMemoryExecutionContext(t -> { |
| 148 | + errorHandler.println("Error: " + t.getMessage()); |
| 149 | + t.printStackTrace(errorHandler); |
| 150 | + }); |
| 151 | + |
| 152 | + // Configure HTTP and Maven settings |
| 153 | + HttpSenderExecutionContextView.view(ctx).setHttpSender(new HttpUrlConnectionSender()); |
| 154 | + MavenExecutionContextView mavenCtx = MavenExecutionContextView.view(ctx); |
| 155 | + mavenCtx.setAddCentralRepository(true); |
| 156 | + |
| 157 | + // Create artifact cache in user's .rewrite directory |
| 158 | + Path cacheDir; |
| 159 | + try { |
| 160 | + cacheDir = Paths.get(System.getProperty("user.home"), ".rewrite", "cache", "artifacts"); |
| 161 | + Files.createDirectories(cacheDir); |
| 162 | + } catch (IOException e) { |
| 163 | + throw new RuntimeException("Failed to create Maven artifact cache directory", e); |
| 164 | + } |
| 165 | + LocalMavenArtifactCache artifactCache = new LocalMavenArtifactCache(cacheDir); |
| 166 | + |
| 167 | + MavenArtifactDownloader downloader = new MavenArtifactDownloader( |
| 168 | + artifactCache, |
| 169 | + null, // No custom Maven settings |
| 170 | + new HttpUrlConnectionSender(), |
| 171 | + t -> errorHandler.println("Download error: " + t.getMessage()) |
| 172 | + ); |
| 173 | + |
| 174 | + // Set up resolvers |
| 175 | + List<RecipeBundleResolver> resolvers = new ArrayList<>(); |
| 176 | + resolvers.add(new MavenRecipeBundleResolver(ctx, downloader, RecipeClassLoader::new)); |
| 177 | + |
| 178 | + if (logStream != null) { |
| 179 | + logStream.println("Configured Maven recipe bundle resolver"); |
| 180 | + logStream.flush(); |
| 181 | + } |
| 182 | + |
| 183 | + // Set up JSON-RPC communication on stdin/stdout |
| 184 | + SimpleModule module = new SimpleModule(); |
| 185 | + module.addSerializer(Path.class, new PathSerializer()); |
| 186 | + module.addDeserializer(Path.class, new PathDeserializer()); |
| 187 | + |
| 188 | + JsonMessageFormatter formatter = new JsonMessageFormatter(module, new ParameterNamesModule()); |
| 189 | + MessageHandler handler = new HeaderDelimitedMessageHandler(formatter, System.in, System.out); |
| 190 | + |
| 191 | + if (trace) { |
| 192 | + handler = new TraceMessageHandler("server", handler); |
| 193 | + } |
| 194 | + |
| 195 | + JsonRpc jsonRpc = new JsonRpc(handler); |
| 196 | + |
| 197 | + // Create the RPC server with the marketplace and resolvers |
| 198 | + RewriteRpc server = new RewriteRpc(jsonRpc, marketplace, resolvers); |
| 199 | + |
| 200 | + if (logStream != null) { |
| 201 | + server.log(logStream); |
| 202 | + logStream.println("RPC server started"); |
| 203 | + logStream.flush(); |
| 204 | + } |
| 205 | + |
| 206 | + // The JsonRpc.bind() call in RewriteRpc constructor starts the message handler |
| 207 | + // that reads from stdin in a background thread. |
| 208 | + |
| 209 | + // Keep the main thread alive while the RPC handler processes messages. |
| 210 | + // Use Object.wait() to block indefinitely - the process will be terminated |
| 211 | + // externally when the parent process closes stdin or kills this process. |
| 212 | + Object lock = new Object(); |
| 213 | + synchronized (lock) { |
| 214 | + try { |
| 215 | + // Wait indefinitely - this keeps the JVM alive |
| 216 | + lock.wait(); |
| 217 | + } catch (InterruptedException e) { |
| 218 | + Thread.currentThread().interrupt(); |
| 219 | + if (logStream != null) { |
| 220 | + logStream.println("Server interrupted"); |
| 221 | + logStream.flush(); |
| 222 | + } |
| 223 | + } |
| 224 | + } |
| 225 | + |
| 226 | + server.shutdown(); |
| 227 | + } |
| 228 | + |
| 229 | + private static class PathSerializer extends JsonSerializer<Path> { |
| 230 | + @Override |
| 231 | + public void serialize(Path path, JsonGenerator g, SerializerProvider serializerProvider) throws IOException { |
| 232 | + g.writeString(path.toString()); |
| 233 | + } |
| 234 | + } |
| 235 | + |
| 236 | + private static class PathDeserializer extends JsonDeserializer<Path> { |
| 237 | + @Override |
| 238 | + public Path deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { |
| 239 | + String pathString = p.getValueAsString(); |
| 240 | + return Paths.get(pathString); |
| 241 | + } |
| 242 | + } |
| 243 | +} |
0 commit comments