261008_01_ENH: 외부 API 및 bypass 원본 오류 응답 전파 기능 추가
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
package com.kri.common.autoconfigure.http;
|
||||
|
||||
import com.kri.common.runtime.web.ExternalApiResponseAdvice;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
@AutoConfiguration
|
||||
@ConditionalOnClass(name = {
|
||||
"jakarta.servlet.http.HttpServletRequest",
|
||||
"org.springframework.web.servlet.DispatcherServlet"
|
||||
})
|
||||
@ConditionalOnProperty(prefix = "kri.web", name = "enabled", havingValue = "true", matchIfMissing = true)
|
||||
public class ExternalApiErrorAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(value = ExternalApiResponseAdvice.class, name = "externalApiResponseAdvice")
|
||||
public ExternalApiResponseAdvice externalApiResponseAdvice() {
|
||||
return new ExternalApiResponseAdvice();
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ public class BypassProperties {
|
||||
private String stripPrefix;
|
||||
private List<String> allowedPaths = new ArrayList<>();
|
||||
private Duration requestTimeout;
|
||||
private boolean throwOnError = false;
|
||||
private List<String> requestCustomizers = new ArrayList<>();
|
||||
private List<String> responseCustomizers = new ArrayList<>();
|
||||
}
|
||||
|
||||
@@ -89,8 +89,8 @@ public class ExternalApiClient {
|
||||
}
|
||||
|
||||
HttpRequest request = builder.build();
|
||||
HttpResponse<String> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
|
||||
HttpResponse<byte[]> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
|
||||
return ExternalApiResponse.ofBytes(resp.statusCode(), resp.headers(), resp.body());
|
||||
} catch (IOException | InterruptedException e) {
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
@@ -114,8 +114,8 @@ public class ExternalApiClient {
|
||||
builder.header("Content-Type", "multipart/form-data; boundary=" + boundary);
|
||||
|
||||
HttpRequest request = builder.build();
|
||||
HttpResponse<String> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body());
|
||||
HttpResponse<byte[]> resp = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray());
|
||||
return ExternalApiResponse.ofBytes(resp.statusCode(), resp.headers(), resp.body());
|
||||
} catch (IOException | InterruptedException e) {
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
|
||||
@@ -1,28 +1,89 @@
|
||||
package com.kri.common.feature.http;
|
||||
|
||||
import java.net.http.HttpHeaders;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 외부 API 호출 결과를 단순하게 담는 DTO.
|
||||
*/
|
||||
public class ExternalApiResponse {
|
||||
|
||||
private static final Pattern CONTENT_TYPE_PARAMETER =
|
||||
Pattern.compile("(?:^|;)\\s*([^;=\\s]+)\\s*=\\s*(?:\"((?:\\\\.|[^\"\\\\])*+)\"|([^;\"\\s]+))\\s*(?=;|$)");
|
||||
|
||||
private final int statusCode;
|
||||
private final Map<String, List<String>> headers;
|
||||
private final String body;
|
||||
private final byte[] bodyBytes;
|
||||
|
||||
public ExternalApiResponse(int statusCode, Map<String, List<String>> headers, String body) {
|
||||
this(statusCode, headers, body,
|
||||
body == null ? new byte[0] : body.getBytes(resolveCharset(headers)));
|
||||
}
|
||||
|
||||
private ExternalApiResponse(int statusCode, Map<String, List<String>> headers,
|
||||
String body, byte[] bodyBytes) {
|
||||
this.statusCode = statusCode;
|
||||
this.headers = headers;
|
||||
this.body = body;
|
||||
this.bodyBytes = bodyBytes.clone();
|
||||
}
|
||||
|
||||
public static ExternalApiResponse of(int status, HttpHeaders headers, String body) {
|
||||
return new ExternalApiResponse(status, headers.map(), body);
|
||||
}
|
||||
|
||||
/** Preserve the received bytes while keeping the existing decoded string API. */
|
||||
public static ExternalApiResponse ofBytes(int status, HttpHeaders headers, byte[] body) {
|
||||
byte[] bytes = body == null ? new byte[0] : body;
|
||||
return new ExternalApiResponse(status, headers.map(),
|
||||
new String(bytes, resolveCharset(headers.map())), bytes);
|
||||
}
|
||||
|
||||
/** Return this response for 2xx, or throw with the original upstream response. */
|
||||
public ExternalApiResponse requireSuccess() {
|
||||
if (statusCode < 200 || statusCode >= 300) {
|
||||
throw new ExternalApiResponseException(statusCode, headers, bodyBytes);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public byte[] getBodyBytes() {
|
||||
return bodyBytes.clone();
|
||||
}
|
||||
|
||||
private static Charset resolveCharset(Map<String, List<String>> headers) {
|
||||
if (headers != null) {
|
||||
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
|
||||
if (entry.getKey() != null && entry.getKey().equalsIgnoreCase("Content-Type")
|
||||
&& entry.getValue() != null && !entry.getValue().isEmpty() && entry.getValue().get(0) != null) {
|
||||
// Consume each complete parameter so quoted values cannot introduce a fake charset.
|
||||
Matcher matcher = CONTENT_TYPE_PARAMETER.matcher(entry.getValue().get(0));
|
||||
while (matcher.find()) {
|
||||
if (!matcher.group(1).equalsIgnoreCase("charset")) {
|
||||
continue;
|
||||
}
|
||||
String charset = matcher.group(2) == null ? matcher.group(3)
|
||||
: matcher.group(2).replaceAll("\\\\(.)", "$1");
|
||||
try {
|
||||
return Charset.forName(charset);
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// Match the JDK string body handler's UTF-8 fallback for an unknown charset.
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.kri.common.feature.http;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** An upstream HTTP error whose response can be relayed without rewriting its body. */
|
||||
public class ExternalApiResponseException extends RuntimeException {
|
||||
|
||||
private final int statusCode;
|
||||
private final Map<String, List<String>> headers;
|
||||
private final byte[] body;
|
||||
|
||||
public ExternalApiResponseException(int statusCode, Map<String, List<String>> headers, byte[] body) {
|
||||
super("External API returned HTTP " + statusCode);
|
||||
this.statusCode = statusCode;
|
||||
Map<String, List<String>> copy = new LinkedHashMap<>();
|
||||
if (headers != null) {
|
||||
headers.forEach((name, values) -> {
|
||||
if (name != null && values != null) {
|
||||
copy.put(name, List.copyOf(values));
|
||||
}
|
||||
});
|
||||
}
|
||||
this.headers = Collections.unmodifiableMap(copy);
|
||||
this.body = body == null ? new byte[0] : body.clone();
|
||||
}
|
||||
|
||||
public int getStatusCode() {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
public Map<String, List<String>> getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
|
||||
public byte[] getBody() {
|
||||
return body.clone();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.kri.common.feature.http.bypass;
|
||||
|
||||
import com.kri.common.feature.http.ExternalApiResponseException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
@@ -43,6 +44,14 @@ public class BypassResponse {
|
||||
return statusCode;
|
||||
}
|
||||
|
||||
/** Return this response for 2xx, or throw with the original upstream response. */
|
||||
public BypassResponse requireSuccess() {
|
||||
if (statusCode < 200 || statusCode >= 300) {
|
||||
throw new ExternalApiResponseException(statusCode, headers, body);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
public Map<String, List<String>> headers() {
|
||||
return headers;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.kri.common.runtime.http.bypass;
|
||||
|
||||
import com.kri.common.autoconfigure.http.bypass.BypassProperties;
|
||||
import com.kri.common.feature.http.ExternalApiResponseException;
|
||||
import com.kri.common.feature.http.bypass.BypassClient;
|
||||
import com.kri.common.feature.http.bypass.BypassContext;
|
||||
import com.kri.common.feature.http.bypass.BypassForwardOptions;
|
||||
@@ -94,7 +95,11 @@ public class DefaultBypassClient implements BypassClient {
|
||||
bypassRequest = applyRequestCustomizers(bypassRequest, context, targetProperties, effectiveOptions);
|
||||
|
||||
BypassResponse bypassResponse = send(target, targetProperties, bypassRequest);
|
||||
return applyResponseCustomizers(bypassResponse, context, targetProperties, effectiveOptions);
|
||||
bypassResponse = applyResponseCustomizers(bypassResponse, context, targetProperties, effectiveOptions);
|
||||
if (targetProperties.isThrowOnError()) {
|
||||
bypassResponse.requireSuccess();
|
||||
}
|
||||
return bypassResponse;
|
||||
}
|
||||
|
||||
private BypassProperties.Target resolveTargetProperties(String targetName) {
|
||||
@@ -253,6 +258,8 @@ public class DefaultBypassClient implements BypassClient {
|
||||
try {
|
||||
BypassResponse result = customizer.customize(response, context);
|
||||
return result == null ? response : result;
|
||||
} catch (ExternalApiResponseException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw BusinessException.internalError("BYPASS_RESPONSE_CUSTOMIZE_FAILED",
|
||||
"Bypass response customize failed.").with("target", context.targetName());
|
||||
@@ -385,7 +392,8 @@ public class DefaultBypassClient implements BypassClient {
|
||||
}
|
||||
|
||||
private static boolean isHopByHopHeader(String name) {
|
||||
return name != null && HOP_BY_HOP_HEADERS.contains(name.toLowerCase(Locale.ROOT));
|
||||
return name != null && (name.startsWith(":")
|
||||
|| HOP_BY_HOP_HEADERS.contains(name.toLowerCase(Locale.ROOT)));
|
||||
}
|
||||
|
||||
private static List<String> nullToEmpty(List<String> values) {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.kri.common.runtime.web;
|
||||
|
||||
import com.kri.common.feature.http.ExternalApiResponseException;
|
||||
import java.util.List;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
@RestControllerAdvice
|
||||
public class ExternalApiResponseAdvice {
|
||||
|
||||
@ExceptionHandler(ExternalApiResponseException.class)
|
||||
public ResponseEntity<byte[]> handleExternalApiResponse(ExternalApiResponseException exception) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
// Forward representation headers only; transport and authentication headers stay upstream.
|
||||
for (String name : List.of(HttpHeaders.CONTENT_TYPE, HttpHeaders.CONTENT_ENCODING)) {
|
||||
exception.getHeaders().entrySet().stream()
|
||||
.filter(entry -> entry.getKey().equalsIgnoreCase(name))
|
||||
.findFirst()
|
||||
.ifPresent(entry -> headers.put(name, entry.getValue()));
|
||||
}
|
||||
return ResponseEntity.status(exception.getStatusCode())
|
||||
.headers(headers)
|
||||
.body(exception.getBody());
|
||||
}
|
||||
}
|
||||
@@ -10,3 +10,4 @@ com.kri.common.autoconfigure.redis.CommonRedisAutoConfiguration
|
||||
com.kri.common.autoconfigure.scheduling.CommonSchedulingAutoConfiguration
|
||||
com.kri.common.autoconfigure.http.bypass.BypassAutoConfiguration
|
||||
com.kri.common.autoconfigure.crypto.CryptoAutoConfiguration
|
||||
com.kri.common.autoconfigure.http.ExternalApiErrorAutoConfiguration
|
||||
|
||||
Reference in New Issue
Block a user