Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b4HkWoC7hLzk61vZa8
41 lines
1.5 KiB
Java
41 lines
1.5 KiB
Java
package com.ankurm.prreviewer;
|
|
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
import java.util.Map;
|
|
import java.util.concurrent.CompletableFuture;
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
import java.util.concurrent.ExecutorService;
|
|
import java.util.concurrent.Executors;
|
|
|
|
/**
|
|
* Runs reviews off the request thread, one at a time per pull request. Two quick pushes would otherwise
|
|
* both read "nothing posted yet" and both post the same comments. This is per process: run one replica,
|
|
* or move the lock to a shared store.
|
|
*/
|
|
public class ReviewQueue implements AutoCloseable {
|
|
|
|
private static final Logger log = LoggerFactory.getLogger(ReviewQueue.class);
|
|
|
|
private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
|
|
private final Map<String, CompletableFuture<Void>> tails = new ConcurrentHashMap<>();
|
|
|
|
public CompletableFuture<Void> submit(String key, Runnable job) {
|
|
CompletableFuture<Void> next = tails.compute(key, (k, tail) ->
|
|
(tail == null ? CompletableFuture.<Void>completedFuture(null) : tail)
|
|
.thenRunAsync(job, executor)
|
|
.exceptionally(e -> {
|
|
log.error("review of {} failed", k, e);
|
|
return null;
|
|
}));
|
|
next.whenComplete((v, e) -> tails.remove(key, next));
|
|
return next;
|
|
}
|
|
|
|
@Override
|
|
public void close() {
|
|
executor.close();
|
|
}
|
|
}
|