Repository navigation
Expand file tree
/
Copy pathStreamHTTPClientTest.java
More file actions
490 lines (429 loc) · 19.2 KB
/
Copy pathStreamHTTPClientTest.java
File metadata and controls
490 lines (429 loc) · 19.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
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
package io.getstream;
import static org.junit.jupiter.api.Assertions.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.getstream.models.MessageResponse;
import io.getstream.models.TrackActivityMetricsEvent;
import io.getstream.models.TrackActivityMetricsRequest;
import io.getstream.models.UpdateAppRequest;
import io.getstream.services.framework.StreamClientOptions;
import io.getstream.services.framework.StreamHTTPClient;
import io.getstream.services.framework.StreamSDKClient;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class StreamHTTPClientTest {
private static StreamHTTPClient client;
private static ObjectMapper objectMapper;
@BeforeAll
static void setup() {
// Initialize with test credentials (secret must be at least 32 characters for HS256)
client = new StreamHTTPClient("apiKey", "012345678901234567890123456789ab");
objectMapper = client.getObjectMapper();
}
@Test
void testUnixNanosecondTimestampParsing() throws Exception {
long timestampInNanos = 1704542400000000000L;
long timestampInMillis = timestampInNanos / 1_000_000;
// Create a JSON response with unix microsecond timestamp
String json =
String.format(
"""
{
"id": "test-message-id",
"text": "Test message",
"type": "regular",
"created_at": %d,
"updated_at": %d
}
""",
timestampInNanos, timestampInNanos);
// Parse the JSON
MessageResponse message = objectMapper.readValue(json, MessageResponse.class);
// Expected date: 2024-01-06 12:00:00 UTC
Date expectedDate = new Date(timestampInMillis);
// Assert that the parsed date matches the expected date
assertEquals(
expectedDate.getTime(),
message.getCreatedAt().getTime(),
1000, // Allow 1 second tolerance
String.format(
"Expected timestamp %d (2024-01-06) but got %d (%s)",
expectedDate.getTime(), message.getCreatedAt().getTime(), message.getCreatedAt()));
assertEquals(
expectedDate.getTime(),
message.getUpdatedAt().getTime(),
1000, // Allow 1 second tolerance
String.format(
"Expected timestamp %d (2024-01-06) but got %d (%s)",
expectedDate.getTime(), message.getUpdatedAt().getTime(), message.getUpdatedAt()));
}
@Test
void testNullFieldsOmittedFromSerialization() throws JsonProcessingException {
// Only set one field, leave everything else null
UpdateAppRequest request = UpdateAppRequest.builder().enforceUniqueUsernames("no").build();
String json = objectMapper.writeValueAsString(request);
// The set field must be present
assertTrue(json.contains("\"enforce_unique_usernames\":\"no\""));
// Null fields must be omitted, not serialized as null
assertFalse(json.contains("null"), "Null fields should be omitted, got: " + json);
assertFalse(json.contains("webhook_url"));
assertFalse(json.contains("multi_tenant_enabled"));
}
@Test
void testCollectionFieldsSerializedWhenSet() throws JsonProcessingException {
// An explicitly set empty list should still be serialized
UpdateAppRequest request = UpdateAppRequest.builder().grants(new java.util.HashMap<>()).build();
String json = objectMapper.writeValueAsString(request);
assertTrue(
json.contains("\"grants\":{}"),
"Empty collections should be serialized when explicitly set, got: " + json);
}
@Test
void testActivityMetricsConfigSerializedWhenSet() throws JsonProcessingException {
UpdateAppRequest request =
UpdateAppRequest.builder()
.activityMetricsConfig(Map.of("views", 10, "clicks", 5, "shares", 25))
.build();
String json = objectMapper.writeValueAsString(request);
assertTrue(json.contains("\"activity_metrics_config\""), "Expected config field in: " + json);
assertTrue(json.contains("\"views\":10"), "Expected default metric override in: " + json);
assertTrue(json.contains("\"clicks\":5"), "Expected default metric override in: " + json);
assertTrue(json.contains("\"shares\":25"), "Expected custom metric in: " + json);
}
@Test
void testTrackActivityMetricsRequestSerializedWithCustomMetric() throws JsonProcessingException {
TrackActivityMetricsRequest request =
TrackActivityMetricsRequest.builder()
.userID("user-123")
.events(
List.of(
TrackActivityMetricsEvent.builder()
.activityID("activity-123")
.metric("shares")
.delta(3)
.build()))
.build();
String json = objectMapper.writeValueAsString(request);
assertTrue(json.contains("\"user_id\":\"user-123\""), "Expected user_id in: " + json);
assertTrue(json.contains("\"events\""), "Expected events array in: " + json);
assertTrue(
json.contains("\"activity_id\":\"activity-123\""), "Expected activity ID in: " + json);
assertTrue(json.contains("\"metric\":\"shares\""), "Expected custom metric in: " + json);
assertTrue(json.contains("\"delta\":3"), "Expected delta in: " + json);
}
@Test
void testCustomOkHttpClientPreservesConfig() {
ConnectionPool customPool = new ConnectionPool(20, 120, TimeUnit.SECONDS);
OkHttpClient customHttp =
new OkHttpClient.Builder()
.connectionPool(customPool)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(45, TimeUnit.SECONDS)
.build();
var sdkClient = new StreamSDKClient("apiKey", "012345678901234567890123456789ab", customHttp);
OkHttpClient builtClient = sdkClient.getHttpClient().getHttpClient();
assertSame(customPool, builtClient.connectionPool());
assertEquals(30_000, builtClient.connectTimeoutMillis());
assertEquals(45_000, builtClient.readTimeoutMillis());
assertFalse(
builtClient.interceptors().isEmpty(), "SDK should add its interceptors to the client");
}
@Test
void testDefaultConstructorStillWorks() {
assertNotNull(client.getHttpClient());
assertFalse(client.getHttpClient().interceptors().isEmpty());
}
@Test
void testRFC3339TimestampParsing() throws Exception {
// Create a JSON response with RFC 3339 formatted timestamp
String json =
"""
{
"id": "test-message-id",
"text": "Test message",
"type": "regular",
"created_at": "2024-01-06T12:00:00.000Z",
"updated_at": "2024-01-06T12:00:00Z"
}
""";
// Parse the JSON
MessageResponse message = objectMapper.readValue(json, MessageResponse.class);
// Expected date: 2024-01-06 12:00:00 UTC
Date expectedDate = new Date(1704542400000L);
// Assert that the parsed date matches the expected date
assertEquals(
expectedDate.getTime(),
message.getCreatedAt().getTime(),
1000, // Allow 1 second tolerance
String.format(
"Expected timestamp %d (2024-01-06T12:00:00Z) but got %d (%s)",
expectedDate.getTime(), message.getCreatedAt().getTime(), message.getCreatedAt()));
assertEquals(
expectedDate.getTime(),
message.getUpdatedAt().getTime(),
1000, // Allow 1 second tolerance
String.format(
"Expected timestamp %d (2024-01-06T12:00:00Z) but got %d (%s)",
expectedDate.getTime(), message.getUpdatedAt().getTime(), message.getUpdatedAt()));
}
@Test
void testStreamClientOptionsDefaults() {
StreamClientOptions opts = new StreamClientOptions();
assertEquals(100, opts.getMaxConnsPerHost(), "default MaxConnsPerHost = 100");
assertEquals(Duration.ofSeconds(55), opts.getIdleTimeout(), "default IdleTimeout = 55s");
assertEquals(Duration.ofSeconds(10), opts.getConnectTimeout(), "default ConnectTimeout = 10s");
assertEquals(Duration.ofSeconds(30), opts.getRequestTimeout(), "default RequestTimeout = 30s");
assertNull(opts.getHttpClient(), "no user-supplied OkHttpClient by default");
}
@Test
void testStreamClientOptionsFluentSetters() {
StreamClientOptions opts =
new StreamClientOptions()
.setMaxConnsPerHost(10)
.setIdleTimeout(Duration.ofSeconds(120))
.setConnectTimeout(Duration.ofSeconds(5))
.setRequestTimeout(Duration.ofSeconds(20));
assertEquals(10, opts.getMaxConnsPerHost());
assertEquals(Duration.ofSeconds(120), opts.getIdleTimeout());
assertEquals(Duration.ofSeconds(5), opts.getConnectTimeout());
assertEquals(Duration.ofSeconds(20), opts.getRequestTimeout());
}
@Test
void testStreamHTTPClientUsesDefaultOptions() {
StreamHTTPClient http = new StreamHTTPClient("apiKey", "012345678901234567890123456789ab");
OkHttpClient built = http.getHttpClient();
assertNotNull(built.connectionPool());
assertEquals(10_000, built.connectTimeoutMillis(), "default ConnectTimeout = 10_000ms");
assertEquals(30_000, built.callTimeoutMillis(), "default RequestTimeout = 30_000ms");
// OkHttp 4.x does not expose ConnectionPool.maxIdleConnections() publicly; we cover the
// pass-through path indirectly via the options-driven test below + the escape-hatch test.
}
@Test
void testStreamHTTPClientAppliesCustomOptions() {
StreamClientOptions opts =
new StreamClientOptions()
.setMaxConnsPerHost(20)
.setIdleTimeout(Duration.ofSeconds(90))
.setConnectTimeout(Duration.ofSeconds(7))
.setRequestTimeout(Duration.ofSeconds(45));
OkHttpClient built =
new StreamHTTPClient("apiKey", "012345678901234567890123456789ab", opts).getHttpClient();
assertEquals(7_000, built.connectTimeoutMillis());
assertEquals(45_000, built.callTimeoutMillis());
}
@Test
void testStreamSDKClientWithOptions() {
StreamClientOptions opts =
new StreamClientOptions().setMaxConnsPerHost(15).setRequestTimeout(Duration.ofSeconds(25));
StreamSDKClient sdk = new StreamSDKClient("apiKey", "012345678901234567890123456789ab", opts);
OkHttpClient built = sdk.getHttpClient().getHttpClient();
assertEquals(25_000, built.callTimeoutMillis(), "RequestTimeout flows through SDK client");
}
@Test
void testEscapeHatchViaOptionsBypassesKnobs() {
ConnectionPool customPool = new ConnectionPool(42, 200, TimeUnit.SECONDS);
OkHttpClient userClient =
new OkHttpClient.Builder()
.connectionPool(customPool)
.connectTimeout(77, TimeUnit.SECONDS)
.callTimeout(88, TimeUnit.SECONDS)
.build();
StreamClientOptions opts =
new StreamClientOptions()
.setHttpClient(userClient)
// All four below MUST be ignored when an OkHttpClient is supplied:
.setMaxConnsPerHost(99)
.setIdleTimeout(Duration.ofSeconds(99))
.setConnectTimeout(Duration.ofSeconds(99))
.setRequestTimeout(Duration.ofSeconds(99));
StreamSDKClient sdk = new StreamSDKClient("apiKey", "012345678901234567890123456789ab", opts);
OkHttpClient built = sdk.getHttpClient().getHttpClient();
assertSame(customPool, built.connectionPool(), "user pool preserved");
assertEquals(77_000, built.connectTimeoutMillis(), "user connectTimeout preserved");
assertEquals(88_000, built.callTimeoutMillis(), "user callTimeout preserved");
assertFalse(
built.interceptors().isEmpty(), "SDK still adds its interceptors to user-supplied client");
}
// Records the SLF4J events emitted at construction (client.initialized replaced the old
// java.util.logging "connection pool:" line in CHA-2957); inject via StreamClientOptions.
static final class RecordingLogger extends org.slf4j.helpers.LegacyAbstractLogger {
final List<String> messages = new ArrayList<>();
@Override
protected void handleNormalizedLoggingCall(
org.slf4j.event.Level level,
org.slf4j.Marker marker,
String messagePattern,
Object[] arguments,
Throwable throwable) {
messages.add(org.slf4j.helpers.MessageFormatter.basicArrayFormat(messagePattern, arguments));
}
@Override
protected String getFullyQualifiedCallerName() {
return null;
}
@Override
public boolean isTraceEnabled() {
return true;
}
@Override
public boolean isDebugEnabled() {
return true;
}
@Override
public boolean isInfoEnabled() {
return true;
}
@Override
public boolean isWarnEnabled() {
return true;
}
@Override
public boolean isErrorEnabled() {
return true;
}
}
private static String lastClientInitialized(RecordingLogger rec) {
return rec.messages.stream()
.filter(m -> m.startsWith("client.initialized"))
.reduce((a, b) -> b)
.orElseThrow();
}
@Test
void testInfoLogOnConstructionWithDefaults() {
RecordingLogger rec = new RecordingLogger();
new StreamHTTPClient(
"apiKey", "012345678901234567890123456789ab", new StreamClientOptions().setLogger(rec));
String got = lastClientInitialized(rec);
assertTrue(got.contains("stream.client.max_conns_per_host=100"), got);
assertTrue(got.contains("stream.client.idle_timeout_seconds=55"), got);
assertTrue(got.contains("stream.client.connect_timeout_seconds=10"), got);
assertTrue(got.contains("stream.client.request_timeout_seconds=30"), got);
assertTrue(got.contains("stream.client.user_http_client=false"), got);
}
@Test
void testInfoLogOnConstructionWithUserHttpClient() {
RecordingLogger rec = new RecordingLogger();
StreamClientOptions opts =
new StreamClientOptions().setHttpClient(new OkHttpClient.Builder().build()).setLogger(rec);
new StreamHTTPClient("apiKey", "012345678901234567890123456789ab", opts);
String got = lastClientInitialized(rec);
assertTrue(got.contains("stream.client.user_http_client=true"), got);
}
@Test
void testStreamHTTPClientDispatcherCapsRequestsPerHost() {
StreamClientOptions opts = new StreamClientOptions().setMaxConnsPerHost(17);
OkHttpClient built =
new StreamHTTPClient("apiKey", "012345678901234567890123456789ab", opts).getHttpClient();
assertEquals(
17,
built.dispatcher().getMaxRequestsPerHost(),
"maxConnsPerHost must drive Dispatcher.maxRequestsPerHost (the real per-host cap)");
}
@Test
void testDispatcherDefaultPerHostCap() {
OkHttpClient built =
new StreamHTTPClient("apiKey", "012345678901234567890123456789ab").getHttpClient();
assertEquals(100, built.dispatcher().getMaxRequestsPerHost());
}
@Test
void testDefaultPoolKeepsBurstConnectionsWarm() throws Exception {
int n = 10;
try (MockWebServer server = new MockWebServer()) {
for (int i = 0; i < n; i++) {
server.enqueue(new MockResponse().setBody("{}").setBodyDelay(200, TimeUnit.MILLISECONDS));
}
server.start();
OkHttpClient built =
new StreamHTTPClient("apiKey", "012345678901234567890123456789ab").getHttpClient();
Request request = new Request.Builder().url(server.url("/")).build();
ExecutorService executor = Executors.newFixedThreadPool(n);
List<Future<String>> calls = new ArrayList<>();
for (int i = 0; i < n; i++) {
calls.add(
executor.submit(
() -> {
try (Response response = built.newCall(request).execute()) {
return response.body().string();
}
}));
}
for (Future<String> call : calls) {
call.get(10, TimeUnit.SECONDS);
}
executor.shutdown();
// Let the pool's async cleanup evict anything over its idle limit.
Thread.sleep(300);
assertEquals(n, built.connectionPool().idleConnectionCount());
}
}
@Test
void testApiTimeoutEnvPropertyStillOverridesRequestTimeout() {
// Regression guard for CHA-2956: the legacy STREAM_API_TIMEOUT / io.getstream.timeout override
// must still take effect via the env/properties constructor path. The env var and the system
// property share one code path (getOrDefault falls through to the property), so driving it
// through the property exercises the same fold-into-options logic.
String prevTimeout = System.getProperty(StreamHTTPClient.API_TIMEOUT_PROP_NAME);
String prevKey = System.getProperty(StreamHTTPClient.API_KEY_PROP_NAME);
String prevSecret = System.getProperty(StreamHTTPClient.API_SECRET_PROP_NAME);
try {
System.setProperty(StreamHTTPClient.API_TIMEOUT_PROP_NAME, "12345");
System.setProperty(StreamHTTPClient.API_KEY_PROP_NAME, "apiKey");
System.setProperty(StreamHTTPClient.API_SECRET_PROP_NAME, "012345678901234567890123456789ab");
OkHttpClient built = new StreamHTTPClient(System.getProperties()).getHttpClient();
assertEquals(
12_345,
built.callTimeoutMillis(),
"STREAM_API_TIMEOUT / io.getstream.timeout must drive the request (call) timeout");
} finally {
restoreProperty(StreamHTTPClient.API_TIMEOUT_PROP_NAME, prevTimeout);
restoreProperty(StreamHTTPClient.API_KEY_PROP_NAME, prevKey);
restoreProperty(StreamHTTPClient.API_SECRET_PROP_NAME, prevSecret);
}
}
@Test
void testConnectionMaxAgeEnvPropertyStillOverridesIdleTimeout() {
// Regression guard for CHA-2956: STREAM_API_CONNECTION_MAX_AGE / io.getstream.connection.maxAge
// must still take effect. OkHttp's ConnectionPool does not expose idle-ms publicly, so we
// assert via the effective-config INFO log, which reads options.getIdleTimeout().
String prevMaxAge = System.getProperty(StreamHTTPClient.API_CONNECTION_MAX_AGE_PROP_NAME);
String prevKey = System.getProperty(StreamHTTPClient.API_KEY_PROP_NAME);
String prevSecret = System.getProperty(StreamHTTPClient.API_SECRET_PROP_NAME);
try {
System.setProperty(StreamHTTPClient.API_CONNECTION_MAX_AGE_PROP_NAME, "123");
System.setProperty(StreamHTTPClient.API_KEY_PROP_NAME, "apiKey");
System.setProperty(StreamHTTPClient.API_SECRET_PROP_NAME, "012345678901234567890123456789ab");
RecordingLogger rec = new RecordingLogger();
new StreamHTTPClient(System.getProperties(), new StreamClientOptions().setLogger(rec));
String got = lastClientInitialized(rec);
assertTrue(
got.contains("stream.client.idle_timeout_seconds=123"),
"STREAM_API_CONNECTION_MAX_AGE must drive the idle timeout (123s), got: " + got);
} finally {
restoreProperty(StreamHTTPClient.API_CONNECTION_MAX_AGE_PROP_NAME, prevMaxAge);
restoreProperty(StreamHTTPClient.API_KEY_PROP_NAME, prevKey);
restoreProperty(StreamHTTPClient.API_SECRET_PROP_NAME, prevSecret);
}
}
private static void restoreProperty(String key, String prev) {
if (prev == null) {
System.clearProperty(key);
} else {
System.setProperty(key, prev);
}
}
}