Skip to content

Commit 5ce19a6

Browse files
committed
fixes #90 Update router middleware to call getFinalizedRequest to complete the request chain
1 parent caf7085 commit 5ce19a6

File tree

3 files changed

+61
-9
lines changed

3 files changed

+61
-9
lines changed

src/main/java/com/networknt/aws/lambda/handler/middleware/metrics/APMMetricsMiddleware.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,12 +83,12 @@ public Status execute(LightLambdaExchange exchange) {
8383

8484
exchange.addResponseCompleteListener(finalExchange -> {
8585
Map<String, Object> auditInfo = (Map<String, Object>)finalExchange.getAttachment(AUDIT_ATTACHMENT_KEY);
86-
if(logger.isTraceEnabled()) logger.trace("auditInfo = " + auditInfo);
86+
if(logger.isTraceEnabled()) logger.trace("auditInfo = {}", auditInfo);
8787
if (auditInfo != null && !auditInfo.isEmpty()) {
8888
Map<String, String> tags = new HashMap<>();
8989
tags.put("endpoint", (String) auditInfo.get(Constants.ENDPOINT_STRING));
9090
String clientId = auditInfo.get(Constants.CLIENT_ID_STRING) != null ? (String) auditInfo.get(Constants.CLIENT_ID_STRING) : "unknown";
91-
if(logger.isTraceEnabled()) logger.trace("clientId = " + clientId);
91+
if(logger.isTraceEnabled()) logger.trace("clientId = {}", clientId);
9292
tags.put("clientId", clientId);
9393
// scope client id will only be available if two token is used. For example, authorization code flow.
9494
if (config.isSendScopeClientId()) {
@@ -120,7 +120,8 @@ public Status execute(LightLambdaExchange exchange) {
120120
metricName = metricName.tagged(tags);
121121
long time = Clock.defaultClock().getTick() - startTime;
122122
registry.getOrAdd(metricName, MetricRegistry.MetricBuilder.TIMERS).update(time, TimeUnit.NANOSECONDS);
123-
if(logger.isTraceEnabled()) logger.trace("metricName = " + metricName + " commonTags = " + JsonMapper.toJson(commonTags) + " tags = " + JsonMapper.toJson(tags));
123+
if(logger.isTraceEnabled())
124+
logger.trace("metricName = {} commonTags = {} tags = {}", metricName, JsonMapper.toJson(commonTags), JsonMapper.toJson(tags));
124125
incCounterForStatusCode(finalExchange.getFinalizedResponse(true).getStatusCode(), commonTags, tags);
125126
} else {
126127
// when we reach here, it will be in light-gateway so no specification is loaded on the server and also the security verification is failed.

src/main/java/com/networknt/aws/lambda/handler/middleware/router/LambdaRouterMiddleware.java

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.networknt.aws.lambda.handler.middleware.router;
22

3+
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
34
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
45
import com.networknt.aws.lambda.LightLambdaExchange;
56
import com.networknt.aws.lambda.handler.Handler;
@@ -63,11 +64,13 @@ public Status execute(LightLambdaExchange exchange) {
6364
return this.successMiddlewareStatus();
6465
} else {
6566
if (!exchange.hasFailedState()) {
67+
// get the finalized request to trigger the state change for the request complete.
68+
APIGatewayProxyRequestEvent requestEvent = exchange.getFinalizedRequest(false);
6669
/* invoke http service */
6770
String serviceId = serviceIdOptional.get();
68-
var originalPath = exchange.getRequest().getPath();
71+
var originalPath = requestEvent.getPath();
6972
var targetPath = originalPath;
70-
var method = exchange.getRequest().getHttpMethod().toLowerCase();
73+
var method = requestEvent.getHttpMethod().toLowerCase();
7174
LOG.debug("Request path: {} -- Request method: {} -- Start time: {}", originalPath, method, System.currentTimeMillis());
7275
// lookup the host from the serviceId
7376
String host = cluster.serviceToUrl(protocol, serviceId, null, null);
@@ -89,8 +92,8 @@ public Status execute(LightLambdaExchange exchange) {
8992
if("get".equalsIgnoreCase(method) || "delete".equalsIgnoreCase(method)) {
9093
HttpClientRequest request = new HttpClientRequest();
9194
try {
92-
HttpRequest.Builder builder = request.initBuilder(host + targetPath, HttpMethod.valueOf(exchange.getRequest().getHttpMethod()));
93-
exchange.getRequest().getHeaders().forEach(builder::header);
95+
HttpRequest.Builder builder = request.initBuilder(host + targetPath, HttpMethod.valueOf(requestEvent.getHttpMethod()));
96+
requestEvent.getHeaders().forEach(builder::header);
9497
builder.timeout(Duration.ofMillis(CONFIG.getMaxRequestTime()));
9598
HttpResponse<String> response = (HttpResponse<String>) request.send(builder, HttpResponse.BodyHandlers.ofString());
9699
APIGatewayProxyResponseEvent res = new APIGatewayProxyResponseEvent()
@@ -113,8 +116,8 @@ public Status execute(LightLambdaExchange exchange) {
113116
} else if("post".equalsIgnoreCase(method) || "put".equalsIgnoreCase(method) || "patch".equalsIgnoreCase(method)) {
114117
HttpClientRequest request = new HttpClientRequest();
115118
try {
116-
HttpRequest.Builder builder = request.initBuilder(host + targetPath, HttpMethod.valueOf(exchange.getRequest().getHttpMethod()), Optional.of(exchange.getRequest().getBody()));
117-
exchange.getRequest().getHeaders().forEach(builder::header);
119+
HttpRequest.Builder builder = request.initBuilder(host + targetPath, HttpMethod.valueOf(requestEvent.getHttpMethod()), Optional.of(requestEvent.getBody()));
120+
requestEvent.getHeaders().forEach(builder::header);
118121
builder.timeout(Duration.ofMillis(CONFIG.getMaxRequestTime()));
119122
HttpResponse<String> response = (HttpResponse<String>) request.send(builder, HttpResponse.BodyHandlers.ofString());
120123
APIGatewayProxyResponseEvent res = new APIGatewayProxyResponseEvent()

src/test/java/com/networknt/aws/lambda/LightLambdaExchangeTest.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,4 +126,52 @@ void exchangeCompleteListener() {
126126
Assertions.assertNotNull(exchange.getAttachment(TEST_ATTACHMENT));
127127
}
128128

129+
@Test
130+
public void testExchangeState() {
131+
var apiGatewayProxyRequestEvent = TestUtils.createTestRequestEvent();
132+
apiGatewayProxyRequestEvent.setPath("/v1/pets");
133+
Map<String, String> headerMap = new HashMap<>();
134+
headerMap.put("x-Traceability-id", "abc");
135+
apiGatewayProxyRequestEvent.setHeaders(headerMap);
136+
// set request body
137+
apiGatewayProxyRequestEvent.setBody("{\"id\": 1, \"name\": \"dog\"}");
138+
InvocationResponse invocation = InvocationResponse.builder()
139+
.requestId("12345")
140+
.event(apiGatewayProxyRequestEvent)
141+
.build();
142+
APIGatewayProxyRequestEvent requestEvent = invocation.getEvent();
143+
Context lambdaContext = new LambdaContext(invocation.getRequestId());
144+
145+
var testAsynchronousMiddleware = new TestAsynchronousMiddleware();
146+
var testInvocationHandler = new TestInvocationHandler();
147+
148+
Chain requestChain = new Chain(false);
149+
150+
requestChain.addChainable(testAsynchronousMiddleware);
151+
requestChain.addChainable(testAsynchronousMiddleware);
152+
requestChain.addChainable(testAsynchronousMiddleware);
153+
requestChain.addChainable(testInvocationHandler);
154+
requestChain.addChainable(testAsynchronousMiddleware);
155+
requestChain.addChainable(testAsynchronousMiddleware);
156+
requestChain.addChainable(testAsynchronousMiddleware);
157+
requestChain.setupGroupedChain();
158+
159+
LightLambdaExchange exchange = new LightLambdaExchange(lambdaContext, requestChain);
160+
161+
/* Request should NOT be in progress without setting the initial request data. */
162+
Assertions.assertFalse(exchange.isRequestInProgress());
163+
164+
165+
/* Request should be in progress with the initial request data set. */
166+
exchange.setInitialRequest(requestEvent);
167+
Assertions.assertTrue(exchange.isRequestInProgress());
168+
exchange.getFinalizedRequest(false);
169+
// set the response
170+
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();
171+
response.setStatusCode(200);
172+
exchange.setInitialResponse(response);
173+
Assertions.assertEquals(22, exchange.getState());
174+
Assertions.assertTrue(exchange.isRequestComplete());
175+
176+
}
129177
}

0 commit comments

Comments
 (0)