mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 22:11:36 -05:00
feat(elbv2): ALB Lambda target type (#730)
* feat(elbv2): add Lambda target type support for ALB forwarding
This commit is contained in:
1 parent
e402c6ec18
commit
86eac926f9
8 files changed
+345
-4
No files matched your search
@@ -1,5 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.elbv2;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Action;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.Listener;
|
||||
@@ -7,7 +9,11 @@ import io.github.hectorvent.floci.services.elbv2.model.Rule;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.RuleCondition;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetDescription;
|
||||
import io.github.hectorvent.floci.services.elbv2.model.TargetGroup;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.HttpClientOptions;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
@@ -19,7 +25,10 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
@@ -49,6 +58,12 @@ public class ElbV2DataPlane {
|
||||
@Inject
|
||||
EmulatorConfig config;
|
||||
|
||||
@Inject
|
||||
LambdaService lambdaService;
|
||||
|
||||
@Inject
|
||||
ObjectMapper objectMapper;
|
||||
|
||||
private final Map<String, HttpServer> servers = new ConcurrentHashMap<>();
|
||||
private final Map<String, AtomicReference<List<CompiledRule>>> ruleChains = new ConcurrentHashMap<>();
|
||||
private final Map<String, AtomicInteger> rrCounters = new ConcurrentHashMap<>();
|
||||
@@ -152,6 +167,18 @@ public class ElbV2DataPlane {
|
||||
req.response().setStatusCode(502).end("Target group not found");
|
||||
return;
|
||||
}
|
||||
|
||||
if ("lambda".equals(tg.getTargetType())) {
|
||||
List<TargetDescription> targets = tg.getTargets();
|
||||
if (targets.isEmpty()) {
|
||||
req.response().setStatusCode(503).end("No Lambda targets registered");
|
||||
return;
|
||||
}
|
||||
String functionArn = targets.get(0).getId();
|
||||
invokeLambdaTarget(req, functionArn, region);
|
||||
return;
|
||||
}
|
||||
|
||||
List<TargetDescription> allTargets = tg.getTargets();
|
||||
List<TargetDescription> healthy = allTargets.stream()
|
||||
.filter(t -> healthChecker.isHealthy(tgArn, t, ElbV2HealthChecker.effectivePort(t, tg)))
|
||||
@@ -168,6 +195,118 @@ public class ElbV2DataPlane {
|
||||
proxyRequest(req, target.getId(), targetPort);
|
||||
}
|
||||
|
||||
private void invokeLambdaTarget(io.vertx.core.http.HttpServerRequest req, String functionArn, String region) {
|
||||
req.bodyHandler(body -> {
|
||||
try {
|
||||
Map<String, Object> event = buildAlbEvent(req, body);
|
||||
byte[] payload = objectMapper.writeValueAsBytes(event);
|
||||
InvokeResult result = lambdaService.invoke(region, functionArn, payload, InvocationType.RequestResponse);
|
||||
|
||||
if (result.getFunctionError() != null) {
|
||||
req.response().setStatusCode(502).end("Lambda function error: " + result.getFunctionError());
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.getPayload() == null || result.getPayload().length == 0) {
|
||||
req.response().setStatusCode(200).end();
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, Object> lambdaResp = objectMapper.readValue(result.getPayload(),
|
||||
new TypeReference<Map<String, Object>>() {});
|
||||
|
||||
int statusCode = 200;
|
||||
Object sc = lambdaResp.get("statusCode");
|
||||
if (sc != null) {
|
||||
statusCode = ((Number) sc).intValue();
|
||||
}
|
||||
|
||||
req.response().setStatusCode(statusCode);
|
||||
|
||||
Object headers = lambdaResp.get("headers");
|
||||
if (headers instanceof Map<?, ?> headerMap) {
|
||||
for (Map.Entry<?, ?> entry : headerMap.entrySet()) {
|
||||
req.response().putHeader(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
|
||||
}
|
||||
}
|
||||
|
||||
Object multiValueHeaders = lambdaResp.get("multiValueHeaders");
|
||||
if (multiValueHeaders instanceof Map<?, ?> mvh) {
|
||||
for (Map.Entry<?, ?> entry : mvh.entrySet()) {
|
||||
if (entry.getValue() instanceof List<?> values) {
|
||||
for (Object v : values) {
|
||||
req.response().putHeader(String.valueOf(entry.getKey()), String.valueOf(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Object responseBody = lambdaResp.get("body");
|
||||
Boolean isBase64 = (Boolean) lambdaResp.get("isBase64Encoded");
|
||||
if (responseBody == null) {
|
||||
req.response().end();
|
||||
} else if (Boolean.TRUE.equals(isBase64)) {
|
||||
byte[] decoded = Base64.getDecoder().decode(String.valueOf(responseBody));
|
||||
req.response().end(Buffer.buffer(decoded));
|
||||
} else {
|
||||
req.response().end(String.valueOf(responseBody));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.errorf(e, "Error invoking Lambda target %s", functionArn);
|
||||
req.response().setStatusCode(502).end("Lambda invocation error");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Map<String, Object> buildAlbEvent(io.vertx.core.http.HttpServerRequest req, Buffer body) {
|
||||
Map<String, Object> event = new HashMap<>();
|
||||
event.put("requestContext", Map.of("elb", Map.of("targetGroupArn", "")));
|
||||
event.put("httpMethod", req.method().name());
|
||||
event.put("path", req.path() != null ? req.path() : "/");
|
||||
|
||||
Map<String, String> queryParams = new HashMap<>();
|
||||
Map<String, List<String>> multiValueQueryParams = new HashMap<>();
|
||||
String query = req.query();
|
||||
if (query != null && !query.isEmpty()) {
|
||||
for (String pair : query.split("&")) {
|
||||
int eq = pair.indexOf('=');
|
||||
String key = eq >= 0 ? pair.substring(0, eq) : pair;
|
||||
String val = eq >= 0 ? pair.substring(eq + 1) : "";
|
||||
queryParams.putIfAbsent(key, val);
|
||||
multiValueQueryParams.computeIfAbsent(key, k -> new ArrayList<>()).add(val);
|
||||
}
|
||||
}
|
||||
event.put("queryStringParameters", queryParams.isEmpty() ? null : queryParams);
|
||||
event.put("multiValueQueryStringParameters", multiValueQueryParams.isEmpty() ? null : multiValueQueryParams);
|
||||
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
Map<String, List<String>> multiValueHeaders = new HashMap<>();
|
||||
req.headers().forEach(entry -> {
|
||||
String key = entry.getKey().toLowerCase();
|
||||
headers.putIfAbsent(key, entry.getValue());
|
||||
multiValueHeaders.computeIfAbsent(key, k -> new ArrayList<>()).add(entry.getValue());
|
||||
});
|
||||
event.put("headers", headers);
|
||||
event.put("multiValueHeaders", multiValueHeaders);
|
||||
|
||||
boolean isBase64 = false;
|
||||
String bodyStr = null;
|
||||
if (body != null && body.length() > 0) {
|
||||
String contentType = req.getHeader("Content-Type");
|
||||
if (contentType != null && !contentType.startsWith("text/") && !contentType.contains("json")
|
||||
&& !contentType.contains("xml") && !contentType.contains("form")) {
|
||||
bodyStr = Base64.getEncoder().encodeToString(body.getBytes());
|
||||
isBase64 = true;
|
||||
} else {
|
||||
bodyStr = body.toString(StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
event.put("body", bodyStr);
|
||||
event.put("isBase64Encoded", isBase64);
|
||||
|
||||
return event;
|
||||
}
|
||||
|
||||
private String resolveTgArn(Action action) {
|
||||
if (action.getTargetGroupArn() != null) {
|
||||
return action.getTargetGroupArn();
|
||||
|
||||
@@ -49,6 +49,9 @@ public class ElbV2HealthChecker {
|
||||
if (config.services().elbv2().mock()) {
|
||||
return;
|
||||
}
|
||||
if ("lambda".equals(tg.getTargetType())) {
|
||||
return;
|
||||
}
|
||||
String tgArn = tg.getTargetGroupArn();
|
||||
states.computeIfAbsent(tgArn, k -> new ConcurrentHashMap<>());
|
||||
|
||||
|
||||
@@ -562,9 +562,15 @@ public class ElbV2Service {
|
||||
List<TargetDescription> candidates = filterTargets != null && !filterTargets.isEmpty()
|
||||
? filterTargets : tg.getTargets();
|
||||
|
||||
boolean isLambdaTg = "lambda".equals(tg.getTargetType());
|
||||
return candidates.stream().map(t -> {
|
||||
TargetHealth th = new TargetHealth();
|
||||
th.setTarget(t);
|
||||
if (isLambdaTg) {
|
||||
th.setHealthCheckPort("N/A");
|
||||
th.setState("healthy");
|
||||
return th;
|
||||
}
|
||||
int port = ElbV2HealthChecker.effectivePort(t, tg);
|
||||
th.setHealthCheckPort(String.valueOf(port));
|
||||
String state = healthChecker.getState(tgArn, t.getId(), port);
|
||||
|
||||
Reference in new issue
Block a user