Junjie
22 小时以前 ef776e9fd5e4f64e4ad09a3faa12fb7bb646c79c
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package com.zy.core.thread.impl.v5;
 
import com.alibaba.fastjson.JSON;
import com.core.common.Cools;
import com.zy.common.utils.RedisUtil;
import com.zy.core.enums.RedisKeyType;
import com.zy.core.model.command.StationCommand;
import com.zy.core.service.StationTaskLoopService;
import lombok.Data;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
public class StationV5RunBlockReroutePlanner {
 
    private static final int RUN_BLOCK_REROUTE_STATE_EXPIRE_SECONDS = 60 * 60 * 24;
    private static final int SHORT_PATH_REPEAT_AVOID_THRESHOLD = 2;
 
    private final RedisUtil redisUtil;
 
    public StationV5RunBlockReroutePlanner(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }
 
    public PlanResult plan(Integer taskNo,
                           Integer blockStationId,
                           StationTaskLoopService.LoopEvaluation loopEvaluation,
                           List<StationCommand> candidateCommands) {
        RunBlockRerouteState rerouteState = loadRunBlockRerouteState(taskNo, blockStationId);
        rerouteState.setTaskNo(taskNo);
        rerouteState.setBlockStationId(blockStationId);
        rerouteState.setPlanCount((rerouteState.getPlanCount() == null ? 0 : rerouteState.getPlanCount()) + 1);
 
        StationCommand rerouteCommand = selectAvailableRerouteCommand(rerouteState, loopEvaluation, candidateCommands);
        if (rerouteCommand == null && candidateCommands != null && !candidateCommands.isEmpty()) {
            rerouteState.resetIssuedRoutes();
            rerouteCommand = selectAvailableRerouteCommand(rerouteState, loopEvaluation, candidateCommands);
        }
 
        saveRunBlockRerouteState(rerouteState);
        return new PlanResult(
                rerouteCommand,
                rerouteState.getPlanCount() == null ? 0 : rerouteState.getPlanCount(),
                copyRoutePathList(rerouteState.getIssuedRoutePathList())
        );
    }
 
    private StationCommand selectAvailableRerouteCommand(RunBlockRerouteState rerouteState,
                                                         StationTaskLoopService.LoopEvaluation loopEvaluation,
                                                         List<StationCommand> candidateCommands) {
        if (rerouteState == null || candidateCommands == null || candidateCommands.isEmpty()) {
            return null;
        }
 
        Set<String> issuedRouteSignatureSet = rerouteState.getIssuedRouteSignatureSet();
        StationTaskLoopService.LoopIdentitySnapshot loopIdentity = loopEvaluation == null
                ? StationTaskLoopService.LoopIdentitySnapshot.empty()
                : loopEvaluation.getLoopIdentity();
        if (loopIdentity == null) {
            loopIdentity = StationTaskLoopService.LoopIdentitySnapshot.empty();
        }
 
        List<RerouteCandidateCommand> candidateCommandList = new ArrayList<>();
        for (StationCommand candidateCommand : candidateCommands) {
            if (candidateCommand == null || candidateCommand.getNavigatePath() == null || candidateCommand.getNavigatePath().isEmpty()) {
                continue;
            }
            String routeSignature = buildPathSignature(candidateCommand.getNavigatePath());
            if (Cools.isEmpty(routeSignature)) {
                continue;
            }
            RerouteCandidateCommand rerouteCandidateCommand = new RerouteCandidateCommand();
            rerouteCandidateCommand.setCommand(candidateCommand);
            rerouteCandidateCommand.setRouteSignature(routeSignature);
            rerouteCandidateCommand.setPathLength(candidateCommand.getNavigatePath().size());
            rerouteCandidateCommand.setIssuedCount(rerouteState.getRouteIssueCountMap().getOrDefault(routeSignature, 0));
            rerouteCandidateCommand.setLoopFingerprint(loopIdentity.getLoopFingerprint());
            rerouteCandidateCommand.setLoopTriggered(loopEvaluation != null && loopEvaluation.isLargeLoopTriggered());
            rerouteCandidateCommand.setCurrentLoopHitCount(countCurrentLoopStationHit(
                    candidateCommand.getNavigatePath(),
                    loopIdentity.getStationIdSet()
            ));
            candidateCommandList.add(rerouteCandidateCommand);
        }
        if (candidateCommandList.isEmpty()) {
            return null;
        }
 
        List<RerouteCandidateCommand> orderedCandidateCommandList = reorderCandidateCommandsForLoopRelease(candidateCommandList);
        for (RerouteCandidateCommand candidateCommand : orderedCandidateCommandList) {
            if (candidateCommand == null || candidateCommand.getCommand() == null) {
                continue;
            }
            if (issuedRouteSignatureSet.contains(candidateCommand.getRouteSignature())) {
                continue;
            }
 
            StationCommand rerouteCommand = candidateCommand.getCommand();
            issuedRouteSignatureSet.add(candidateCommand.getRouteSignature());
            rerouteState.getIssuedRoutePathList().add(new ArrayList<>(rerouteCommand.getNavigatePath()));
            rerouteState.setLastSelectedRoute(new ArrayList<>(rerouteCommand.getNavigatePath()));
            rerouteState.getRouteIssueCountMap().put(
                    candidateCommand.getRouteSignature(),
                    rerouteState.getRouteIssueCountMap().getOrDefault(candidateCommand.getRouteSignature(), 0) + 1
            );
            return rerouteCommand;
        }
        return null;
    }
 
    private List<RerouteCandidateCommand> reorderCandidateCommandsForLoopRelease(List<RerouteCandidateCommand> candidateCommandList) {
        if (candidateCommandList == null || candidateCommandList.isEmpty()) {
            return new ArrayList<>();
        }
 
        int shortestPathLength = Integer.MAX_VALUE;
        int shortestPathLoopHitCount = Integer.MAX_VALUE;
        boolean shortestPathOverused = false;
        boolean currentLoopOverused = false;
        boolean hasLongerCandidate = false;
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand == null || candidateCommand.getPathLength() == null || candidateCommand.getPathLength() <= 0) {
                continue;
            }
            shortestPathLength = Math.min(shortestPathLength, candidateCommand.getPathLength());
        }
        if (shortestPathLength == Integer.MAX_VALUE) {
            return candidateCommandList;
        }
 
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand == null || candidateCommand.getPathLength() == null || candidateCommand.getPathLength() <= 0) {
                continue;
            }
            if (candidateCommand.getPathLength() == shortestPathLength) {
                shortestPathLoopHitCount = Math.min(shortestPathLoopHitCount, safeInt(candidateCommand.getCurrentLoopHitCount()));
            }
            if (candidateCommand.getPathLength() > shortestPathLength) {
                hasLongerCandidate = true;
            }
            if (candidateCommand.getPathLength() == shortestPathLength
                    && candidateCommand.getIssuedCount() != null
                    && candidateCommand.getIssuedCount() >= SHORT_PATH_REPEAT_AVOID_THRESHOLD) {
                shortestPathOverused = true;
            }
            if (!Cools.isEmpty(candidateCommand.getLoopFingerprint())
                    && Boolean.TRUE.equals(candidateCommand.getLoopTriggered())) {
                currentLoopOverused = true;
            }
        }
        if (!shortestPathOverused && !currentLoopOverused) {
            return candidateCommandList;
        }
        if (shortestPathLoopHitCount == Integer.MAX_VALUE) {
            shortestPathLoopHitCount = 0;
        }
 
        boolean hasLoopExitCandidate = false;
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand == null) {
                continue;
            }
            if (safeInt(candidateCommand.getCurrentLoopHitCount()) < shortestPathLoopHitCount) {
                hasLoopExitCandidate = true;
                break;
            }
        }
        if (!hasLongerCandidate && !hasLoopExitCandidate) {
            return candidateCommandList;
        }
 
        List<RerouteCandidateCommand> reorderedList = new ArrayList<>();
        if (currentLoopOverused && hasLoopExitCandidate) {
            for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
                if (candidateCommand == null) {
                    continue;
                }
                if (safeInt(candidateCommand.getCurrentLoopHitCount()) < shortestPathLoopHitCount) {
                    appendCandidateIfAbsent(reorderedList, candidateCommand);
                }
            }
        }
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand != null
                    && candidateCommand.getPathLength() != null
                    && candidateCommand.getPathLength() > shortestPathLength) {
                appendCandidateIfAbsent(reorderedList, candidateCommand);
            }
        }
        for (RerouteCandidateCommand candidateCommand : candidateCommandList) {
            if (candidateCommand == null || candidateCommand.getPathLength() == null) {
                continue;
            }
            appendCandidateIfAbsent(reorderedList, candidateCommand);
        }
        return reorderedList;
    }
 
    private void appendCandidateIfAbsent(List<RerouteCandidateCommand> reorderedList,
                                         RerouteCandidateCommand candidateCommand) {
        if (reorderedList == null || candidateCommand == null) {
            return;
        }
        if (!reorderedList.contains(candidateCommand)) {
            reorderedList.add(candidateCommand);
        }
    }
 
    private RunBlockRerouteState loadRunBlockRerouteState(Integer taskNo, Integer blockStationId) {
        if (redisUtil == null || taskNo == null || taskNo <= 0 || blockStationId == null || blockStationId <= 0) {
            return new RunBlockRerouteState();
        }
        Object stateObj = redisUtil.get(buildRunBlockRerouteStateKey(taskNo, blockStationId));
        if (stateObj == null) {
            return new RunBlockRerouteState();
        }
        try {
            RunBlockRerouteState state = JSON.parseObject(String.valueOf(stateObj), RunBlockRerouteState.class);
            return state == null ? new RunBlockRerouteState() : state.normalize();
        } catch (Exception ignore) {
            return new RunBlockRerouteState();
        }
    }
 
    private void saveRunBlockRerouteState(RunBlockRerouteState rerouteState) {
        if (redisUtil == null
                || rerouteState == null
                || rerouteState.getTaskNo() == null
                || rerouteState.getTaskNo() <= 0
                || rerouteState.getBlockStationId() == null
                || rerouteState.getBlockStationId() <= 0) {
            return;
        }
        rerouteState.normalize();
        redisUtil.set(
                buildRunBlockRerouteStateKey(rerouteState.getTaskNo(), rerouteState.getBlockStationId()),
                JSON.toJSONString(rerouteState),
                RUN_BLOCK_REROUTE_STATE_EXPIRE_SECONDS
        );
    }
 
    private String buildRunBlockRerouteStateKey(Integer taskNo, Integer blockStationId) {
        return RedisKeyType.STATION_RUN_BLOCK_REROUTE_STATE_.key + taskNo + "_" + blockStationId;
    }
 
    private int countCurrentLoopStationHit(List<Integer> path, Set<Integer> currentLoopStationIdSet) {
        if (path == null || path.isEmpty() || currentLoopStationIdSet == null || currentLoopStationIdSet.isEmpty()) {
            return 0;
        }
        int hitCount = 0;
        for (Integer stationId : path) {
            if (stationId != null && currentLoopStationIdSet.contains(stationId)) {
                hitCount++;
            }
        }
        return hitCount;
    }
 
    private String buildPathSignature(List<Integer> path) {
        if (path == null || path.isEmpty()) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (Integer stationNo : path) {
            if (stationNo == null) {
                continue;
            }
            if (builder.length() > 0) {
                builder.append("->");
            }
            builder.append(stationNo);
        }
        return builder.toString();
    }
 
    private int safeInt(Integer value) {
        return value == null ? 0 : value;
    }
 
    private List<List<Integer>> copyRoutePathList(List<List<Integer>> source) {
        List<List<Integer>> copy = new ArrayList<>();
        if (source == null || source.isEmpty()) {
            return copy;
        }
        for (List<Integer> route : source) {
            copy.add(route == null ? new ArrayList<>() : new ArrayList<>(route));
        }
        return copy;
    }
 
    @Data
    public static class PlanResult {
        private final StationCommand command;
        private final int planCount;
        private final List<List<Integer>> issuedRoutePathList;
    }
 
    @Data
    private static class RunBlockRerouteState {
        private Integer taskNo;
        private Integer blockStationId;
        private Integer planCount = 0;
        private List<List<Integer>> issuedRoutePathList = new ArrayList<>();
        private List<Integer> lastSelectedRoute = new ArrayList<>();
        private Set<String> issuedRouteSignatureSet = new LinkedHashSet<>();
        private Map<String, Integer> routeIssueCountMap = new HashMap<>();
 
        private RunBlockRerouteState normalize() {
            if (planCount == null || planCount < 0) {
                planCount = 0;
            }
            if (issuedRoutePathList == null) {
                issuedRoutePathList = new ArrayList<>();
            }
            if (lastSelectedRoute == null) {
                lastSelectedRoute = new ArrayList<>();
            }
            if (issuedRouteSignatureSet == null) {
                issuedRouteSignatureSet = new LinkedHashSet<>();
            }
            if (routeIssueCountMap == null) {
                routeIssueCountMap = new HashMap<>();
            }
            for (List<Integer> routePath : issuedRoutePathList) {
                if (routePath == null || routePath.isEmpty()) {
                    continue;
                }
                String pathSignature = buildPathSignatureText(routePath);
                if (!Cools.isEmpty(pathSignature)) {
                    issuedRouteSignatureSet.add(pathSignature);
                    routeIssueCountMap.putIfAbsent(pathSignature, 1);
                }
            }
            return this;
        }
 
        private void resetIssuedRoutes() {
            this.issuedRoutePathList = new ArrayList<>();
            this.lastSelectedRoute = new ArrayList<>();
            this.issuedRouteSignatureSet = new LinkedHashSet<>();
        }
 
        private static String buildPathSignatureText(List<Integer> routePath) {
            if (routePath == null || routePath.isEmpty()) {
                return "";
            }
            StringBuilder builder = new StringBuilder();
            for (Integer stationId : routePath) {
                if (stationId == null) {
                    continue;
                }
                if (builder.length() > 0) {
                    builder.append("->");
                }
                builder.append(stationId);
            }
            return builder.toString();
        }
    }
 
    @Data
    private static class RerouteCandidateCommand {
        private StationCommand command;
        private String routeSignature;
        private Integer pathLength;
        private Integer issuedCount;
        private String loopFingerprint;
        private Boolean loopTriggered;
        private Integer currentLoopHitCount;
    }
}