JSON-RPC 2.0 client implementation for communicating with the Copilot CLI. @since 1.0.0
| 38 | * @since 1.0.0 |
| 39 | */ |
| 40 | class JsonRpcClient implements AutoCloseable { |
| 41 | |
| 42 | private static final Logger LOG = Logger.getLogger(JsonRpcClient.class.getName()); |
| 43 | private static final ObjectMapper MAPPER = createObjectMapper(); |
| 44 | |
| 45 | private final InputStream inputStream; |
| 46 | private final OutputStream outputStream; |
| 47 | private final Socket socket; |
| 48 | private final Process process; |
| 49 | private final AtomicLong requestIdCounter = new AtomicLong(0); |
| 50 | private final Map<Long, CompletableFuture<JsonNode>> pendingRequests = new ConcurrentHashMap<>(); |
| 51 | private final Map<String, BiConsumer<String, JsonNode>> notificationHandlers = new ConcurrentHashMap<>(); |
| 52 | private final ExecutorService readerExecutor; |
| 53 | private volatile boolean running = true; |
| 54 | |
| 55 | private JsonRpcClient(InputStream inputStream, OutputStream outputStream, Socket socket, Process process) { |
| 56 | this.inputStream = inputStream; |
| 57 | this.outputStream = outputStream; |
| 58 | this.socket = socket; |
| 59 | this.process = process; |
| 60 | this.readerExecutor = Executors.newSingleThreadExecutor(r -> { |
| 61 | Thread t = new Thread(r, "jsonrpc-reader"); |
| 62 | t.setDaemon(true); |
| 63 | return t; |
| 64 | }); |
| 65 | startReader(); |
| 66 | } |
| 67 | |
| 68 | static ObjectMapper createObjectMapper() { |
| 69 | var mapper = new ObjectMapper(); |
| 70 | mapper.registerModule(new JavaTimeModule()); |
| 71 | mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); |
| 72 | mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); |
| 73 | mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL); |
| 74 | return mapper; |
| 75 | } |
| 76 | |
| 77 | public static ObjectMapper getObjectMapper() { |
| 78 | return MAPPER; |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * Creates a JSON-RPC client using stdio with a process. |
| 83 | */ |
| 84 | public static JsonRpcClient fromProcess(Process process) { |
| 85 | return new JsonRpcClient(process.getInputStream(), process.getOutputStream(), null, process); |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Creates a JSON-RPC client using TCP socket. |
| 90 | */ |
| 91 | public static JsonRpcClient fromSocket(Socket socket) throws IOException { |
| 92 | return new JsonRpcClient(socket.getInputStream(), socket.getOutputStream(), socket, null); |
| 93 | } |
| 94 | |
| 95 | /** |
| 96 | * Registers a handler for JSON-RPC method calls (requests/notifications from |
| 97 | * server). |
no test coverage detected
searching dependent graphs…