Repository navigation
Expand file tree
/
Copy pathGitHubTelemetryTest.java
More file actions
404 lines (347 loc) · 18.2 KB
/
Copy pathGitHubTelemetryTest.java
File metadata and controls
404 lines (347 loc) · 18.2 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
package com.github.copilot;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.copilot.generated.rpc.GitHubTelemetryNotification;
import com.github.copilot.rpc.ClientInfo;
import com.github.copilot.rpc.CopilotClientOptions;
import com.github.copilot.rpc.PermissionHandler;
import com.github.copilot.rpc.ResumeSessionConfig;
import com.github.copilot.rpc.SessionConfig;
/**
* Exercises the hand-written GitHub telemetry forwarding surface: the
* {@code gitHubTelemetry.event} notification adapter, the
* {@code enableGitHubTelemetryForwarding} capability flag on the connect
* handshake and the create/resume requests, and the {@code onGitHubTelemetry}
* client option.
*/
@AllowCopilotExperimental
class GitHubTelemetryTest {
private record SocketPair(JsonRpcClient client, Socket serverSide,
ServerSocket serverSocket) implements AutoCloseable {
@Override
public void close() throws Exception {
client.close();
serverSide.close();
serverSocket.close();
}
}
private SocketPair createSocketPair() throws Exception {
var loopback = InetAddress.getLoopbackAddress();
var serverSocket = new ServerSocket(0, 1, loopback);
var clientSocket = new Socket(loopback, serverSocket.getLocalPort());
var serverSide = serverSocket.accept();
var client = JsonRpcClient.fromSocket(clientSocket);
return new SocketPair(client, serverSide, serverSocket);
}
private void writeRpcMessage(OutputStream out, String json) throws IOException {
byte[] content = json.getBytes(StandardCharsets.UTF_8);
String header = "Content-Length: " + content.length + "\r\n\r\n";
out.write(header.getBytes(StandardCharsets.UTF_8));
out.write(content);
out.flush();
}
@Test
void adapterDispatchesNotificationToHandlerWithTypedPayload() throws Exception {
try (var pair = createSocketPair()) {
var received = new CompletableFuture<GitHubTelemetryNotification>();
Function<GitHubTelemetryNotification, CompletableFuture<Void>> handler = notification -> {
received.complete(notification);
return CompletableFuture.completedFuture(null);
};
new GitHubTelemetryAdapter(handler).registerHandlers(pair.client());
String notification = """
{
"jsonrpc": "2.0",
"method": "gitHubTelemetry.event",
"params": {
"sessionId": "sess-123",
"restricted": true,
"event": {
"kind": "tool_call_executed",
"created_at": "2024-01-01T00:00:00Z",
"model_call_id": "call-9",
"properties": { "tool": "shell" },
"metrics": { "duration_ms": 42.5 },
"exp_assignment_context": "ctx",
"features": { "flag_a": "on" },
"session_id": "sess-123",
"copilot_tracking_id": "track-1",
"client": {
"cli_version": "1.2.3",
"os_platform": "win32",
"os_version": "10",
"os_arch": "x64",
"node_version": "20.0.0",
"is_staff": false
}
}
}
}
""";
writeRpcMessage(pair.serverSide().getOutputStream(), notification);
GitHubTelemetryNotification result = received.get(5, TimeUnit.SECONDS);
assertEquals("sess-123", result.sessionId());
assertTrue(result.restricted());
var event = result.event();
assertNotNull(event);
assertEquals("tool_call_executed", event.kind());
assertEquals("2024-01-01T00:00:00Z", event.createdAt());
assertEquals("call-9", event.modelCallId());
assertEquals("shell", event.properties().get("tool"));
assertEquals(42.5, event.metrics().get("duration_ms"));
assertEquals("ctx", event.expAssignmentContext());
assertEquals("on", event.features().get("flag_a"));
assertEquals("sess-123", event.sessionId());
assertEquals("track-1", event.copilotTrackingId());
var client = event.client();
assertNotNull(client);
assertEquals("1.2.3", client.cliVersion());
assertEquals("win32", client.osPlatform());
assertEquals("x64", client.osArch());
assertEquals("20.0.0", client.nodeVersion());
assertEquals(Boolean.FALSE, client.isStaff());
}
}
@Test
void clientOptsSessionsIntoForwardingAndReceivesEvents() throws Exception {
var received = new CompletableFuture<GitHubTelemetryNotification>();
Function<GitHubTelemetryNotification, CompletableFuture<Void>> handler = notification -> {
received.complete(notification);
return CompletableFuture.completedFuture(null);
};
try (var server = new FakeRuntimeServer();
var client = new CopilotClient(
new CopilotClientOptions().setCliUrl(server.url()).setOnGitHubTelemetry(handler))) {
client.start().get(15, TimeUnit.SECONDS);
// Connecting must opt into telemetry forwarding at the connection level so
// the runtime can forward the first session's un-replayable start event.
JsonNode connectParams = server.awaitConnect();
assertTrue(connectParams.path("enableGitHubTelemetryForwarding").asBoolean(),
"connect request should carry enableGitHubTelemetryForwarding=true");
// Creating a session must opt it into telemetry forwarding.
client.createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(15,
TimeUnit.SECONDS);
JsonNode createParams = server.awaitCreate();
assertTrue(createParams.path("enableGitHubTelemetryForwarding").asBoolean(),
"create request should carry enableGitHubTelemetryForwarding=true");
// The adapter registered on connect should forward server-pushed events.
server.sendTelemetry(Map.of("sessionId", "sess-xyz", "restricted", false, "event",
Map.of("kind", "session_started", "session_id", "sess-xyz")));
GitHubTelemetryNotification event = received.get(5, TimeUnit.SECONDS);
assertEquals("sess-xyz", event.sessionId());
assertFalse(event.restricted());
assertEquals("session_started", event.event().kind());
// Resuming a session must opt it in as well.
client.resumeSession("resume-1",
new ResumeSessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL))
.get(15, TimeUnit.SECONDS);
JsonNode resumeParams = server.awaitResume();
assertTrue(resumeParams.path("enableGitHubTelemetryForwarding").asBoolean(),
"resume request should carry enableGitHubTelemetryForwarding=true");
}
}
@Test
void clientOmitsForwardingWhenNoHandler() throws Exception {
try (var server = new FakeRuntimeServer();
var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url()))) {
client.start().get(15, TimeUnit.SECONDS);
JsonNode connectParams = server.awaitConnect();
assertFalse(connectParams.has("enableGitHubTelemetryForwarding"),
"connect request should omit the flag when no handler is registered");
assertEquals("[\"agent\",\"client\",\"shell\"]", connectParams.path("supportedTaskKinds").toString());
client.createSession(new SessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL)).get(15,
TimeUnit.SECONDS);
JsonNode createParams = server.awaitCreate();
assertFalse(createParams.has("enableGitHubTelemetryForwarding"),
"create request should omit the flag when no handler is registered");
client.resumeSession("resume-1",
new ResumeSessionConfig().setOnPermissionRequest(PermissionHandler.APPROVE_ALL))
.get(15, TimeUnit.SECONDS);
JsonNode resumeParams = server.awaitResume();
assertFalse(resumeParams.has("enableGitHubTelemetryForwarding"),
"resume request should omit the flag when no handler is registered");
}
}
@Test
void connectForwardsDeclaredClientInfo() throws Exception {
try (var server = new FakeRuntimeServer();
var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url())
.setClientInfo(new ClientInfo().setApplicationName("acme-developer-portal")
.setApplicationVersion("2.4.0").setIntegrationName("copilot-assistant")
.setIntegrationVersion("1.5.0")))) {
client.start().get(15, TimeUnit.SECONDS);
JsonNode connectParams = server.awaitConnect();
JsonNode clientInfo = connectParams.path("clientInfo");
assertEquals(4, clientInfo.size(), "clientInfo should carry only the four declared fields");
assertEquals("acme-developer-portal", clientInfo.path("editorName").asText());
assertEquals("2.4.0", clientInfo.path("editorVersion").asText());
assertEquals("copilot-assistant", clientInfo.path("extensionName").asText());
assertEquals("1.5.0", clientInfo.path("extensionVersion").asText());
}
}
@Test
void connectOmitsClientInfoWhenUnset() throws Exception {
try (var server = new FakeRuntimeServer();
var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url()))) {
client.start().get(15, TimeUnit.SECONDS);
JsonNode connectParams = server.awaitConnect();
assertFalse(connectParams.has("clientInfo"),
"connect request should omit clientInfo when none was declared");
}
}
@Test
void connectOmitsEmptyClientInfoFields() throws Exception {
try (var server = new FakeRuntimeServer();
var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url())
.setClientInfo(new ClientInfo().setApplicationName("example-app")))) {
client.start().get(15, TimeUnit.SECONDS);
JsonNode connectParams = server.awaitConnect();
JsonNode clientInfo = connectParams.path("clientInfo");
assertEquals("example-app", clientInfo.path("editorName").asText());
assertFalse(clientInfo.has("editorVersion"), "unset editorVersion should be omitted");
assertFalse(clientInfo.has("extensionName"), "unset extensionName should be omitted");
assertFalse(clientInfo.has("extensionVersion"), "unset extensionVersion should be omitted");
}
}
@Test
void connectDropsEmptyClientInfoFields() throws Exception {
try (var server = new FakeRuntimeServer();
var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url())
.setClientInfo(new ClientInfo().setApplicationName("example-app").setApplicationVersion("")))) {
client.start().get(15, TimeUnit.SECONDS);
JsonNode connectParams = server.awaitConnect();
JsonNode clientInfo = connectParams.path("clientInfo");
assertEquals(1, clientInfo.size(), "clientInfo should carry only the non-empty field");
assertEquals("example-app", clientInfo.path("editorName").asText());
assertFalse(clientInfo.has("editorVersion"), "empty editorVersion should be dropped");
}
}
@Test
void connectOmitsAllEmptyClientInfo() throws Exception {
try (var server = new FakeRuntimeServer();
var client = new CopilotClient(new CopilotClientOptions().setCliUrl(server.url())
.setClientInfo(new ClientInfo().setApplicationName("").setApplicationVersion("")
.setIntegrationName("").setIntegrationVersion("")))) {
client.start().get(15, TimeUnit.SECONDS);
JsonNode connectParams = server.awaitConnect();
assertFalse(connectParams.has("clientInfo"), "connect request should omit an all-empty clientInfo");
}
}
@Test
void optionsRetainAndCloneClientInfo() {
var info = new ClientInfo().setApplicationName("example-app");
var options = new CopilotClientOptions().setClientInfo(info);
assertSame(info, options.getClientInfo());
var copy = options.clone();
assertSame(info, copy.getClientInfo());
}
@Test
void optionsRetainAndCloneTelemetryHandler() {
Function<GitHubTelemetryNotification, CompletableFuture<Void>> handler = n -> CompletableFuture
.completedFuture(null);
var options = new CopilotClientOptions().setOnGitHubTelemetry(handler);
assertSame(handler, options.getOnGitHubTelemetry());
var copy = options.clone();
assertSame(handler, copy.getOnGitHubTelemetry());
}
/**
* A minimal in-process JSON-RPC runtime that answers the connect/create/resume
* handshake so a real {@link CopilotClient} can be driven over a socket, and
* can push {@code gitHubTelemetry.event} notifications back to the client.
*/
private static final class FakeRuntimeServer implements AutoCloseable {
private final ServerSocket serverSocket;
private final Thread acceptThread;
private final CompletableFuture<JsonRpcClient> ready = new CompletableFuture<>();
private final CompletableFuture<JsonNode> connectParams = new CompletableFuture<>();
private final CompletableFuture<JsonNode> createParams = new CompletableFuture<>();
private final CompletableFuture<JsonNode> resumeParams = new CompletableFuture<>();
FakeRuntimeServer() throws IOException {
serverSocket = new ServerSocket(0);
acceptThread = new Thread(this::acceptLoop, "fake-runtime-accept");
acceptThread.setDaemon(true);
acceptThread.start();
}
String url() {
return "127.0.0.1:" + serverSocket.getLocalPort();
}
JsonNode awaitConnect() throws Exception {
return connectParams.get(15, TimeUnit.SECONDS);
}
JsonNode awaitCreate() throws Exception {
return createParams.get(15, TimeUnit.SECONDS);
}
JsonNode awaitResume() throws Exception {
return resumeParams.get(15, TimeUnit.SECONDS);
}
void sendTelemetry(Object params) throws Exception {
ready.get(15, TimeUnit.SECONDS).notify("gitHubTelemetry.event", params);
}
private void acceptLoop() {
try {
Socket socket = serverSocket.accept();
JsonRpcClient server = JsonRpcClient.fromSocket(socket, rpc -> {
rpc.registerMethodHandler("connect", (id, params) -> {
connectParams.complete(params);
respond(rpc, id, Map.of("protocolVersion", 2));
});
rpc.registerMethodHandler("session.create", (id, params) -> {
createParams.complete(params);
respond(rpc, id, Map.of("sessionId", params.path("sessionId").asText("created"),
"workspacePath", "/workspace"));
});
rpc.registerMethodHandler("session.resume", (id, params) -> {
resumeParams.complete(params);
respond(rpc, id, Map.of("sessionId", params.path("sessionId").asText("resume-1"),
"workspacePath", "/workspace"));
});
rpc.registerMethodHandler("session.detach",
(id, params) -> respond(rpc, id, Map.of("success", true)));
rpc.registerMethodHandler("runtime.shutdown", (id, params) -> respond(rpc, id, Map.of()));
});
ready.complete(server);
} catch (IOException e) {
ready.completeExceptionally(e);
connectParams.completeExceptionally(e);
createParams.completeExceptionally(e);
resumeParams.completeExceptionally(e);
}
}
private static void respond(JsonRpcClient server, String id, Object result) {
if (id == null) {
return;
}
try {
server.sendResponse(id, result);
} catch (IOException e) {
// Connection torn down (e.g. client closing); ignore.
}
}
@Override
public void close() throws Exception {
JsonRpcClient server = ready.getNow(null);
if (server != null) {
server.close();
}
serverSocket.close();
}
}
}