Merge pull request #50 from SlimusMinus/fix-ai_timeout
All checks were successful
deploy-backend / deploy (push) Successful in 1m29s

fixed ai image timeout
This commit is contained in:
SlimusMinus
2026-10-15 00:49:40 +03:00
committed by GitHub
8 changed files with 218 additions and 20 deletions

View File

@@ -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;
}
}

View File

@@ -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;
}
}
}

View File

@@ -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> R post(String uri, MultipartFile file, Class<R> 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;
}
}
}

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -19,4 +19,10 @@ public class AiProperties {
* 10 seconds
*/
private int timeout;
/**
* Таймаут ответа для модерации изображений, секунды. Картинки AI-сервис
* обрабатывает заметно дольше текста, особенно первую после простоя.
*/
private int imageTimeout = 30;
}

View File

@@ -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

View File

@@ -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});
}
}