From 3dcd27d08ae6d4b94b4a3297a2b3385e33ae03f2 Mon Sep 17 00:00:00 2001 From: SlimusMinus Date: Tue, 20 Oct 2026 01:41:03 +0300 Subject: [PATCH] Keep network calls out of post transactions; cache and throttle geocoding - PostService.create/update geocode and upload photos before opening the DB transaction (TransactionTemplate); uploaded files are removed if the transaction fails, so a DB connection is no longer held while waiting for Nominatim or MinIO. - GeocodingService: configurable URL and User-Agent (geocoding.*), results cached in Redis for 30 days by coordinates rounded to ~11 m, and a cluster-wide 1 request/s slot (geo:throttle) as the public Nominatim policy requires; city/district are cut to the column sizes. Co-Authored-By: Claude Opus 5.5 --- .../refound/service/GeocodingService.java | 122 +++++++++++++++- .../krylov/refound/service/PostService.java | 137 +++++++++++------- src/main/resources/application.yaml | 7 + .../refound/service/GeocodingServiceTest.java | 58 ++++++++ 4 files changed, 265 insertions(+), 59 deletions(-) create mode 100644 src/test/java/com/krylov/refound/service/GeocodingServiceTest.java diff --git a/src/main/java/com/krylov/refound/service/GeocodingService.java b/src/main/java/com/krylov/refound/service/GeocodingService.java index 56f7fc6..1a928dd 100644 --- a/src/main/java/com/krylov/refound/service/GeocodingService.java +++ b/src/main/java/com/krylov/refound/service/GeocodingService.java @@ -14,31 +14,74 @@ import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; -import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; +/** + * Город и район по координатам (обратное геокодирование, Nominatim/OSM). + * + * + */ @Component @Slf4j -@RequiredArgsConstructor public class GeocodingService { - private final ObjectMapper mapper; - // Поля address-объекта Nominatim, которые в сумме считаем "городом" (в порядке приоритета) private static final List CITY_FIELDS = List.of("city", "town", "village", "municipality"); + private static final Duration CACHE_TTL = Duration.ofDays(30); + private static final String THROTTLE_KEY = "geo:throttle"; + private static final int THROTTLE_ATTEMPTS = 5; + private static final long THROTTLE_WAIT_MILLIS = 250; + /** Колонки posts.city и posts.district. */ + private static final int CITY_MAX = 100; + private static final int DISTRICT_MAX = 500; + + private final ObjectMapper mapper; + private final StringRedisTemplate redisTemplate; + private final String baseUrl; + private final String userAgent; + private final Duration minInterval; // HttpClient потокобезопасен и предназначен для переиспользования — не создаём его на каждый запрос private final HttpClient httpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(5)) .build(); + public GeocodingService(ObjectMapper mapper, StringRedisTemplate redisTemplate, + @Value("${geocoding.url:https://nominatim.openstreetmap.org}") String baseUrl, + @Value("${geocoding.user-agent:ReFound-backend/1.0}") String userAgent, + @Value("${geocoding.min-interval:PT1S}") Duration minInterval) { + this.mapper = mapper; + this.redisTemplate = redisTemplate; + this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; + this.userAgent = userAgent; + this.minInterval = minInterval; + } + /** * Определяет город и остальную часть адреса по координатам через Nominatim reverse geocoding. */ public AddressInfo getAddress(String lat, String lon) { - String url = "https://nominatim.openstreetmap.org/reverse" + String cacheKey = cacheKey(lat, lon); + AddressInfo cached = readCache(cacheKey); + if (cached != null) { + return cached; + } + + acquireSlot(); + String url = baseUrl + "/reverse" + "?lat=" + encode(lat) + "&lon=" + encode(lon) + "&format=jsonv2" @@ -47,7 +90,8 @@ public class GeocodingService { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .timeout(Duration.ofSeconds(5)) - .header("User-Agent", "MyApp/1.0") + .header("User-Agent", userAgent) + .header("Accept-Language", "ru") .GET() .build(); @@ -67,7 +111,65 @@ public class GeocodingService { throw new ApiException(ErrorCode.INTERNAL_ERROR, "Запрос к сервису геокодирования прерван.", HttpStatus.INTERNAL_SERVER_ERROR); } - return toAddressInfo(root); + AddressInfo result = toAddressInfo(root); + writeCache(cacheKey, result); + return result; + } + + /** Ждёт свободный слот общего лимита запросов к геокодеру. */ + private void acquireSlot() { + for (int attempt = 0; attempt < THROTTLE_ATTEMPTS; attempt++) { + try { + Boolean acquired = redisTemplate.opsForValue().setIfAbsent(THROTTLE_KEY, "1", minInterval); + if (Boolean.TRUE.equals(acquired)) { + return; + } + } catch (RuntimeException e) { + // Без Redis общий лимит не соблюсти — идём без него, это редкий случай + log.debug("Лимит геокодера не проверен: {}", e.getMessage()); + return; + } + try { + Thread.sleep(THROTTLE_WAIT_MILLIS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + } + throw new ApiException(ErrorCode.INTERNAL_ERROR, "Сервис геокодирования перегружен.", HttpStatus.SERVICE_UNAVAILABLE); + } + + static String cacheKey(String lat, String lon) { + return "geo:" + round(lat) + ":" + round(lon); + } + + private static String round(String coordinate) { + try { + return String.format(java.util.Locale.ROOT, "%.4f", Double.parseDouble(coordinate)); + } catch (NumberFormatException e) { + return coordinate; + } + } + + private AddressInfo readCache(String key) { + try { + String json = redisTemplate.opsForValue().get(key); + return json == null ? null : mapper.readValue(json, AddressInfo.class); + } catch (Exception e) { + log.debug("Кэш геокодера недоступен: {}", e.getMessage()); + return null; + } + } + + private void writeCache(String key, AddressInfo info) { + if (info.city() == null) { + return; + } + try { + redisTemplate.opsForValue().set(key, mapper.writeValueAsString(info), CACHE_TTL); + } catch (Exception e) { + log.debug("Не удалось сохранить результат геокодера: {}", e.getMessage()); + } } private AddressInfo toAddressInfo(JsonNode root) { @@ -82,7 +184,11 @@ public class GeocodingService { String district = buildDistrict(displayName, city); - return new AddressInfo(city, district); + return new AddressInfo(truncate(city, CITY_MAX), truncate(district, DISTRICT_MAX)); + } + + private static String truncate(String value, int max) { + return value == null || value.length() <= max ? value : value.substring(0, max); } /** diff --git a/src/main/java/com/krylov/refound/service/PostService.java b/src/main/java/com/krylov/refound/service/PostService.java index 006eb4f..df49691 100644 --- a/src/main/java/com/krylov/refound/service/PostService.java +++ b/src/main/java/com/krylov/refound/service/PostService.java @@ -37,10 +37,12 @@ import org.springframework.data.jpa.domain.Specification; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionTemplate; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import java.time.Duration; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -68,32 +70,45 @@ public class PostService { private final PostCacheService postCacheService; private final PostCacheKeyGenerator postCacheKeyGenerator; private final PostDeletionService postDeletionService; + private final TransactionTemplate transactionTemplate; private final PostSearchService postSearchService; private final SearchSuggestService searchSuggestService; - @Transactional + /** + * Создание объявления. Сетевые вызовы — геокодер и загрузка фото в MinIO — идут + * до транзакции: соединение с БД не держится, пока ждём внешние сервисы. + * Если транзакция не прошла, загруженные файлы удаляются. + */ public PostRequest create(PostRequest request, List images) { - User currentUser = userService.getCurrentUser(); PostFieldLimits.validate(request.getTitle(), request.getAddress(), request.getPhone(), request.getRewardText()); - Post post = mapper.toEntity(request); - post.setCreatedAt(TimeZoneContext.now()); - post.setStatus(PostStatus.MODERATION); - post.setUser(currentUser); - post.setIsReward(request.getReward()); - // Адрес из формы сохраняем как есть; геокодер заполняет только city/district - post.setAddress(normalizeAddress(request.getAddress())); - resolveLocation(post, request.getLatitude(), request.getLongitude(), request.getAddress()); + AddressInfo location = geocode(request.getLatitude(), request.getLongitude()); + List imageKeys = uploadImages(images); - postRepository.save(post); - log.info("Создан пост id={} пользователем userId={}, статус={}", post.getId(), currentUser.getId(), post.getStatus()); + try { + transactionTemplate.executeWithoutResult(status -> { + Post post = mapper.toEntity(request); + post.setCreatedAt(TimeZoneContext.now()); + post.setStatus(PostStatus.MODERATION); + post.setUser(currentUser); + post.setIsReward(request.getReward()); + // Адрес из формы сохраняем как есть; геокодер заполняет только city/district + post.setAddress(normalizeAddress(request.getAddress())); + applyLocation(post, location, request.getAddress()); - int uploaded = attachImages(post, images); - log.info("К посту id={} прикреплено {} изображений", post.getId(), uploaded); + postRepository.save(post); + attachImages(post, imageKeys); + log.info("Создан пост id={} пользователем userId={}, изображений={}", post.getId(), currentUser.getId(), + imageKeys.size()); - statisticsService.incrementCreated(); - postCacheService.invalidatePosts(); + statisticsService.incrementCreated(); + postCacheService.invalidatePosts(); + }); + } catch (RuntimeException e) { + postDeletionService.deleteFilesAfterCommit(imageKeys); + throw e; + } return request; } @@ -196,12 +211,9 @@ public class PostService { } /** - * Удобный overload для контроллера, принимающего multipart-поля по отдельности. - * @Transactional стоит и здесь, и на основном update() — раньше этот метод вызывал - * update(id, request, images, existingUrls) через this, что было self-invocation - * и обходило Spring-прокси: @Transactional на вызываемом методе не срабатывал. + * Правка объявления владельцем; multipart-поля приходят по отдельности. + * Как и при создании, геокодер и загрузка фото выполняются до транзакции. */ - @Transactional public PostResponse update(Long id, String type, String title, String address, Double latitude, Double longitude, String description, String category, String phone, Boolean reward, String rewardText, List images, String existingImagesJson) { @@ -221,11 +233,21 @@ public class PostService { List existingUrls = parseExistingImages(existingImagesJson); - return doUpdate(id, request, images, existingUrls); + // Проверка владельца — до обращения к внешним сервисам и загрузки файлов + findOwnedPost(id); + AddressInfo location = geocode(latitude, longitude); + List imageKeys = uploadImages(images); + + try { + return transactionTemplate.execute(status -> doUpdate(id, request, imageKeys, existingUrls, location)); + } catch (RuntimeException e) { + postDeletionService.deleteFilesAfterCommit(imageKeys); + throw e; + } } - private PostResponse doUpdate(Long id, PostRequest request, List images, List existingUrls) { - // Проверка владельца выполняется до любых изменений и загрузки файлов + private PostResponse doUpdate(Long id, PostRequest request, List imageKeys, List existingUrls, + AddressInfo location) { Post post = findOwnedPost(id); post.setStatus(PostStatus.MODERATION); @@ -244,7 +266,7 @@ public class PostService { post.setLatitude(request.getLatitude()); post.setLongitude(request.getLongitude()); } - resolveLocation(post, request.getLatitude(), request.getLongitude(), request.getAddress()); + applyLocation(post, location, request.getAddress()); List keepUrls = existingUrls != null ? existingUrls : List.of(); @@ -254,7 +276,7 @@ public class PostService { removeImages(post, toRemove); - int uploaded = attachImages(post, images); + int uploaded = attachImages(post, imageKeys); Post updated = postRepository.save(post); log.info("Обновлён пост id={}: удалено изображений={}, добавлено={}, статус={}", id, toRemove.size(), uploaded, updated.getStatus()); @@ -362,29 +384,37 @@ public class PostService { } /** - * Загружает файлы в MinIO и привязывает их к посту. Возвращает количество загруженных файлов. + * Загружает фото в MinIO (вне транзакции). Если какое-то не загрузилось, + * уже загруженные удаляются, и ошибка пробрасывается. */ - private int attachImages(Post post, List images) { + private List uploadImages(List images) { if (images == null || images.isEmpty()) { - return 0; + return List.of(); } - - int count = 0; - for (MultipartFile image : images) { - if (image == null || image.isEmpty()) { - continue; + List keys = new ArrayList<>(); + try { + for (MultipartFile image : images) { + if (image != null && !image.isEmpty()) { + keys.add(fileStorageService.uploadFile(image)); + } } + } catch (RuntimeException e) { + postDeletionService.deleteFilesAfterCommit(keys); + throw e; + } + return keys; + } - String objectKey = fileStorageService.uploadFile(image); - + /** Привязывает загруженные файлы к посту. Возвращает их количество. */ + private int attachImages(Post post, List imageKeys) { + for (String objectKey : imageKeys) { Image img = new Image(); img.setUrl(objectKey); // храним ключ MinIO, а не путь на диске img.setPost(post); imageRepository.save(img); post.getImages().add(img); - count++; } - return count; + return imageKeys.size(); } private void removeImages(Post post, List toRemove) { @@ -395,20 +425,25 @@ public class PostService { /** * Город и район по координатам. Геокодер (Nominatim) — внешний сервис: если он * недоступен, объявление всё равно сохраняется, а городом становится адрес из - * формы. Раньше недоступность Nominatim не давала создать объявление (503). + * формы (applyLocation). Раньше недоступность Nominatim не давала создать объявление. */ - private void resolveLocation(Post post, Double latitude, Double longitude, String address) { - if (latitude != null && longitude != null) { - try { - AddressInfo resolved = geocodingService.getAddress(latitude.toString(), longitude.toString()); - if (StringUtils.hasText(resolved.city())) { - post.setCity(resolved.city()); - post.setDistrict(resolved.district()); - return; - } - } catch (ApiException e) { - log.warn("Геокодинг недоступен, город берём из адреса: postId={}, {}", post.getId(), e.getMessage()); - } + private AddressInfo geocode(Double latitude, Double longitude) { + if (latitude == null || longitude == null) { + return null; + } + try { + return geocodingService.getAddress(latitude.toString(), longitude.toString()); + } catch (ApiException e) { + log.warn("Геокодинг недоступен, город берём из адреса: {}", e.getMessage()); + return null; + } + } + + private static void applyLocation(Post post, AddressInfo location, String address) { + if (location != null && StringUtils.hasText(location.city())) { + post.setCity(location.city()); + post.setDistrict(location.district()); + return; } post.setCity(PostFieldLimits.cityFromAddress(address)); } diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index e196ae5..1bcbef3 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -73,6 +73,13 @@ ai: delay: 500 multiplier: 2 +# Обратное геокодирование (GeocodingService): публичный Nominatim требует +# User-Agent с контактом и не больше 1 запроса/с; для нагрузки — свой экземпляр +geocoding: + url: ${GEOCODING_URL:https://nominatim.openstreetmap.org} + user-agent: ${GEOCODING_USER_AGENT:ReFound-backend/1.0} + min-interval: ${GEOCODING_MIN_INTERVAL:PT1S} + # Поиск по объявлениям (PostSearchService) search: typo-threshold: 0.3 diff --git a/src/test/java/com/krylov/refound/service/GeocodingServiceTest.java b/src/test/java/com/krylov/refound/service/GeocodingServiceTest.java new file mode 100644 index 0000000..3ed340c --- /dev/null +++ b/src/test/java/com/krylov/refound/service/GeocodingServiceTest.java @@ -0,0 +1,58 @@ +package com.krylov.refound.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.krylov.refound.dto.AddressInfo; +import com.krylov.refound.exception.ApiException; +import java.time.Duration; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.http.HttpStatus; + +class GeocodingServiceTest { + + private ValueOperations values; + private GeocodingService service; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + StringRedisTemplate redis = mock(StringRedisTemplate.class); + values = mock(ValueOperations.class); + when(redis.opsForValue()).thenReturn(values); + // Адрес, на котором ничего не слушает: тесты не должны ходить в настоящий Nominatim + service = new GeocodingService(new ObjectMapper(), redis, "http://127.0.0.1:1", "test", Duration.ofSeconds(1)); + } + + @Test + void cachedAddressIsReturnedWithoutHttpCall() { + when(values.get("geo:55.7558:37.6173")).thenReturn("{\"city\":\"Москва\",\"district\":\"Тверской район\"}"); + + AddressInfo info = service.getAddress("55.75580001", "37.61729999"); + + assertThat(info).isEqualTo(new AddressInfo("Москва", "Тверской район")); + } + + @Test + void busyThrottleSlotGives503() { + when(values.setIfAbsent(eq("geo:throttle"), anyString(), any(Duration.class))).thenReturn(false); + + assertThatThrownBy(() -> service.getAddress("55.0", "37.0")) + .isInstanceOfSatisfying(ApiException.class, + e -> assertThat(e.getStatus()).isEqualTo(HttpStatus.SERVICE_UNAVAILABLE)); + } + + @Test + void coordinatesAreRoundedForCacheKey() { + assertThat(GeocodingService.cacheKey("55.123456", "-37.1")).isEqualTo("geo:55.1235:-37.1000"); + } +}