Repository navigation
Expand file tree
/
Copy pathCongestionClientTracingIntegrationTest.java
More file actions
273 lines (250 loc) · 12.3 KB
/
Copy pathCongestionClientTracingIntegrationTest.java
File metadata and controls
273 lines (250 loc) · 12.3 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
package com.beachcheck.external.congestion;
import static com.beachcheck.support.tracing.SpanTestSupport.awaitSpans;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withServerError;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import com.beachcheck.global.tracing.HttpClientTracingConfiguration;
import com.beachcheck.global.tracing.QuerylessClientRequestObservationConvention;
import com.beachcheck.global.tracing.ServerErrorClientRequestObservationHandler;
import com.beachcheck.global.tracing.W3cTracePropagationConfig;
import com.beachcheck.support.tracing.RecordingSpanExporter;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.data.SpanData;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestClient;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
@DisplayName("CongestionClient Trace 통합 계약")
class CongestionClientTracingIntegrationTest {
private static final String BASE_URL = "https://example.com";
private static final String BEACH_CODE = "GYEONGPO";
private static final String REQUEST_URL = BASE_URL + "/congestion/current?beach_id=" + BEACH_CODE;
private static final String TRANSPORT_ERROR_DETAIL = "transport failed for " + BEACH_CODE;
private final ApplicationContextRunner contextRunner =
new ApplicationContextRunner()
.withUserConfiguration(TraceTestConfiguration.class)
.withPropertyValues("management.tracing.sampling.probability=1.0");
@Test
@DisplayName("RestClient가 부모 Trace를 전파하고 traceparent를 SigV4 서명에 포함한다")
void fetchCurrent_propagatesParentTraceAndSignsTraceparent() {
contextRunner.run(
context -> {
// Given
TraceClientFixture fixture = context.getBean(TraceClientFixture.class);
Tracer tracer = context.getBean(Tracer.class);
RecordingSpanExporter exporter = context.getBean(RecordingSpanExporter.class);
SdkTracerProvider tracerProvider = context.getBean(SdkTracerProvider.class);
AtomicReference<String> traceparent = new AtomicReference<>();
AtomicReference<String> authorization = new AtomicReference<>();
fixture
.server()
.expect(requestTo(REQUEST_URL))
.andExpect(method(GET))
.andExpect(
request -> {
traceparent.set(request.getHeaders().getFirst("traceparent"));
authorization.set(request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION));
})
.andRespond(
withSuccess(
"""
{
"beach_id": "GYEONGPO",
"beach_name": "Gyeongpo Beach"
}
""",
MediaType.APPLICATION_JSON));
Span parent = tracer.nextSpan().name("congestion.parent.test").start();
// When
CongestionCurrentResponse response;
try (Tracer.SpanInScope ignored = tracer.withSpan(parent)) {
response = fixture.client().fetchCurrent(BEACH_CODE);
} finally {
parent.end();
}
// Then
List<SpanData> spans = awaitSpans(exporter, tracerProvider, 2);
SpanData clientSpan = onlyClientSpan(spans);
assertThat(response).isNotNull();
assertThat(clientSpan.getTraceId()).isEqualTo(parent.context().traceId());
assertThat(clientSpan.getParentSpanId()).isEqualTo(parent.context().spanId());
assertThat(traceparent.get()).isNotBlank();
assertThat(traceparent.get().split("-"))
.containsExactly("00", clientSpan.getTraceId(), clientSpan.getSpanId(), "01");
assertThat(signedHeaders(authorization.get())).contains("traceparent");
assertThat(clientSpan.getAttributes().get(AttributeKey.stringKey("http.url")))
.isEqualTo(BASE_URL + "/congestion/current");
assertThat(clientSpan.getAttributes().asMap().values())
.map(Object::toString)
.allSatisfy(
value ->
assertThat(value)
.doesNotContain(
BEACH_CODE,
authorization.get(),
"test-access-key",
"test-secret-key",
"Signature="));
fixture.server().verify();
});
}
@Test
@DisplayName("500 응답은 기존 null 반환을 유지하고 HTTP client span에 실패 결과를 기록한다")
void fetchCurrent_serverErrorReturnsNullAndRecordsFailureResult() {
contextRunner.run(
context -> {
// Given
TraceClientFixture fixture = context.getBean(TraceClientFixture.class);
Tracer tracer = context.getBean(Tracer.class);
RecordingSpanExporter exporter = context.getBean(RecordingSpanExporter.class);
SdkTracerProvider tracerProvider = context.getBean(SdkTracerProvider.class);
fixture
.server()
.expect(requestTo(REQUEST_URL))
.andExpect(method(GET))
.andRespond(withServerError());
Span parent = tracer.nextSpan().name("congestion.parent.test").start();
// When
CongestionCurrentResponse response;
try (Tracer.SpanInScope ignored = tracer.withSpan(parent)) {
response = fixture.client().fetchCurrent(BEACH_CODE);
} finally {
parent.end();
}
// Then
SpanData clientSpan = onlyClientSpan(awaitSpans(exporter, tracerProvider, 2));
assertThat(response).isNull();
assertThat(clientSpan.getAttributes().get(AttributeKey.stringKey("status")))
.isEqualTo("500");
assertThat(clientSpan.getAttributes().get(AttributeKey.stringKey("outcome")))
.isEqualTo("SERVER_ERROR");
assertThat(clientSpan.getStatus().getStatusCode()).isEqualTo(StatusCode.ERROR);
assertThat(clientSpan.getParentSpanId()).isEqualTo(parent.context().spanId());
fixture.server().verify();
});
}
@Test
@DisplayName("transport 예외는 원문 없이 일반화된 실패만 HTTP client span에 기록한다")
void fetchCurrent_transportErrorRecordsSanitizedFailure() {
contextRunner.run(
context -> {
// Given
TraceClientFixture fixture = context.getBean(TraceClientFixture.class);
Tracer tracer = context.getBean(Tracer.class);
RecordingSpanExporter exporter = context.getBean(RecordingSpanExporter.class);
SdkTracerProvider tracerProvider = context.getBean(SdkTracerProvider.class);
fixture
.server()
.expect(requestTo(REQUEST_URL))
.andExpect(method(GET))
.andRespond(
request -> {
throw new java.io.IOException(TRANSPORT_ERROR_DETAIL);
});
Span parent = tracer.nextSpan().name("congestion.parent.test").start();
// When
CongestionCurrentResponse response;
try (Tracer.SpanInScope ignored = tracer.withSpan(parent)) {
response = fixture.client().fetchCurrent(BEACH_CODE);
} finally {
parent.end();
}
// Then
SpanData clientSpan = onlyClientSpan(awaitSpans(exporter, tracerProvider, 2));
assertThat(response).isNull();
assertThat(clientSpan.getStatus().getStatusCode()).isEqualTo(StatusCode.ERROR);
assertThat(clientSpan.getStatus().getDescription())
.isEqualTo("HTTP client request failed");
assertThat(clientSpan.getAttributes().get(AttributeKey.stringKey("error.type")))
.isEqualTo("org.springframework.web.client.ResourceAccessException");
assertSpanDoesNotContain(clientSpan, BEACH_CODE, TRANSPORT_ERROR_DETAIL);
fixture.server().verify();
});
}
private SpanData onlyClientSpan(List<SpanData> spans) {
List<SpanData> clientSpans =
spans.stream().filter(span -> span.getKind() == SpanKind.CLIENT).toList();
assertThat(clientSpans).hasSize(1);
return clientSpans.getFirst();
}
private String signedHeaders(String authorization) {
assertThat(authorization).contains("SignedHeaders=");
return authorization.substring(
authorization.indexOf("SignedHeaders=") + "SignedHeaders=".length(),
authorization.indexOf(',', authorization.indexOf("SignedHeaders=")));
}
private void assertSpanDoesNotContain(SpanData span, String... forbiddenValues) {
for (String forbiddenValue : forbiddenValues) {
assertThat(span.getName()).doesNotContain(forbiddenValue);
assertThat(span.getStatus().getDescription()).doesNotContain(forbiddenValue);
assertThat(span.getAttributes().asMap().values().toString()).doesNotContain(forbiddenValue);
assertThat(span.getEvents())
.allSatisfy(
event -> {
assertThat(event.getName()).doesNotContain(forbiddenValue);
assertThat(event.getAttributes().asMap().values().toString())
.doesNotContain(forbiddenValue);
});
assertThat(span.toString()).doesNotContain(forbiddenValue);
}
}
@TestConfiguration(proxyBeanMethods = false)
@EnableAutoConfiguration(
exclude = {
DataSourceAutoConfiguration.class,
FlywayAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
@Import({
HttpClientTracingConfiguration.class,
W3cTracePropagationConfig.class,
QuerylessClientRequestObservationConvention.class,
ServerErrorClientRequestObservationHandler.class
})
static class TraceTestConfiguration {
@Bean
RecordingSpanExporter recordingSpanExporter() {
return new RecordingSpanExporter();
}
@Bean
AwsCredentialsProvider awsCredentialsProvider() {
return StaticCredentialsProvider.create(
AwsBasicCredentials.create("test-access-key", "test-secret-key"));
}
@Bean
CongestionInterceptor congestionInterceptor(AwsCredentialsProvider credentialsProvider) {
return new AwsSigV4Interceptor(credentialsProvider, "us-east-1");
}
@Bean
TraceClientFixture traceClientFixture(
RestClient.Builder builder, CongestionInterceptor congestionInterceptor) {
MockRestServiceServer server = MockRestServiceServer.bindTo(builder).build();
CongestionClient client = new CongestionClient(BASE_URL, builder, congestionInterceptor);
return new TraceClientFixture(client, server);
}
}
private record TraceClientFixture(CongestionClient client, MockRestServiceServer server) {}
}