Repository navigation
Expand file tree
/
Copy pathTraceClientTest.java
More file actions
2505 lines (2200 loc) · 119 KB
/
Copy pathTraceClientTest.java
File metadata and controls
2505 lines (2200 loc) · 119 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package software.stephenson.trace;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Drives the client against a real HTTP server on a loopback port -- the
* JDK's own, so the test has no more dependencies than the client does.
*/
class TraceClientTest {
private static final String UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
private HttpServer server;
private final List<Received> received = new CopyOnWriteArrayList<>();
private volatile int replyStatus = 201;
private volatile CountDownLatch arrived = new CountDownLatch(1);
// What the client sees as its environment. Empty unless a test says
// otherwise, so a DO_NOT_TRACK on the machine running the suite cannot
// fail the tests that expect an enabled client.
private final Map<String, String> environment = new HashMap<>();
private Function<String, String> realEnvironment;
private static final class Received {
final String method;
final String path;
final String authorization;
final String contentType;
final String userAgent;
final String body;
Received(String method, String path, String authorization, String contentType, String userAgent, String body) {
this.method = method;
this.path = path;
this.authorization = authorization;
this.contentType = contentType;
this.userAgent = userAgent;
this.body = body;
}
}
@BeforeEach
void isolateEnvironment() {
realEnvironment = TraceClient.environment;
TraceClient.environment = environment::get;
}
@AfterEach
void restoreEnvironment() {
TraceClient.environment = realEnvironment;
}
@BeforeEach
void startServer() throws Exception {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/", exchange -> {
byte[] body = readAll(exchange.getRequestBody());
received.add(new Received(
exchange.getRequestMethod(),
exchange.getRequestURI().getPath(),
exchange.getRequestHeaders().getFirst("Authorization"),
exchange.getRequestHeaders().getFirst("Content-Type"),
exchange.getRequestHeaders().getFirst("User-Agent"),
new String(body, StandardCharsets.UTF_8)));
exchange.sendResponseHeaders(replyStatus, -1);
exchange.close();
arrived.countDown();
});
server.start();
}
@AfterEach
void stopServer() {
server.stop(0);
}
private String baseUrl() {
return "http://127.0.0.1:" + server.getAddress().getPort();
}
@Test
void report_postsTheEventToTheMetricsEndpointWithTheKey() throws Exception {
// Arrange
TraceClient client = TraceClient.builder(baseUrl() + "/", "MyPlugin", "1.2.3").key("k-123").build();
// Act
client.report("startup");
// Assert
assertTrue(arrived.await(5, TimeUnit.SECONDS), "the report should reach the server");
Received request = received.get(0);
assertEquals("POST", request.method);
assertEquals("/api/metrics", request.path, "a trailing slash on the base URL must not double up");
assertEquals("Bearer k-123", request.authorization);
assertTrue(request.contentType.startsWith("application/json"), request.contentType);
assertEquals("{\"application\":\"MyPlugin\",\"name\":\"startup\",\"tags\":{\"version\":\"1.2.3\"}}", request.body);
client.close();
}
@Test
void report_carriesValueAndTagsWhenGiven() throws Exception {
// Arrange
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build();
Map<String, String> tags = new LinkedHashMap<>();
tags.put("command", "home");
tags.put("world", "the \"end\"");
// Act
client.report("command", 2.5, tags);
// Assert
assertTrue(arrived.await(5, TimeUnit.SECONDS));
assertEquals(
"{\"application\":\"MyPlugin\",\"name\":\"command\",\"value\":2.5,"
+ "\"tags\":{\"command\":\"home\",\"world\":\"the \\\"end\\\"\",\"version\":\"1.2.3\"}}",
received.get(0).body);
client.close();
}
@Test
void report_returnsBeforeTheServerAnswers() throws Exception {
// Arrange
// A server that never replies. If report() waited on the network the
// caller -- a game server's main thread, in the case that matters --
// would wait with it.
CountDownLatch release = new CountDownLatch(1);
HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
slow.createContext("/", exchange -> {
try {
release.await(10, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
exchange.sendResponseHeaders(201, -1);
exchange.close();
});
slow.start();
TraceClient client = TraceClient.builder("http://127.0.0.1:" + slow.getAddress().getPort(), "MyPlugin", "1.2.3")
.key("k").build();
// Act
long before = System.nanoTime();
client.report("startup");
long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - before);
// Assert
assertTrue(elapsedMs < 1_000, "report() took " + elapsedMs + " ms; it must not wait on the network");
release.countDown();
client.close();
slow.stop(0);
}
@Test
void report_doesNotThrowWhenNothingIsListening() throws Exception {
// Arrange
// Pick a port by binding and releasing it, so nothing answers there.
HttpServer probe = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
int deadPort = probe.getAddress().getPort();
probe.stop(0);
RecordingHandler log = new RecordingHandler();
Logger logger = Logger.getLogger("TraceClientTest.dead");
logger.setLevel(Level.ALL);
logger.addHandler(log);
TraceClient client = TraceClient.builder("http://127.0.0.1:" + deadPort, "MyPlugin", "1.2.3")
.key("k").logger(logger).build();
// Act
assertDoesNotThrow(() -> client.report("startup"));
client.close(); // waits for the in-flight attempt to fail
// Assert
assertTrue(log.await(5, TimeUnit.SECONDS), "the failure should be mentioned at FINE");
assertEquals(Level.FINE, log.records.get(0).getLevel());
assertTrue(log.records.get(0).getMessage().contains("could not deliver"), log.records.get(0).getMessage());
}
@Test
void report_doesNotThrowWhenTheServerRejectsTheKey() throws Exception {
// Arrange
replyStatus = 401;
RecordingHandler log = new RecordingHandler();
Logger logger = Logger.getLogger("TraceClientTest.rejected");
logger.setLevel(Level.ALL);
logger.addHandler(log);
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("revoked").logger(logger).build();
// Act
assertDoesNotThrow(() -> client.report("startup"));
// Assert
assertTrue(log.await(5, TimeUnit.SECONDS));
assertTrue(log.records.get(0).getMessage().contains("answered 401"), log.records.get(0).getMessage());
client.close();
}
@Test
void report_aTagsMapChangedMidReadIsDroppedWithoutThrowing() throws Exception {
// Arrange
// What a HashMap does when another thread changes it during the
// copy, without needing to win that race.
Map<String, String> beingChanged = new AbstractMap<String, String>() {
@Override
public Set<Map.Entry<String, String>> entrySet() {
throw new ConcurrentModificationException();
}
};
RecordingHandler log = new RecordingHandler();
Logger logger = Logger.getLogger("TraceClientTest.unreadableTags");
logger.setLevel(Level.ALL);
logger.addHandler(log);
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").logger(logger).build();
// Act
assertDoesNotThrow(() -> client.report("command", 1.0, beingChanged));
client.report("after", null, null);
// Assert
assertTrue(arrived.await(5, TimeUnit.SECONDS), "the client should keep working");
assertEquals(1, client.coalescing(), "only the good report opened a window");
client.close();
assertEquals(1, received.size(), "the unreadable report is dropped");
assertTrue(received.get(0).body.contains("\"name\":\"after\""), received.get(0).body);
assertTrue(log.records.isEmpty(), "nothing is logged on the caller's thread: " + log.records);
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void report_aNonStringTagSmuggledInByARawMapIsDroppedWithoutThrowing() throws Exception {
// Arrange
// A Bukkit getValues(false) is a Map<String, Object>; one unchecked
// cast puts an Integer where json() needs a String.
Map raw = new HashMap();
raw.put("count", 5);
Map<String, String> tags = raw;
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build();
// Act
assertDoesNotThrow(() -> client.report("command", null, tags));
client.report("after", null, null);
// Assert
assertTrue(arrived.await(5, TimeUnit.SECONDS), "the client should keep working");
client.close();
assertEquals(1, received.size(), "the unreadable report is dropped");
assertTrue(received.get(0).body.contains("\"name\":\"after\""), received.get(0).body);
}
@Test
void disabledClient_sendsNothing() throws Exception {
// Arrange
TraceClient byFlag = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").enabled(false).build();
TraceClient byMissingKey = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").build();
TraceClient byBlankKey = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key(" ").build();
TraceClient explicit = TraceClient.disabled();
// Act
for (TraceClient client : new TraceClient[] {byFlag, byMissingKey, byBlankKey, explicit}) {
assertFalse(client.isEnabled());
client.report("startup");
client.close();
}
// Assert
assertFalse(arrived.await(300, TimeUnit.MILLISECONDS), "nothing should have been sent");
assertTrue(received.isEmpty());
}
@Test
void report_ignoresABlankName() throws Exception {
// Arrange
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build();
// Act
client.report(null);
client.report(" ");
client.close();
// Assert
assertFalse(arrived.await(300, TimeUnit.MILLISECONDS));
assertTrue(received.isEmpty());
}
@Test
void builder_rejectsAMissingBaseUrlOrApplication() {
assertThrows(IllegalArgumentException.class, () -> TraceClient.builder(null, "MyPlugin", "1.2.3"));
assertThrows(IllegalArgumentException.class, () -> TraceClient.builder(" ", "MyPlugin", "1.2.3"));
assertThrows(IllegalArgumentException.class, () -> TraceClient.builder("http://x", null, "1.2.3"));
assertThrows(IllegalArgumentException.class, () -> TraceClient.builder("http://x", "", "1.2.3"));
}
@Test
void builder_rejectsAMissingOrOverlongVersion() {
assertThrows(IllegalArgumentException.class, () -> TraceClient.builder("http://x", "MyPlugin", null));
assertThrows(IllegalArgumentException.class, () -> TraceClient.builder("http://x", "MyPlugin", " "));
StringBuilder overlong = new StringBuilder();
for (int i = 0; i <= TraceClient.MAX_TAG_LENGTH; i++) {
overlong.append('9');
}
assertThrows(IllegalArgumentException.class, () -> TraceClient.builder("http://x", "MyPlugin", overlong.toString()));
}
@Test
void builder_namesWhatIsMissingInItsMessage() {
// Act
IllegalArgumentException noBaseUrl = assertThrows(IllegalArgumentException.class,
() -> TraceClient.builder(" ", "MyPlugin", "1.2.3"));
IllegalArgumentException noApplication = assertThrows(IllegalArgumentException.class,
() -> TraceClient.builder("http://x", null, "1.2.3"));
IllegalArgumentException noVersion = assertThrows(IllegalArgumentException.class,
() -> TraceClient.builder("http://x", "MyPlugin", ""));
IllegalArgumentException allMissing = assertThrows(IllegalArgumentException.class,
() -> TraceClient.builder(null, null, null));
// Assert
assertEquals("baseUrl is required", noBaseUrl.getMessage());
assertEquals("application is required", noApplication.getMessage());
assertEquals("version is required", noVersion.getMessage());
assertEquals("baseUrl is required", allMissing.getMessage(), "checked in argument order");
}
@Test
void builder_rejectsAnOverlongVersionAndAcceptsOneAtTheLimit() throws Exception {
// Arrange
StringBuilder max = new StringBuilder();
for (int i = 0; i < TraceClient.MAX_TAG_LENGTH; i++) {
max.append('9');
}
// Act
IllegalArgumentException tooLong = assertThrows(IllegalArgumentException.class,
() -> TraceClient.builder(baseUrl(), "MyPlugin", max + "9"));
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", " " + max + " ").key("k").build();
client.report("startup");
// Assert
assertEquals("version is longer than " + TraceClient.MAX_TAG_LENGTH + " characters", tooLong.getMessage());
assertTrue(arrived.await(5, TimeUnit.SECONDS), "a version at the limit is accepted");
assertTrue(received.get(0).body.contains("\"version\":\"" + max + "\""),
"surrounding whitespace does not count and is not sent: " + received.get(0).body);
client.close();
}
@Test
void report_tagsACommandWithTheProgramVersionTrimmed() throws Exception {
// Arrange
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", " 2.0.0-SNAPSHOT ").key("k").build();
// Act
client.report("command", null, Collections.singletonMap("name", "home"));
// Assert
assertTrue(arrived.await(5, TimeUnit.SECONDS));
assertEquals("{\"application\":\"MyPlugin\",\"name\":\"command\","
+ "\"tags\":{\"name\":\"home\",\"version\":\"2.0.0-SNAPSHOT\"}}", received.get(0).body);
client.close();
}
@Test
void report_anEventsOwnVersionTagWinsOverTheProgramVersion() throws Exception {
// Arrange
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build();
Map<String, String> tags = new LinkedHashMap<>();
tags.put("version", "9.9.9");
// Act
client.report("startup", null, tags);
// Assert
assertTrue(arrived.await(5, TimeUnit.SECONDS));
assertEquals("{\"application\":\"MyPlugin\",\"name\":\"startup\",\"tags\":{\"version\":\"9.9.9\"}}",
received.get(0).body);
assertEquals(Collections.singletonMap("version", "9.9.9"), tags, "the caller's map is not modified");
client.close();
}
@Test
void withVersion_neverModifiesTheCallersMap() {
Map<String, String> tags = new LinkedHashMap<>();
tags.put("name", "home");
Map<String, String> merged = TraceClient.withVersion(tags, "1.2.3");
assertEquals(Collections.singletonMap("name", "home"), tags);
assertEquals("1.2.3", merged.get("version"));
assertEquals("1.2.3", TraceClient.withVersion(null, "1.2.3").get("version"));
}
@Test
void withVersion_dropsNullKeysAndValuesAndKeepsTheEventsOwnVersion() {
// Arrange
Map<String, String> tags = new LinkedHashMap<>();
tags.put("name", "home");
tags.put("nullValue", null);
tags.put(null, "nullKey");
tags.put("version", "own");
// Act
Map<String, String> merged = TraceClient.withVersion(tags, "1.2.3");
// Assert
Map<String, String> expected = new LinkedHashMap<>();
expected.put("name", "home");
expected.put("version", "own");
assertEquals(expected, merged);
assertEquals(4, tags.size(), "the caller's map is not modified");
}
@Test
void withVersion_addsTheVersionEvenToAnEventAlreadyAtMaxTags() {
// Characterizes current behaviour, which issue #13 questions: unlike
// install and the server-wide tags, version is not held to MAX_TAGS,
// so an event with MAX_TAGS tags of its own goes out with one more.
// Arrange
Map<String, String> tags = new LinkedHashMap<>();
for (int i = 0; i < TraceClient.MAX_TAGS; i++) {
tags.put("e" + i, "v");
}
// Act
Map<String, String> merged = TraceClient.withVersion(tags, "1.2.3");
// Assert
assertEquals(TraceClient.MAX_TAGS + 1, merged.size());
assertEquals("1.2.3", merged.get("version"));
}
@Test
void withInstall_addsTheIdOnlyWhenThereIsOneAndRoomAndNoneAlready() {
// Arrange
Map<String, String> tags = new LinkedHashMap<>();
tags.put("version", "1.2.3");
Map<String, String> own = Collections.singletonMap("install", "the-events-own");
Map<String, String> full = new LinkedHashMap<>();
for (int i = 0; i < TraceClient.MAX_TAGS; i++) {
full.put("e" + i, "v");
}
// Act
Map<String, String> added = TraceClient.withInstall(tags, "abc");
// Assert
Map<String, String> expected = new LinkedHashMap<>();
expected.put("version", "1.2.3");
expected.put("install", "abc");
assertEquals(expected, added);
assertEquals(Collections.singletonMap("version", "1.2.3"), tags, "the caller's map is not modified");
assertSame(tags, TraceClient.withInstall(tags, null), "no ID, nothing added");
assertSame(own, TraceClient.withInstall(own, "abc"), "the event's own install tag wins");
assertSame(full, TraceClient.withInstall(full, "abc"), "never pushed past MAX_TAGS");
}
@Test
void serverWideConfig_theFirstEnabledLineIsTheSwitch() {
assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: true", "enabled: false")).disables);
assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: false", "enabled: true")).disables);
assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("# enabled: true", "enabled: false")).disables,
"a commented-out line is not the first one");
}
@Test
void serverWideConfig_aValuelessEnabledLineIsSkippedButACommentOnlyOneIsTheSwitch() {
// Characterizes current behaviour, which issue #27 questions:
// ENABLED_LINE needs a non-blank value, so a bare "enabled:" is
// passed over and a later line is the switch; but after
// "enabled: # ..." the captured value is "#", which is not off, so
// that line is the switch and a later one is ignored.
assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled:", "enabled: false")).disables);
assertTrue(TraceClient.parseServerWideConfig(Arrays.asList("enabled: ", "enabled: false")).disables);
assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled: # set below", "enabled: false")).disables);
assertFalse(TraceClient.parseServerWideConfig(Arrays.asList("enabled:")).disables, "a bare enabled: alone is enabled");
}
@Test
void json_escapesControlCharactersAndSkipsNullTags() {
Map<String, String> tags = new LinkedHashMap<>();
tags.put("ok", "line\nbreak\ttab\\slash");
tags.put("nullValue", null);
tags.put(null, "nullKey");
String json = TraceClient.json("App", "n", Double.NaN, tags);
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"tags\":{\"ok\":\"line\\nbreak\\ttab\\\\slash\"}}", json,
"NaN is not JSON and is dropped; null keys or values are skipped");
assertEquals("\"\\u0001\"", TraceClient.quote("\u0001"));
}
@Test
void json_dropsInfiniteValuesAndKeepsFiniteOnes() {
// Arrange + Act
String positive = TraceClient.json("App", "n", Double.POSITIVE_INFINITY, null);
String negative = TraceClient.json("App", "n", Double.NEGATIVE_INFINITY, null);
String finite = TraceClient.json("App", "n", -0.5, null);
// Assert
assertEquals("{\"application\":\"App\",\"name\":\"n\"}", positive, "Infinity is not JSON and is dropped");
assertEquals("{\"application\":\"App\",\"name\":\"n\"}", negative, "-Infinity is not JSON and is dropped");
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":-0.5}", finite);
}
@Test
void json_writesValuesAsDoubleToStringDoesWhichIsStillValidJson() {
// A value goes out as Double.toString: always with a fraction, and in
// exponent form below 1e-3 and from 1e7 up. JSON allows "1.0E20" and
// "1.0E-5" (an upper-case E and a signed exponent), so the server
// must parse both forms.
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.0}", TraceClient.json("App", "n", 1.0, null));
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1234567.0}", TraceClient.json("App", "n", 1234567.0, null));
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.0E7}", TraceClient.json("App", "n", 1e7, null));
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.0E20}", TraceClient.json("App", "n", 1e20, null));
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":0.001}", TraceClient.json("App", "n", 0.001, null));
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.0E-5}", TraceClient.json("App", "n", 1e-5, null));
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":-0.0}", TraceClient.json("App", "n", -0.0, null));
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"value\":1.7976931348623157E308}",
TraceClient.json("App", "n", Double.MAX_VALUE, null));
}
@Test
void json_omitsTagsWhenNullOrEmpty() {
// Arrange + Act
String nullTags = TraceClient.json("App", "n", null, null);
String emptyTags = TraceClient.json("App", "n", null, Collections.<String, String>emptyMap());
// Assert
assertEquals("{\"application\":\"App\",\"name\":\"n\"}", nullTags);
assertEquals("{\"application\":\"App\",\"name\":\"n\"}", emptyTags);
}
@Test
void json_writesAnEmptyTagsObjectWhenEveryTagIsSkipped() {
// Characterizes current behaviour: a map that is non-empty but holds
// only null keys or values still produces a "tags" key, with nothing
// in it. Valid JSON either way.
// Arrange
Map<String, String> tags = new LinkedHashMap<>();
tags.put("nullValue", null);
tags.put(null, "nullKey");
// Act
String json = TraceClient.json("App", "n", null, tags);
// Assert
assertEquals("{\"application\":\"App\",\"name\":\"n\",\"tags\":{}}", json);
}
@Test
void quote_escapesCarriageReturnAndEveryOtherControlCharacter() {
assertEquals("\"a\\rb\"", TraceClient.quote("a\rb"));
assertEquals("\"\\u0000\"", TraceClient.quote("\u0000"));
assertEquals("\"\\u0008\"", TraceClient.quote("\b"));
assertEquals("\"\\u000c\"", TraceClient.quote("\f"));
assertEquals("\"\\u001f\"", TraceClient.quote("\u001f"));
assertEquals("\"\"", TraceClient.quote(""));
}
@Test
void quote_passesPrintableAndNonAsciiCharactersThrough() {
// Only what JSON requires is escaped; the body is sent as UTF-8.
assertEquals("\" /é€\u007f\"", TraceClient.quote(" /é€\u007f"));
}
@Test
void queue_isBoundedAndDropsRatherThanGrows() throws Exception {
// Arrange
// Hold the sending thread on the first report so everything behind it
// queues, overfill the queue, then let the server drain and count.
CountDownLatch release = new CountDownLatch(1);
AtomicInteger delivered = new AtomicInteger();
HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
slow.createContext("/", exchange -> {
try {
release.await(10, TimeUnit.SECONDS);
} catch (InterruptedException ignored) {
Thread.currentThread().interrupt();
}
delivered.incrementAndGet();
exchange.sendResponseHeaders(201, -1);
exchange.close();
});
slow.start();
RecordingHandler log = new RecordingHandler();
Logger logger = Logger.getLogger("TraceClientTest.flood");
logger.setLevel(Level.ALL);
logger.addHandler(log);
TraceClient client = TraceClient.builder("http://127.0.0.1:" + slow.getAddress().getPort(), "MyPlugin", "1.2.3")
.key("k").logger(logger).build();
int flood = TraceClient.QUEUE_CAPACITY * 3;
// Act
// startup, because it is never coalesced: every one of these goes
// to the queue, so the queue is all that bounds them.
for (int i = 0; i < flood; i++) {
client.report("startup");
}
release.countDown();
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20);
int seen = -1;
while (System.nanoTime() < deadline) {
Thread.sleep(200);
int now = delivered.get();
if (now == seen) {
break; // nothing arrived in the last 200 ms: the queue is drained
}
seen = now;
}
// Assert
assertTrue(delivered.get() >= 1, "the first report was in flight and must land");
assertTrue(delivered.get() <= TraceClient.QUEUE_CAPACITY + 1,
"delivered " + delivered.get() + " of " + flood + "; at most the in-flight one plus a full queue may survive");
assertTrue(delivered.get() < flood, "an unbounded queue would have delivered all " + flood);
client.close();
// The README says drops are silent. The server only answers 201, so
// the one other line the send path can write is "could not deliver",
// for a loopback connection that failed -- one stray line was seen
// once on Java 8 CI. Allow a few of those, far fewer than there were
// drops: logging each drop would be hundreds of lines.
List<String> messages = log.records.stream().map(LogRecord::getMessage).collect(Collectors.toList());
int dropped = flood - (TraceClient.QUEUE_CAPACITY + 1);
assertTrue(messages.stream().allMatch(m -> m.startsWith("[trace] could not deliver ")),
"only a failed send may be logged, but logged: " + messages);
assertTrue(messages.size() < dropped / 10,
"a full queue drops without logging, but logged " + messages.size() + " lines: " + messages);
slow.stop(0);
}
@Test
void close_sendsWhatWasJustQueuedBeforeStopping() throws Exception {
// A CLI reports once and exits at once. Without draining, the event
// races the sender thread and is lost a good fraction of the time; 30
// back-to-back report()+close() pairs make that fraction visible.
for (int i = 0; i < 30; i++) {
TraceClient client = TraceClient.builder(baseUrl(), "MyCli", "1.2.3").key("k").build();
client.report("startup", null, Collections.singletonMap("run", String.valueOf(i)));
client.close();
}
assertEquals(30, received.size(), "every report()+close() pair must deliver");
}
@Test
void close_stillReturnsWithinTheTimeoutWhenTheServerHangs() throws Exception {
CountDownLatch release = new CountDownLatch(1);
HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
slow.createContext("/", exchange -> {
try { release.await(15, TimeUnit.SECONDS); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); }
exchange.sendResponseHeaders(201, -1);
exchange.close();
});
slow.start();
TraceClient client = TraceClient.builder("http://127.0.0.1:" + slow.getAddress().getPort(), "MyCli", "1.2.3").key("k").build();
client.report("startup");
long before = System.nanoTime();
client.close();
long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - before);
assertTrue(elapsedMs < 7_000, "close() took " + elapsedMs + " ms; draining must be bounded by the timeout");
release.countDown();
slow.stop(0);
}
@Test
void close_whenInterruptedReturnsAtOnceAndKeepsTheInterruptFlag() throws Exception {
// Arrange
// A server holding a request, so close() would otherwise wait out
// the whole drain timeout. A host shutting down on an interrupt must
// not wait that long, and must still see that it was interrupted.
CountDownLatch inFlight = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
slow.createContext("/", exchange -> {
inFlight.countDown();
try { release.await(15, TimeUnit.SECONDS); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); }
exchange.sendResponseHeaders(201, -1);
exchange.close();
});
slow.start();
TraceClient client = TraceClient.builder("http://127.0.0.1:" + slow.getAddress().getPort(), "MyCli", "1.2.3").key("k").build();
client.report("startup");
assertTrue(inFlight.await(5, TimeUnit.SECONDS), "the report should reach the server");
// Act
Thread.currentThread().interrupt();
long before = System.nanoTime();
client.close();
long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - before);
boolean stillInterrupted = Thread.interrupted(); // clears it, so later tests run uninterrupted
// Assert
assertTrue(stillInterrupted, "close() must restore the interrupt it swallowed");
assertTrue(elapsedMs < 2_000, "close() took " + elapsedMs + " ms; an interrupt must cut the drain short");
release.countDown();
slow.stop(0);
}
@Test
void report_sendsFromOneDaemonThreadNamedForTheApplication() throws Exception {
// Arrange
// A server holding the first request, so the sender thread is alive
// and busy while the rest queue behind it.
CountDownLatch inFlight = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
HttpServer slow = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
slow.createContext("/", exchange -> {
inFlight.countDown();
try { release.await(15, TimeUnit.SECONDS); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); }
exchange.sendResponseHeaders(201, -1);
exchange.close();
});
slow.start();
TraceClient client = TraceClient.builder("http://127.0.0.1:" + slow.getAddress().getPort(), "ThreadProbe", "1.2.3")
.key("k").build();
// Act
for (int i = 0; i < 5; i++) {
client.report("startup");
}
assertTrue(inFlight.await(5, TimeUnit.SECONDS), "the first report should reach the server");
List<Thread> senders = Thread.getAllStackTraces().keySet().stream()
.filter(thread -> thread.getName().equals("trace-client/ThreadProbe"))
.collect(Collectors.toList());
// Assert
assertEquals(1, senders.size(), "one sender thread, however many reports wait");
assertTrue(senders.get(0).isDaemon(), "a daemon thread never keeps the host's JVM from exiting");
release.countDown();
client.close();
slow.stop(0);
}
@Test
void close_isSafeToCallTwice() throws Exception {
// Arrange
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build();
client.report("startup");
// Act
client.close();
// Assert
assertDoesNotThrow(client::close);
assertEquals(1, received.size(), "the report queued before the first close() is delivered once");
}
@Test
void report_afterCloseIsDroppedWithoutThrowing() throws Exception {
// Arrange
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build();
client.close();
// Act
assertDoesNotThrow(() -> client.report("late"));
// Assert
assertFalse(arrived.await(300, TimeUnit.MILLISECONDS), "nothing should be sent after close()");
assertTrue(received.isEmpty());
}
@Test
void report_sendsAUserAgentNamingTheClientAndTheApplication() throws Exception {
// Arrange
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build();
// Act
client.report("startup");
// Assert
assertTrue(arrived.await(5, TimeUnit.SECONDS));
String userAgent = received.get(0).userAgent;
assertTrue(userAgent != null && userAgent.matches("trace-client/\\d+\\.\\d+\\.\\d+ \\(MyPlugin\\)"),
"unexpected User-Agent: " + userAgent);
client.close();
}
@Test
void report_logsASuccessStatusOtherThan201() throws Exception {
// Arrange
// The server answers 201 Created; any other status, even a 2xx, is
// worth a FINE line because it means the endpoint is not what the
// client expects.
replyStatus = 200;
RecordingHandler log = new RecordingHandler();
Logger logger = Logger.getLogger("TraceClientTest.status200");
logger.setLevel(Level.ALL);
logger.addHandler(log);
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").logger(logger).build();
// Act
assertDoesNotThrow(() -> client.report("startup"));
// Assert
assertTrue(log.await(5, TimeUnit.SECONDS));
assertEquals(Level.FINE, log.records.get(0).getLevel());
assertTrue(log.records.get(0).getMessage().startsWith("[trace] trace server answered 200"),
log.records.get(0).getMessage());
client.close();
}
@Test
void report_aBaseUrlThatIsNotHttpIsLoggedFineAndNeverThrows() throws Exception {
// Arrange
// build() takes the base URL as a string and never parses it, so a
// typo only shows up in send(): "no protocol" is an IOException, and a
// file: URL opens a connection that is not an HttpURLConnection -- a
// ClassCastException, which is why send() catches RuntimeException too.
String[][] cases = {
{"not a url", "java.net.MalformedURLException"},
{"file:///trace-client-test", "java.lang.ClassCastException"},
};
for (String[] misconfigured : cases) {
RecordingHandler log = new RecordingHandler();
Logger logger = Logger.getLogger("TraceClientTest.misconfigured." + misconfigured[1]);
logger.setLevel(Level.ALL);
logger.addHandler(log);
TraceClient client = assertDoesNotThrow(() ->
TraceClient.builder(misconfigured[0], "MyPlugin", "1.2.3").key("k").logger(logger).build());
assertTrue(client.isEnabled(), "a bad URL is not an opt-out");
// Act
assertDoesNotThrow(() -> client.report("startup"));
client.close();
// Assert
assertTrue(log.await(5, TimeUnit.SECONDS), misconfigured[0] + " should be mentioned at FINE");
LogRecord record = log.records.get(0);
assertEquals(Level.FINE, record.getLevel());
assertTrue(record.getMessage().startsWith("[trace] could not deliver {\"application\":\"MyPlugin\""),
record.getMessage());
assertTrue(record.getMessage().contains(misconfigured[1]), record.getMessage());
}
}
@Test
void report_drainsAResponseBodyAndKeepsSendingAfterAnError() throws Exception {
// Arrange
// Unlike the shared server, this one answers with a body: an error page
// first, then a 201 with content. send() reads either to its end and
// the next report still goes out.
List<String> bodies = new CopyOnWriteArrayList<>();
CountDownLatch both = new CountDownLatch(2);
HttpServer chatty = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
chatty.createContext("/", exchange -> {
bodies.add(new String(readAll(exchange.getRequestBody()), StandardCharsets.UTF_8));
byte[] reply = new byte[4096]; // more than drain()'s 512-byte buffer
Arrays.fill(reply, (byte) 'x');
exchange.sendResponseHeaders(bodies.size() == 1 ? 500 : 201, reply.length);
exchange.getResponseBody().write(reply);
exchange.close();
both.countDown();
});
chatty.start();
RecordingHandler log = new RecordingHandler();
Logger logger = Logger.getLogger("TraceClientTest.chatty");
logger.setLevel(Level.ALL);
logger.addHandler(log);
TraceClient client = TraceClient.builder("http://127.0.0.1:" + chatty.getAddress().getPort(), "MyPlugin", "1.2.3")
.key("k").logger(logger).build();
// Act
client.report("first");
client.report("second");
client.close();
// Assert
assertTrue(both.await(5, TimeUnit.SECONDS), "both reports should reach the server");
assertEquals(2, bodies.size());
assertTrue(bodies.get(1).contains("\"name\":\"second\""), bodies.get(1));
assertEquals(1, log.records.size(), "only the 500 is worth a line: " + log.records);
assertEquals("[trace] trace server answered 500 for "
+ "{\"application\":\"MyPlugin\",\"name\":\"first\",\"tags\":{\"version\":\"1.2.3\"}}",
log.records.get(0).getMessage());
chatty.stop(0);
}
@Test
void report_keepsAPathInTheBaseUrlInFrontOfApiMetrics() throws Exception {
// Arrange
// A trace server behind a reverse proxy under a sub-path: only the
// trailing slashes go, the path itself stays.
TraceClient client = TraceClient.builder(baseUrl() + "/trace/", "MyPlugin", "1.2.3").key("k").build();
// Act
client.report("startup");
// Assert
assertTrue(arrived.await(5, TimeUnit.SECONDS));
assertEquals("/trace/api/metrics", received.get(0).path);
client.close();
}
@Test
void report_aRedirectIsNotFollowedAndIsLoggedFine() throws Exception {
// Arrange
// Characterizes current behaviour: the body is streamed with a fixed
// length, so HttpURLConnection cannot replay it to a redirect target.
// It throws HttpRetryException instead, so a base URL that redirects
// (http to https, say) drops every report, and the only trace of it
// is a FINE "could not deliver" line.
List<String> paths = new CopyOnWriteArrayList<>();
HttpServer redirecting = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
redirecting.createContext("/", exchange -> {
paths.add(exchange.getRequestURI().getPath());
readAll(exchange.getRequestBody());
exchange.getResponseHeaders().add("Location", "/moved/api/metrics");
exchange.sendResponseHeaders(301, -1);
exchange.close();
});
redirecting.start();
RecordingHandler log = new RecordingHandler();
Logger logger = Logger.getLogger("TraceClientTest.redirect");
logger.setLevel(Level.ALL);
logger.addHandler(log);
TraceClient client = TraceClient.builder("http://127.0.0.1:" + redirecting.getAddress().getPort(), "MyPlugin", "1.2.3")
.key("k").logger(logger).build();
// Act
assertDoesNotThrow(() -> client.report("startup"));
// Assert
assertTrue(log.await(5, TimeUnit.SECONDS), "the redirect should be mentioned at FINE");
client.close();
assertEquals(Collections.singletonList("/api/metrics"), paths, "the redirect target is never asked");
assertEquals(Level.FINE, log.records.get(0).getLevel());
String message = log.records.get(0).getMessage();
assertTrue(message.startsWith("[trace] could not deliver {\"application\":\"MyPlugin\",\"name\":\"startup\""), message);
assertTrue(message.contains("java.net.HttpRetryException"), message);
redirecting.stop(0);
}
@Test
void builder_trimsTheBaseUrlAndApplicationAndDropsEveryTrailingSlash() throws Exception {
// Arrange
TraceClient client = TraceClient.builder(" " + baseUrl() + "/// ", " MyPlugin ", "1.2.3").key("k").build();
// Act
client.report("startup");
// Assert
assertTrue(arrived.await(5, TimeUnit.SECONDS));
assertEquals("/api/metrics", received.get(0).path);
assertEquals("{\"application\":\"MyPlugin\",\"name\":\"startup\",\"tags\":{\"version\":\"1.2.3\"}}", received.get(0).body);
client.close();
}
@Test
void disabledClient_saysWhy() {
assertEquals(TraceClient.REASON_CONFIG, TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").enabled(false).build().disabledReason());
assertEquals(TraceClient.REASON_NO_KEY, TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").build().disabledReason());
assertEquals(TraceClient.REASON_NO_KEY, TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key(" ").build().disabledReason());
assertNull(TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k").build().disabledReason(), "an enabled client has no reason");
}
@Test
void serverWideConfig_isCreatedWithTheExactContentWhenMissing(@TempDir Path plugins) throws Exception {
// Arrange
File pluginsDirectory = plugins.toFile();
Path file = plugins.resolve("trace").resolve("config.yml");
assertFalse(Files.exists(file));
// Act
TraceClient client = TraceClient.builder(baseUrl(), "MyPlugin", "1.2.3").key("k")
.serverWideConfig(pluginsDirectory).build();
// Assert
assertTrue(Files.exists(file), "plugins/trace/config.yml should have been created");