package com.krylov.refound.service; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.krylov.refound.dto.AddressInfo; import com.krylov.refound.enums.ErrorCode; import com.krylov.refound.exception.ApiException; import java.io.IOException; import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.List; 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 public class GeocodingService { // Поля 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 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" + "&addressdetails=1"; HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .timeout(Duration.ofSeconds(5)) .header("User-Agent", userAgent) .header("Accept-Language", "ru") .GET() .build(); JsonNode root; try { HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { log.warn("Nominatim вернул статус {} для lat={}, lon={}", response.statusCode(), lat, lon); throw new ApiException(ErrorCode.INTERNAL_ERROR, "Сервис геокодирования недоступен.", HttpStatus.SERVICE_UNAVAILABLE); } root = mapper.readTree(response.body()); } catch (IOException e) { log.error("Ошибка при обращении к Nominatim: {}", e.getMessage(), e); throw new ApiException(ErrorCode.INTERNAL_ERROR, "Сервис геокодирования недоступен.", HttpStatus.SERVICE_UNAVAILABLE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ApiException(ErrorCode.INTERNAL_ERROR, "Запрос к сервису геокодирования прерван.", HttpStatus.INTERNAL_SERVER_ERROR); } 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) { JsonNode address = root.path("address"); String displayName = root.path("display_name").asText(""); String city = CITY_FIELDS.stream() .map(field -> address.path(field).asText(null)) .filter(value -> value != null && !value.isBlank()) .findFirst() .orElse(null); String district = buildDistrict(displayName, city); 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); } /** * display_name — это склеенные через запятую компоненты адреса от самого точного к самому общему. * Убираем из этого списка компонент, совпавший с городом, и склеиваем остальное обратно. */ private String buildDistrict(String displayName, String city) { if (displayName.isBlank()) { return null; } String[] parts = displayName.split(","); StringBuilder result = new StringBuilder(); boolean cityRemoved = false; for (String part : parts) { String trimmed = part.trim(); if (!cityRemoved && trimmed.equalsIgnoreCase(city)) { cityRemoved = true; continue; } if (!result.isEmpty()) { result.append(", "); } result.append(trimmed); } return result.isEmpty() ? null : result.toString(); } private String encode(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); } }