package com.trafficaudit.ledgeraudit.route; import com.fasterxml.jackson.databind.JsonNode; import com.trafficaudit.ledgeraudit.config.LedgerAuditProperties; import com.trafficaudit.ledgeraudit.dto.LedgerAuditResponse; import com.trafficaudit.ledgeraudit.model.LedgerLocation; import lombok.extern.slf4j.Slf4j; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; import java.net.URI; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; @Slf4j public class DefaultRouteDistanceProvider implements RouteDistanceProvider { private static final String DISCLAIMER = "\u5730\u56fe\u9a7e\u8f66\u53c2\u8003\u91cc\u7a0b\uff0c\u4e0d\u8003\u8651\u8d27\u8f66\u9650\u9ad8\u9650\u91cd\u9650\u884c\uff0c\u4e0d\u4f5c\u4e3a\u6267\u6cd5\u8ba4\u5b9a\u4f9d\u636e\uff1b\u591a\u62a5\u5468\u8f6c\u91cf\u6309\u5730\u56fe\u6d4b\u7b97\u5468\u8f6c\u91cf\u00d71.3\u4ee5\u4e0a\u7684\u8d85\u51fa\u90e8\u5206\u6d4b\u7b97"; private final LedgerAuditProperties.MapProperties properties; private final RestTemplate restTemplate; private final String mode; private final String geocoder; private final ConcurrentHashMap geocodeCache = new ConcurrentHashMap<>(); private final ConcurrentHashMap routeCache = new ConcurrentHashMap<>(); private final AtomicInteger networkFailures = new AtomicInteger(); private final Object nominatimRateLock = new Object(); private long lastNominatimRequestAt; private volatile String disabledReason; public DefaultRouteDistanceProvider(LedgerAuditProperties.MapProperties properties) { this.properties = properties; this.mode = resolveMode(properties); this.geocoder = resolveGeocoder(properties); SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setConnectTimeout(Math.max(1000, properties.getTimeoutMs())); factory.setReadTimeout(Math.max(1000, properties.getTimeoutMs())); this.restTemplate = new RestTemplate(factory); } @Override public LedgerAuditResponse.MapProviderInfo status() { LedgerAuditResponse.MapProviderInfo info = new LedgerAuditResponse.MapProviderInfo(); info.setCode(mode.toLowerCase(Locale.ROOT)); info.setLabel(labelOf(mode)); info.setConfigured(isConfigured()); if (!isConfigured()) { info.setMessage("\u672a\u914d\u7f6e\u5730\u56fe\u670d\u52a1\u5bc6\u94a5\u6216\u5730\u5740\uff0c\u8def\u7ebf\u8fd0\u8ddd\u5c06\u6807\u8bb0\u4e3a\u65e0\u6cd5\u6838\u67e5"); } else if (disabledReason != null) { info.setMessage(disabledReason); } else { info.setMessage("\u8def\u7ebf\u8fd0\u8ddd\u6309\u666e\u901a\u9a7e\u8f66\u8def\u7ebf\u8ba1\u7b97\uff1b" + DISCLAIMER); } return info; } @Override public RouteMeasureResult measure(LedgerLocation start, LedgerLocation end) { if (!isConfigured()) { return RouteMeasureResult.unavailable(mode.toLowerCase(Locale.ROOT), "\u5730\u56fe\u8def\u7ebf\u670d\u52a1\u672a\u914d\u7f6e"); } if (disabledReason != null) { return RouteMeasureResult.unavailable(mode.toLowerCase(Locale.ROOT), disabledReason); } String cacheKey = routeKey(start, end); RouteMeasureResult cached = routeCache.get(cacheKey); if (cached != null) return cached; try { GeoPoint from = geocode(start, false); GeoPoint to = geocode(end, true); double distanceKm = routeDistance(from, to); RouteMeasureResult result = RouteMeasureResult.ok(distanceKm, mode.toLowerCase(Locale.ROOT)); routeCache.put(cacheKey, result); networkFailures.set(0); return result; } catch (NoResultException e) { RouteMeasureResult result = RouteMeasureResult.unavailable(mode.toLowerCase(Locale.ROOT), e.getMessage()); routeCache.put(cacheKey, result); return result; } catch (Exception e) { int failures = networkFailures.incrementAndGet(); log.warn("ledger map route lookup failed, mode={}, failures={}", mode, failures, e); if (failures >= 3) { disabledReason = "\u5730\u56fe\u670d\u52a1\u8fde\u7eed\u8c03\u7528\u5931\u8d25\uff0c\u672c\u6b21\u5269\u4f59\u8def\u7ebf\u5df2\u505c\u6b62\u8c03\u7528"; } return RouteMeasureResult.unavailable(mode.toLowerCase(Locale.ROOT), "\u5730\u56fe\u8def\u7ebf\u67e5\u8be2\u5931\u8d25\uff1a" + safeMessage(e)); } } private boolean isConfigured() { if ("AMAP".equals(mode)) return hasText(properties.getAmapKey()); if ("BAIDU".equals(mode)) return hasText(properties.getBaiduAk()); if ("OSRM".equals(mode)) { return hasText(properties.getOsrmBaseUrl()) && hasGeocoder(); } return false; } private boolean hasGeocoder() { if ("AMAP".equals(geocoder)) return hasText(properties.getAmapKey()); if ("BAIDU".equals(geocoder)) return hasText(properties.getBaiduAk()); if ("NOMINATIM".equals(geocoder)) return hasText(properties.getNominatimBaseUrl()); return false; } private GeoPoint geocode(LedgerLocation location, boolean destination) throws Exception { String address = location == null ? "" : location.toSearchAddress(); if (!hasText(address)) throw new NoResultException(destination ? "\u7ec8\u70b9\u5730\u5740\u4e3a\u7a7a" : "\u8d77\u70b9\u5730\u5740\u4e3a\u7a7a"); String key = geocoder + "|" + address; GeoPoint cached = geocodeCache.get(key); if (cached != null) return cached; GeoPoint point; if ("BAIDU".equals(geocoder)) { point = geocodeBaidu(address, location.getCity()); } else if ("NOMINATIM".equals(geocoder)) { point = geocodeNominatim(address); } else { point = geocodeAmap(address, location.getCity()); } geocodeCache.put(key, point); return point; } private GeoPoint geocodeAmap(String address, String city) throws Exception { URI uri = UriComponentsBuilder.fromHttpUrl("https://restapi.amap.com/v3/geocode/geo") .queryParam("key", properties.getAmapKey()) .queryParam("address", address) .queryParam("city", city == null ? "" : city) .build().encode().toUri(); JsonNode root = restTemplate.getForObject(uri, JsonNode.class); if (root == null || !"1".equals(root.path("status").asText())) { throw new NoResultException("\u9ad8\u5fb7\u5730\u7406\u7f16\u7801\u65e0\u7ed3\u679c\uff1a" + address); } JsonNode geocodes = root.path("geocodes"); if (!geocodes.isArray() || geocodes.size() == 0) { throw new NoResultException("\u9ad8\u5fb7\u5730\u7406\u7f16\u7801\u65e0\u7ed3\u679c\uff1a" + address); } String[] parts = geocodes.get(0).path("location").asText("").split(","); if (parts.length != 2) throw new NoResultException("\u9ad8\u5fb7\u5730\u7406\u7f16\u7801\u5750\u6807\u65e0\u6548\uff1a" + address); return new GeoPoint(Double.parseDouble(parts[1]), Double.parseDouble(parts[0])); } private GeoPoint geocodeBaidu(String address, String city) throws Exception { URI uri = UriComponentsBuilder.fromHttpUrl("https://api.map.baidu.com/geocoding/v3/") .queryParam("address", address) .queryParam("city", city == null ? "" : city) .queryParam("output", "json") .queryParam("ak", properties.getBaiduAk()) .build().encode().toUri(); JsonNode root = restTemplate.getForObject(uri, JsonNode.class); if (root == null || root.path("status").asInt(-1) != 0) { throw new NoResultException("\u767e\u5ea6\u5730\u7406\u7f16\u7801\u65e0\u7ed3\u679c\uff1a" + address); } JsonNode location = root.path("result").path("location"); if (!location.has("lng") || !location.has("lat")) { throw new NoResultException("\u767e\u5ea6\u5730\u7406\u7f16\u7801\u5750\u6807\u65e0\u6548\uff1a" + address); } return new GeoPoint(location.path("lat").asDouble(), location.path("lng").asDouble()); } private GeoPoint geocodeNominatim(String address) throws Exception { throttleNominatim(); String base = properties.getNominatimBaseUrl().replaceAll("/+$", ""); URI uri = UriComponentsBuilder.fromHttpUrl(base + "/search") .queryParam("q", address) .queryParam("format", "jsonv2") .queryParam("limit", 1) .queryParam("countrycodes", "cn") .queryParam("accept-language", "zh-CN") .build().encode().toUri(); HttpHeaders headers = new HttpHeaders(); headers.set(HttpHeaders.USER_AGENT, properties.getNominatimUserAgent()); ResponseEntity response = restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<>(headers), JsonNode.class); JsonNode root = response.getBody(); if (root == null || !root.isArray() || root.size() == 0) { throw new NoResultException("Nominatim geocoding returned no result: " + address); } JsonNode first = root.get(0); if (!first.hasNonNull("lat") || !first.hasNonNull("lon")) { throw new NoResultException("Nominatim geocoding returned an invalid coordinate: " + address); } return new GeoPoint(first.path("lat").asDouble(), first.path("lon").asDouble()); } private void throttleNominatim() throws InterruptedException { long interval = Math.max(0, properties.getNominatimMinIntervalMs()); if (interval == 0) return; synchronized (nominatimRateLock) { long waitMs = lastNominatimRequestAt + interval - System.currentTimeMillis(); if (waitMs > 0) Thread.sleep(waitMs); lastNominatimRequestAt = System.currentTimeMillis(); } } private double routeDistance(GeoPoint from, GeoPoint to) throws Exception { if ("AMAP".equals(mode)) return amapDrivingDistance(from, to); if ("BAIDU".equals(mode)) return baiduDrivingDistance(from, to); return osrmDrivingDistance(from, to); } private double amapDrivingDistance(GeoPoint from, GeoPoint to) throws Exception { URI uri = UriComponentsBuilder.fromHttpUrl("https://restapi.amap.com/v3/direction/driving") .queryParam("key", properties.getAmapKey()) .queryParam("origin", from.lng + "," + from.lat) .queryParam("destination", to.lng + "," + to.lat) .queryParam("extensions", "base") .queryParam("strategy", 0) .build().encode().toUri(); JsonNode root = restTemplate.getForObject(uri, JsonNode.class); if (root == null || !"1".equals(root.path("status").asText())) { throw new Exception("\u9ad8\u5fb7\u8def\u7ebf\u8ba1\u7b97\u65e0\u7ed3\u679c"); } JsonNode paths = root.path("route").path("paths"); if (!paths.isArray() || paths.size() == 0) throw new Exception("\u9ad8\u5fb7\u8def\u7ebf\u8ba1\u7b97\u65e0\u7ed3\u679c"); return paths.get(0).path("distance").asDouble() / 1000d; } private double baiduDrivingDistance(GeoPoint from, GeoPoint to) throws Exception { URI uri = UriComponentsBuilder.fromHttpUrl("https://api.map.baidu.com/directionlite/v1/driving") .queryParam("origin", from.lat + "," + from.lng) .queryParam("destination", to.lat + "," + to.lng) .queryParam("ak", properties.getBaiduAk()) .build().encode().toUri(); JsonNode root = restTemplate.getForObject(uri, JsonNode.class); if (root == null || root.path("status").asInt(-1) != 0) { throw new Exception("\u767e\u5ea6\u8def\u7ebf\u8ba1\u7b97\u65e0\u7ed3\u679c"); } JsonNode routes = root.path("result").path("routes"); if (!routes.isArray() || routes.size() == 0) throw new Exception("\u767e\u5ea6\u8def\u7ebf\u8ba1\u7b97\u65e0\u7ed3\u679c"); return routes.get(0).path("distance").asDouble() / 1000d; } private double osrmDrivingDistance(GeoPoint from, GeoPoint to) throws Exception { String base = properties.getOsrmBaseUrl().replaceAll("/+$", ""); String coords = from.lng + "," + from.lat + ";" + to.lng + "," + to.lat; URI uri = UriComponentsBuilder.fromHttpUrl(base + "/route/v1/driving/" + coords) .queryParam("overview", "false") .queryParam("alternatives", "false") .queryParam("steps", "false") .build().encode().toUri(); JsonNode root = restTemplate.getForObject(uri, JsonNode.class); if (root == null || !"Ok".equals(root.path("code").asText())) { throw new Exception("OSRM \u8def\u7ebf\u8ba1\u7b97\u65e0\u7ed3\u679c"); } JsonNode routes = root.path("routes"); if (!routes.isArray() || routes.size() == 0) throw new Exception("OSRM \u8def\u7ebf\u8ba1\u7b97\u65e0\u7ed3\u679c"); return routes.get(0).path("distance").asDouble() / 1000d; } private String routeKey(LedgerLocation start, LedgerLocation end) { return geocoder + "|" + mode + "|" + start.toSearchAddress() + "|" + end.toSearchAddress(); } private static String resolveMode(LedgerAuditProperties.MapProperties p) { String requested = normalize(p.getProvider()); if ("amap".equals(requested)) return "AMAP"; if ("baidu".equals(requested)) return "BAIDU"; if ("osrm".equals(requested)) return "OSRM"; if (!"auto".equals(requested) && !requested.isEmpty()) return "NONE"; if (hasText(p.getAmapKey())) return "AMAP"; if (hasText(p.getBaiduAk())) return "BAIDU"; return "NONE"; } private static String resolveGeocoder(LedgerAuditProperties.MapProperties p) { String requested = normalize(p.getGeocoder()); if ("amap".equals(requested)) return "AMAP"; if ("baidu".equals(requested)) return "BAIDU"; if ("nominatim".equals(requested)) return "NOMINATIM"; if (hasText(p.getAmapKey())) return "AMAP"; if (hasText(p.getBaiduAk())) return "BAIDU"; return "NONE"; } private static String labelOf(String mode) { if ("AMAP".equals(mode)) return "\u9ad8\u5fb7\u666e\u901a\u9a7e\u8f66\u8def\u7ebf"; if ("BAIDU".equals(mode)) return "\u767e\u5ea6\u666e\u901a\u9a7e\u8f66\u8def\u7ebf"; if ("OSRM".equals(mode)) return "OSRM \u81ea\u5efa\u8def\u7ebf"; return "\u672a\u914d\u7f6e"; } private static String normalize(String value) { return value == null ? "" : value.trim().toLowerCase(Locale.ROOT); } private static boolean hasText(String value) { return value != null && !value.trim().isEmpty(); } private static String safeMessage(Exception e) { String message = e.getMessage(); if (message == null || message.trim().isEmpty()) return e.getClass().getSimpleName(); return message.length() > 160 ? message.substring(0, 160) : message; } private static class GeoPoint { private final double lat; private final double lng; private GeoPoint(double lat, double lng) { this.lat = lat; this.lng = lng; } } private static class NoResultException extends Exception { private NoResultException(String message) { super(message); } } }