diff --git a/src/main/java/com/krylov/refound/ai/client/AiClientErrors.java b/src/main/java/com/krylov/refound/ai/client/AiClientErrors.java new file mode 100644 index 0000000..a3cf1e6 --- /dev/null +++ b/src/main/java/com/krylov/refound/ai/client/AiClientErrors.java @@ -0,0 +1,38 @@ +package com.krylov.refound.ai.client; + +import com.krylov.refound.ai.exception.AiException; +import com.krylov.refound.ai.exception.AiTimeoutException; +import com.krylov.refound.ai.exception.AiUnavailableException; +import java.util.concurrent.TimeoutException; + +/** + * Перевод ошибок WebClient в исключения AI-клиента. + */ +final class AiClientErrors { + + private AiClientErrors() { + } + + /** + * Ошибки статуса (onStatus) уже пришли как AiException — их не трогаем. + * Таймаут ответа → AiTimeoutException, прочие сетевые ошибки → AiUnavailableException. + */ + static AiException translate(Exception ex) { + if (ex instanceof AiException aiException) { + return aiException; + } + if (isTimeout(ex)) { + return new AiTimeoutException(ex); + } + return new AiUnavailableException(ex); + } + + static boolean isTimeout(Throwable ex) { + for (Throwable t = ex; t != null; t = t.getCause()) { + if (t instanceof io.netty.handler.timeout.TimeoutException || t instanceof TimeoutException) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/com/krylov/refound/ai/client/AiHttpClient.java b/src/main/java/com/krylov/refound/ai/client/AiHttpClient.java index eab9bb4..1e45783 100644 --- a/src/main/java/com/krylov/refound/ai/client/AiHttpClient.java +++ b/src/main/java/com/krylov/refound/ai/client/AiHttpClient.java @@ -1,14 +1,15 @@ package com.krylov.refound.ai.client; import com.krylov.refound.ai.exception.AiBadRequestException; +import com.krylov.refound.ai.exception.AiException; import com.krylov.refound.ai.exception.AiServerException; +import com.krylov.refound.ai.exception.AiTimeoutException; import com.krylov.refound.ai.exception.AiUnavailableException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatusCode; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.client.WebClient; -import org.springframework.web.reactive.function.client.WebClientRequestException; @Slf4j @Component @@ -39,13 +40,16 @@ public class AiHttpClient { log.info("AI response received"); return response; - } catch (WebClientRequestException ex) { - log.error("AI connection failed", ex); - throw new AiUnavailableException(ex); - } catch (Exception ex) { - log.error("AI request failed", ex); - throw new AiUnavailableException(ex); + AiException error = AiClientErrors.translate(ex); + if (error instanceof AiTimeoutException) { + log.warn("AI text moderation did not respond in time"); + } else if (error instanceof AiUnavailableException) { + log.warn("AI text moderation is unavailable: {}", ex.getMessage()); + } else { + log.warn("AI text moderation returned an error: {}", error.getMessage()); + } + throw error; } } } diff --git a/src/main/java/com/krylov/refound/ai/client/AiMultipartHttpClient.java b/src/main/java/com/krylov/refound/ai/client/AiMultipartHttpClient.java index 9a8d7b6..3127183 100644 --- a/src/main/java/com/krylov/refound/ai/client/AiMultipartHttpClient.java +++ b/src/main/java/com/krylov/refound/ai/client/AiMultipartHttpClient.java @@ -1,8 +1,13 @@ package com.krylov.refound.ai.client; +import com.krylov.refound.ai.config.AiProperties; import com.krylov.refound.ai.exception.AiBadRequestException; +import com.krylov.refound.ai.exception.AiException; import com.krylov.refound.ai.exception.AiServerException; +import com.krylov.refound.ai.exception.AiTimeoutException; import com.krylov.refound.ai.exception.AiUnavailableException; +import java.io.IOException; +import java.time.Duration; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.ByteArrayResource; @@ -12,19 +17,28 @@ import org.springframework.http.client.MultipartBodyBuilder; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.reactive.function.client.WebClient; -import org.springframework.web.reactive.function.client.WebClientRequestException; +import reactor.netty.http.client.HttpClientRequest; @Slf4j @Component @RequiredArgsConstructor public class AiMultipartHttpClient { private final WebClient aiWebClient; + private final AiProperties properties; public R post(String uri, MultipartFile file, Class responseType) { log.info("AI IMAGE POST {}", uri); + byte[] bytes; + try { + bytes = file.getBytes(); + } catch (IOException ex) { + throw new IllegalStateException("Cannot read image for AI moderation", ex); + } + + Duration timeout = Duration.ofSeconds(properties.getImageTimeout()); try { MultipartBodyBuilder builder = new MultipartBodyBuilder(); - builder.part("file", new ByteArrayResource(file.getBytes()) { + builder.part("file", new ByteArrayResource(bytes) { @Override public String getFilename() { return file.getOriginalFilename(); @@ -36,6 +50,8 @@ public class AiMultipartHttpClient { .uri(uri) .contentType(MediaType.MULTIPART_FORM_DATA) .bodyValue(builder.build()) + // Картинки обрабатываются дольше текста — свой таймаут ответа + .httpRequest(req -> ((HttpClientRequest) req.getNativeRequest()).responseTimeout(timeout)) .retrieve() .onStatus( HttpStatusCode::is4xxClientError, @@ -51,12 +67,16 @@ public class AiMultipartHttpClient { .block(); log.info("AI image response received"); return response; - } catch (WebClientRequestException ex) { - log.error("WebClientRequestException in AiMultipartHttpClient {}", ex.getMessage(), ex); - throw new AiUnavailableException(ex); } catch (Exception ex) { - log.error("Exception in AiMultipartHttpClient {}", ex.getMessage(), ex); - throw new RuntimeException("Cannot send image to AI", ex); + AiException error = AiClientErrors.translate(ex); + if (error instanceof AiTimeoutException) { + log.warn("AI image moderation did not respond within {}s", timeout.toSeconds()); + } else if (error instanceof AiUnavailableException) { + log.warn("AI image moderation is unavailable: {}", ex.getMessage()); + } else { + log.warn("AI image moderation returned an error: {}", error.getMessage()); + } + throw error; } } } diff --git a/src/main/java/com/krylov/refound/ai/client/ImageModerationClient.java b/src/main/java/com/krylov/refound/ai/client/ImageModerationClient.java index 38179c4..015c7c6 100644 --- a/src/main/java/com/krylov/refound/ai/client/ImageModerationClient.java +++ b/src/main/java/com/krylov/refound/ai/client/ImageModerationClient.java @@ -2,6 +2,7 @@ package com.krylov.refound.ai.client; import com.krylov.refound.ai.dto.ImageModerationResponse; import com.krylov.refound.ai.exception.AiServerException; +import com.krylov.refound.ai.exception.AiTimeoutException; import com.krylov.refound.ai.exception.AiUnavailableException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -18,7 +19,7 @@ public class ImageModerationClient { private final AiMultipartHttpClient client; @Retryable( - retryFor = {AiUnavailableException.class, AiServerException.class}, + retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class}, maxAttempts = 3, backoff = @Backoff(delay = 500, multiplier = 2) ) @@ -27,16 +28,25 @@ public class ImageModerationClient { return client.post("/api/v1/moderation/image", file, ImageModerationResponse.class); } + // После исчерпания попыток возвращаем null: пост остаётся на модерации и + // проверяется снова при следующем запуске планировщика. @Recover public ImageModerationResponse recover(AiUnavailableException e, MultipartFile file) { - log.error("AI ImageModeration unavailable after retries", e); + log.error("AI ImageModeration unavailable after retries: {}", e.getCause() != null ? e.getCause().getMessage() : e.getMessage()); + + return null; + } + + @Recover + public ImageModerationResponse recover(AiTimeoutException e, MultipartFile file) { + log.error("AI ImageModeration timed out after retries"); return null; } @Recover public ImageModerationResponse recover(AiServerException e, MultipartFile file) { - log.error("AI ImageModeration server error after retries", e); + log.error("AI ImageModeration server error after retries: {}", e.getMessage()); return null; } diff --git a/src/main/java/com/krylov/refound/ai/client/TextModerationClient.java b/src/main/java/com/krylov/refound/ai/client/TextModerationClient.java index 1462b68..2a84529 100644 --- a/src/main/java/com/krylov/refound/ai/client/TextModerationClient.java +++ b/src/main/java/com/krylov/refound/ai/client/TextModerationClient.java @@ -3,6 +3,7 @@ package com.krylov.refound.ai.client; import com.krylov.refound.ai.dto.ModerationResponse; import com.krylov.refound.ai.dto.TextModerationRequest; import com.krylov.refound.ai.exception.AiServerException; +import com.krylov.refound.ai.exception.AiTimeoutException; import com.krylov.refound.ai.exception.AiUnavailableException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -19,7 +20,7 @@ public class TextModerationClient { private final AiHttpClient client; @Retryable( - retryFor = {AiUnavailableException.class, AiServerException.class}, + retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class}, maxAttempts = 3, backoff = @Backoff(delay = 500, multiplier = 2) ) @@ -28,16 +29,25 @@ public class TextModerationClient { return client.post("/api/v1/moderation/text", new TextModerationRequest(text), ModerationResponse.class); } + // После исчерпания попыток возвращаем null: пост остаётся на модерации и + // проверяется снова при следующем запуске планировщика. @Recover public ModerationResponse recover(AiUnavailableException e, String text) { - log.error("AI TextModeration unavailable after retries", e); + log.error("AI TextModeration unavailable after retries: {}", e.getCause() != null ? e.getCause().getMessage() : e.getMessage()); + + return null; + } + + @Recover + public ModerationResponse recover(AiTimeoutException e, String text) { + log.error("AI TextModeration timed out after retries"); return null; } @Recover public ModerationResponse recover(AiServerException e, String text) { - log.error("AI TextModeration server error after retries", e); + log.error("AI TextModeration server error after retries: {}", e.getMessage()); return null; } diff --git a/src/main/java/com/krylov/refound/ai/config/AiProperties.java b/src/main/java/com/krylov/refound/ai/config/AiProperties.java index e4ac2e5..6600915 100644 --- a/src/main/java/com/krylov/refound/ai/config/AiProperties.java +++ b/src/main/java/com/krylov/refound/ai/config/AiProperties.java @@ -19,4 +19,10 @@ public class AiProperties { * 10 seconds */ private int timeout; + + /** + * Таймаут ответа для модерации изображений, секунды. Картинки AI-сервис + * обрабатывает заметно дольше текста, особенно первую после простоя. + */ + private int imageTimeout = 30; } diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index e94f03d..08bcf50 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -49,6 +49,7 @@ minio: ai: url: ${AI_SERVICE_URL:http://localhost:8000} timeout: 10 + image-timeout: ${AI_IMAGE_TIMEOUT:30} retry: max-attempts: 3 delay: 500 diff --git a/src/test/java/com/krylov/refound/ai/client/AiMultipartHttpClientTest.java b/src/test/java/com/krylov/refound/ai/client/AiMultipartHttpClientTest.java new file mode 100644 index 0000000..3b114b4 --- /dev/null +++ b/src/test/java/com/krylov/refound/ai/client/AiMultipartHttpClientTest.java @@ -0,0 +1,109 @@ +package com.krylov.refound.ai.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.krylov.refound.ai.config.AiProperties; +import com.krylov.refound.ai.config.WebClientConfig; +import com.krylov.refound.ai.exception.AiServerException; +import com.krylov.refound.ai.exception.AiTimeoutException; +import com.krylov.refound.ai.exception.AiUnavailableException; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.mock.web.MockMultipartFile; + +class AiMultipartHttpClientTest { + + private static final String URI = "/api/v1/moderation/image"; + + private HttpServer server; + + @AfterEach + void stopServer() { + if (server != null) { + server.stop(0); + } + } + + @Test + void returnsResponseWhenServiceAnswersInTime() throws IOException { + startServer(0, 200, "{\"approved\":true}"); + + Map response = client(baseUrl(), 2).post(URI, image(), Map.class); + + assertThat(response.get("approved")).isEqualTo(true); + } + + @Test + void slowResponseBecomesTimeoutException() throws IOException { + startServer(2500, 200, "{\"approved\":true}"); + + assertThatThrownBy(() -> client(baseUrl(), 1).post(URI, image(), Map.class)) + .isInstanceOf(AiTimeoutException.class); + } + + @Test + void serverErrorIsNotWrappedSoItCanBeRetried() throws IOException { + startServer(0, 500, "boom"); + + assertThatThrownBy(() -> client(baseUrl(), 2).post(URI, image(), Map.class)) + .isInstanceOf(AiServerException.class); + } + + @Test + void refusedConnectionBecomesUnavailableException() throws IOException { + int freePort; + try (ServerSocket socket = new ServerSocket(0)) { + freePort = socket.getLocalPort(); + } + + assertThatThrownBy(() -> client("http://localhost:" + freePort, 2).post(URI, image(), Map.class)) + .isInstanceOf(AiUnavailableException.class); + } + + private void startServer(long delayMs, int status, String body) throws IOException { + server = HttpServer.create(new InetSocketAddress("localhost", 0), 0); + server.createContext(URI, exchange -> { + exchange.getRequestBody().readAllBytes(); + try { + Thread.sleep(delayMs); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + try { + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } catch (IOException ignored) { + // клиент уже закрыл соединение по таймауту + } + }); + server.start(); + } + + private String baseUrl() { + return "http://localhost:" + server.getAddress().getPort(); + } + + private static AiMultipartHttpClient client(String url, int imageTimeoutSeconds) { + AiProperties properties = new AiProperties(); + properties.setUrl(url); + properties.setTimeout(10); + properties.setImageTimeout(imageTimeoutSeconds); + return new AiMultipartHttpClient(new WebClientConfig().aiWebClient(properties), properties); + } + + private static MockMultipartFile image() { + return new MockMultipartFile("file", "photo.jpg", "image/jpeg", new byte[] {1, 2, 3}); + } +}