xyc
2 小时以前 5b41c8896ef7850be2672e45b69bb58e149729ec
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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<String, GeoPoint> geocodeCache = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, RouteMeasureResult> 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<JsonNode> 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); }
    }
}