Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions src/main/java/uk/gov/hmcts/cp/filters/TracingFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
@Slf4j
public class TracingFilter extends OncePerRequestFilter {

public static final String CORRELATION_ID_HEADER = "X-Correlation-Id";
public static final String MDC_CORRELATION_ID = "correlationId";
public static final String CORRELATION_ID_KEY = "X-Correlation-Id";

@Override
protected boolean shouldNotFilter(@Nonnull final HttpServletRequest request) {
Expand All @@ -33,15 +32,18 @@ protected void doFilterInternal(@Nonnull final HttpServletRequest request,
@Nonnull final HttpServletResponse response,
@Nonnull final FilterChain filterChain) throws ServletException, IOException {
try {
String correlationId = request.getHeader(CORRELATION_ID_HEADER);
if (correlationId == null) {
correlationId = UUID.randomUUID().toString();
}
MDC.put(MDC_CORRELATION_ID, correlationId);
response.setHeader(CORRELATION_ID_HEADER, correlationId);
final String correlationId = getCorrelationId(request);
MDC.put(CORRELATION_ID_KEY, getCorrelationId(request));
response.setHeader(CORRELATION_ID_KEY, correlationId);
filterChain.doFilter(request, response);
} finally {
MDC.remove(MDC_CORRELATION_ID);
MDC.remove(CORRELATION_ID_KEY);
}
}

private String getCorrelationId(final HttpServletRequest request) {
return request.getHeader(CORRELATION_ID_KEY) == null
? UUID.randomUUID().toString()
: request.getHeader(CORRELATION_ID_KEY);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import java.time.OffsetDateTime;
import java.util.UUID;

import static uk.gov.hmcts.cp.filters.TracingFilter.MDC_CORRELATION_ID;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_KEY;

@Service
@AllArgsConstructor
Expand All @@ -30,7 +30,7 @@ public class ServiceBusClientService {

public void queueMessage(final String topicName, final String targetUrl, final String messageString, final int failureCount) {
final ServiceBusSenderClient serviceBusSenderClient = configService.senderClient(topicName);
final UUID correlationId = UUID.fromString(MDC.get(MDC_CORRELATION_ID));
final UUID correlationId = UUID.fromString(MDC.get(CORRELATION_ID_KEY));
final ServiceBusWrappedMessage wrappedMessage = wrapperMapper.newWrapper(correlationId, failureCount, targetUrl, messageString);
final OffsetDateTime nextTryTime = retryService.getNextTryTime(failureCount);
final ServiceBusMessage serviceBusMessage = mapper.newMessage(jsonMapper.toJson(wrappedMessage), nextTryTime);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import java.util.Map;

import static org.awaitility.Awaitility.await;
import static uk.gov.hmcts.cp.filters.TracingFilter.MDC_CORRELATION_ID;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_KEY;
import static uk.gov.hmcts.cp.servicebus.config.ServiceBusConfigService.PCR_INBOUND_TOPIC;
import static uk.gov.hmcts.cp.servicebus.config.ServiceBusConfigService.PCR_OUTBOUND_TOPIC;

Expand Down Expand Up @@ -85,7 +85,7 @@ public void handleMessage(final String topicName, final ServiceBusReceivedMessag
final ServiceBusWrappedMessage queueMessage = jsonMapper.fromJson(wrappedMessageString, ServiceBusWrappedMessage.class);
log.info("Processing {} with targetUrl:{}", topicName, queueMessage.getTargetUrl());
try {
MDC.put(MDC_CORRELATION_ID, queueMessage.getCorrelationId().toString());
MDC.put(CORRELATION_ID_KEY, queueMessage.getCorrelationId().toString());
serviceBusHandlers.handleMessage(topicName, queueMessage.getTargetUrl(), queueMessage.getMessage());
} catch (Exception exception) {
final int failureCount = queueMessage.getFailureCount() + 1;
Expand All @@ -97,7 +97,7 @@ public void handleMessage(final String topicName, final ServiceBusReceivedMessag
clientService.queueMessage(topicName, queueMessage.getTargetUrl(), queueMessage.getMessage(), failureCount);
// Because we added a new message and swallowed the error then the current message will be dropped
} finally {
MDC.remove(MDC_CORRELATION_ID);
MDC.remove(CORRELATION_ID_KEY);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import java.io.IOException;

import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_HEADER;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_KEY;

@Component
public class OutboundTracingInterceptor implements ClientHttpRequestInterceptor {
Expand All @@ -20,7 +20,7 @@ public ClientHttpResponse intercept(final HttpRequest request,
final ClientHttpRequestExecution execution) throws IOException {
final String correlationId = MDC.get("correlationId");
if (correlationId != null) {
request.getHeaders().set(CORRELATION_ID_HEADER, correlationId);
request.getHeaders().set(CORRELATION_ID_KEY, correlationId);
}
return execution.execute(request, body);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
import java.util.Optional;
import java.util.UUID;

import static uk.gov.hmcts.cp.filters.TracingFilter.MDC_CORRELATION_ID;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_KEY;
import static uk.gov.hmcts.cp.servicebus.config.ServiceBusConfigService.PCR_INBOUND_TOPIC;

/**
Expand Down Expand Up @@ -77,7 +77,7 @@ public ResponseEntity<Void> createNotification(
public ResponseEntity<Resource> getDocument(
@NotNull @PathVariable("clientSubscriptionId") final UUID clientSubscriptionId,
@NotNull @PathVariable("documentId") final UUID documentId,
@RequestHeader(value = MDC_CORRELATION_ID, required = false) final UUID xCorrelationId) {
@RequestHeader(value = CORRELATION_ID_KEY, required = false) final UUID xCorrelationId) {
final UUID clientId = UUID.fromString(MDC.get(ClientIdResolutionFilter.MDC_CLIENT_ID));
final DocumentContent content = notificationManager.getPcrDocumentContent(clientSubscriptionId, clientId, documentId);
final Resource resource = new ByteArrayResource(content.getBody());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import java.util.UUID;

import static uk.gov.hmcts.cp.filters.TracingFilter.MDC_CORRELATION_ID;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_KEY;

@RestController
@RequiredArgsConstructor
Expand All @@ -28,7 +28,7 @@ public class SubscriptionController implements SubscriptionApi {
@Override
public ResponseEntity<ClientSubscription> createClientSubscription(
final ClientSubscriptionRequest clientSubscriptionRequest,
@RequestHeader(value = MDC_CORRELATION_ID, required = false) final UUID xCorrelationId) {
@RequestHeader(value = CORRELATION_ID_KEY, required = false) final UUID xCorrelationId) {
final UUID clientId = UUID.fromString(MDC.get(ClientIdResolutionFilter.MDC_CLIENT_ID));
log.info("createClientSubscription callbackUrl:{} clientId:{}",
Encode.forJava(clientSubscriptionRequest.getNotificationEndpoint().getCallbackUrl()), clientId);
Expand All @@ -41,7 +41,7 @@ public ResponseEntity<ClientSubscription> createClientSubscription(
public ResponseEntity<ClientSubscription> updateClientSubscription(
final UUID clientSubscriptionId,
final ClientSubscriptionRequest clientSubscriptionRequest,
@RequestHeader(value = MDC_CORRELATION_ID, required = false) final UUID xCorrelationId) {
@RequestHeader(value = CORRELATION_ID_KEY, required = false) final UUID xCorrelationId) {
final UUID clientId = UUID.fromString(MDC.get(ClientIdResolutionFilter.MDC_CLIENT_ID));
log.info("updateClientSubscription clientSubscriptionId:{} clientId:{}", clientSubscriptionId, clientId);
final ClientSubscription response = subscriptionService.updateSubscription(
Expand All @@ -52,7 +52,7 @@ public ResponseEntity<ClientSubscription> updateClientSubscription(
@Override
public ResponseEntity<ClientSubscription> getClientSubscription(
final UUID clientSubscriptionId,
@RequestHeader(value = MDC_CORRELATION_ID, required = false) final UUID xCorrelationId) {
@RequestHeader(value = CORRELATION_ID_KEY, required = false) final UUID xCorrelationId) {
final UUID clientId = UUID.fromString(MDC.get(ClientIdResolutionFilter.MDC_CLIENT_ID));
log.info("getClientSubscription clientSubscriptionId:{} clientId:{}", clientSubscriptionId, clientId);
final ClientSubscription response = subscriptionService.getSubscription(clientSubscriptionId, clientId);
Expand All @@ -62,7 +62,7 @@ public ResponseEntity<ClientSubscription> getClientSubscription(
@Override
public ResponseEntity<Void> deleteClientSubscription(
final UUID clientSubscriptionId,
@RequestHeader(value = MDC_CORRELATION_ID, required = false) final UUID xCorrelationId) {
@RequestHeader(value = CORRELATION_ID_KEY, required = false) final UUID xCorrelationId) {
final UUID clientId = UUID.fromString(MDC.get(ClientIdResolutionFilter.MDC_CLIENT_ID));
log.info("deleteClientSubscription clientSubscriptionId:{} clientId:{}", clientSubscriptionId, clientId);
subscriptionService.deleteSubscription(clientSubscriptionId, clientId);
Expand Down
10 changes: 5 additions & 5 deletions src/test/java/uk/gov/hmcts/cp/filters/TracingFilterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,22 +45,22 @@ void shouldAlwaysFilter_all_paths() {
@Test
void doFilterInternal_puts_correlationId_in_MDC_and_response_when_header_present() throws ServletException, IOException {
final String correlationId = UUID.randomUUID().toString();
when(request.getHeader(TracingFilter.CORRELATION_ID_HEADER)).thenReturn(correlationId);
when(request.getHeader(TracingFilter.CORRELATION_ID_KEY)).thenReturn(correlationId);

filter.doFilterInternal(request, response, filterChain);

verify(response).setHeader(TracingFilter.CORRELATION_ID_HEADER, correlationId);
verify(response).setHeader(TracingFilter.CORRELATION_ID_KEY, correlationId);
verify(filterChain).doFilter(request, response);
assertThat(MDC.get(TracingFilter.MDC_CORRELATION_ID)).isNull();
assertThat(MDC.get(TracingFilter.CORRELATION_ID_KEY)).isNull();
}

@Test
void doFilterInternal_generates_correlationId_when_header_absent() throws ServletException, IOException {
when(request.getHeader(TracingFilter.CORRELATION_ID_HEADER)).thenReturn(null);
when(request.getHeader(TracingFilter.CORRELATION_ID_KEY)).thenReturn(null);

filter.doFilterInternal(request, response, filterChain);

verify(response).setHeader(eq(TracingFilter.CORRELATION_ID_HEADER), anyString());
verify(response).setHeader(eq(TracingFilter.CORRELATION_ID_KEY), anyString());
verify(filterChain).doFilter(request, response);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static uk.gov.hmcts.cp.filters.TracingFilter.MDC_CORRELATION_ID;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_KEY;
import static uk.gov.hmcts.cp.openapi.model.EventType.PRISON_COURT_REGISTER_GENERATED;
import static uk.gov.hmcts.cp.servicebus.config.ServiceBusConfigService.PCR_INBOUND_TOPIC;

Expand Down Expand Up @@ -61,7 +61,7 @@ void inbound_notification_should_process_material_service() {
MaterialMetadata materialMetadata = new MaterialMetadata();
when(materialService.waitForMaterialMetadata(materialId)).thenReturn(materialMetadata);
EventPayload eventPayload = EventPayload.builder().eventType(PRISON_COURT_REGISTER_GENERATED).materialId(materialId).build();
MDC.put(MDC_CORRELATION_ID, UUID.randomUUID().toString());
MDC.put(CORRELATION_ID_KEY, UUID.randomUUID().toString());
clientService.queueMessage(PCR_INBOUND_TOPIC, null, jsonMapper.toJson(eventPayload), 0);
MDC.clear();

Expand All @@ -74,7 +74,7 @@ void inbound_notification_should_process_material_service() {
void process_message_should_retry_n_times_then_send_to_DLQ() {
when(materialService.waitForMaterialMetadata(materialId)).thenReturn(null);
EventPayload eventPayload = EventPayload.builder().eventType(PRISON_COURT_REGISTER_GENERATED).materialId(materialId).build();
MDC.put(MDC_CORRELATION_ID, UUID.randomUUID().toString());
MDC.put(CORRELATION_ID_KEY, UUID.randomUUID().toString());
clientService.queueMessage(PCR_INBOUND_TOPIC, null, jsonMapper.toJson(eventPayload), 0);
MDC.clear();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_KEY;
import static uk.gov.hmcts.cp.servicebus.config.ServiceBusConfigService.PCR_INBOUND_TOPIC;

@ExtendWith(MockitoExtension.class)
Expand Down Expand Up @@ -49,7 +50,7 @@ class ServiceBusClientServiceTest {
@Test
void queue_message_should_pass_to_topic() {
UUID correlationId = UUID.randomUUID();
MDC.put("correlationId", correlationId.toString());
MDC.put(CORRELATION_ID_KEY, correlationId.toString());
when(configService.senderClient(PCR_INBOUND_TOPIC)).thenReturn(senderClient);
when(wrapperMapper.newWrapper(correlationId, 1, callbackUrl, "message")).thenReturn(wrappedMessage);
when(jsonMapper.toJson(wrappedMessage)).thenReturn("wrapped-message");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ void intercept_adds_X_Correlation_Id_from_MDC() throws Exception {

interceptor.intercept(request, new byte[0], execution);

assertThat(headers.getFirst(TracingFilter.CORRELATION_ID_HEADER))
assertThat(headers.getFirst(TracingFilter.CORRELATION_ID_KEY))
.isEqualTo(correlationId);
}

Expand All @@ -65,6 +65,6 @@ void intercept_does_not_add_header_when_MDC_correlationId_absent() throws Except

interceptor.intercept(request, new byte[0], execution);

assertThat(request.getHeaders().getFirst(TracingFilter.CORRELATION_ID_HEADER)).isNull();
assertThat(request.getHeaders().getFirst(TracingFilter.CORRELATION_ID_KEY)).isNull();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_KEY;

@Slf4j
class SpringLoggingIntegrationTest extends IntegrationTestBase {
Expand All @@ -26,28 +28,31 @@ void afterEach() {
System.setOut(originalStdOut);
}

UUID correlationId = UUID.randomUUID();

@Test
void springboot_test_should_log_correct_fields() throws IOException {
MDC.put("any-mdc-field", "1234-1234");
MDC.put(CORRELATION_ID_KEY, correlationId.toString());
final ByteArrayOutputStream capturedStdOut = captureStdOut();
log.info("spring boot test message", new RuntimeException("TestException"));

final String logMessage = capturedStdOut.toString(StandardCharsets.UTF_8);
assertThat(logMessage).isNotEmpty();

final Map<String, Object> capturedFields =
new ObjectMapper().readValue(logMessage, new TypeReference<>() { });
new ObjectMapper().readValue(logMessage, new TypeReference<>() {
});

assertThat(capturedFields.get("any-mdc-field")).isEqualTo("1234-1234");
assertThat(capturedFields.get(CORRELATION_ID_KEY)).isEqualTo(correlationId.toString());
assertThat(capturedFields.get("timestamp")).isNotNull();
assertThat(capturedFields.get("logger_name"))
.isEqualTo("uk.gov.hmcts.cp.subscription.integration.controllers.SpringLoggingIntegrationTest");
assertThat(capturedFields.get("thread_name")).isEqualTo("Test worker");
assertThat(capturedFields.get("level")).isEqualTo("INFO");
assertThat(capturedFields.get("message").toString())
.contains("spring boot test message")
.contains("java.lang.RuntimeException: TestException")
.contains("uk.gov.hmcts.cp.subscription.integration.controllers.SpringLoggingIntegrationTest");
assertThat(capturedFields.get("logger_name"))
.isEqualTo("uk.gov.hmcts.cp.subscription.integration.controllers.SpringLoggingIntegrationTest");
assertThat(capturedFields.get("thread_name")).isEqualTo("Test worker");
assertThat(capturedFields.get("level")).isEqualTo("INFO");
}

private ByteArrayOutputStream captureStdOut() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package uk.gov.hmcts.cp.subscription.integration.controllers;

import jakarta.annotation.Resource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -16,7 +15,7 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_HEADER;
import static uk.gov.hmcts.cp.filters.TracingFilter.CORRELATION_ID_KEY;

@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.MOCK,
Expand Down Expand Up @@ -48,11 +47,11 @@ void incomingRequestShouldReturnOk() throws Exception {
@Test
void subscriptionEndpointWithCorrelationIdShouldEchoHeaderInResponse() throws Exception {
MvcResult result = mockMvc.perform(get("/client-subscriptions/{id}", UUID.randomUUID())
.header(CORRELATION_ID_HEADER, TEST_CORRELATION_ID)
.header(CORRELATION_ID_KEY, TEST_CORRELATION_ID)
.header("X-Client-Id", "11111111-2222-3333-4444-555555555555"))
.andReturn();

String responseCorrelationId = result.getResponse().getHeader(CORRELATION_ID_HEADER);
String responseCorrelationId = result.getResponse().getHeader(CORRELATION_ID_KEY);
assertThat(responseCorrelationId).isEqualTo(TEST_CORRELATION_ID);
assertThat(springApplicationName).isEqualTo("cp-crime-hearing-case-event-subscription");
}
Expand Down
Loading
Loading