fixed ai image timeout

This commit is contained in:
SlimusMinus
2026-10-15 00:48:58 +03:00
parent 13bb0c8503
commit c83d41a036
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