|
| 1 | +// Copyright 2026 Query Farm LLC - https://query.farm |
| 2 | + |
| 3 | +package farm.query.vgi.example.txfix; |
| 4 | + |
| 5 | +import java.io.IOException; |
| 6 | +import java.net.URLDecoder; |
| 7 | +import java.net.URLEncoder; |
| 8 | +import java.nio.channels.FileChannel; |
| 9 | +import java.nio.channels.FileLock; |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | +import java.nio.file.Files; |
| 12 | +import java.nio.file.Path; |
| 13 | +import java.nio.file.StandardOpenOption; |
| 14 | +import java.security.MessageDigest; |
| 15 | +import java.util.ArrayList; |
| 16 | +import java.util.HexFormat; |
| 17 | +import java.util.LinkedHashMap; |
| 18 | +import java.util.List; |
| 19 | +import java.util.Map; |
| 20 | +import java.util.TreeMap; |
| 21 | +import java.util.concurrent.locks.ReentrantLock; |
| 22 | +import java.util.function.Function; |
| 23 | + |
| 24 | +/** |
| 25 | + * The txfix fixture's state, shared by every worker process: one file per {@code token} |
| 26 | + * partition under {@code $VGI_TXFIX_STATE_DIR} (default {@code <tmp>/vgi-txfix}), read and |
| 27 | + * rewritten under an exclusive file lock (plus an in-process lock, since a JVM cannot hold |
| 28 | + * two overlapping file locks). |
| 29 | + */ |
| 30 | +final class TxFixState { |
| 31 | + |
| 32 | + /** One {@code items} row. */ |
| 33 | + record Row(int id, String name, Long qty) { |
| 34 | + Map<String, Object> asMap() { |
| 35 | + Map<String, Object> m = new LinkedHashMap<>(); |
| 36 | + m.put("id", id); |
| 37 | + m.put("name", name); |
| 38 | + m.put("qty", qty); |
| 39 | + return m; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + /** One event-log entry. */ |
| 44 | + record Event(long seq, String kind, String txId, boolean ok) {} |
| 45 | + |
| 46 | + static final List<Row> INITIAL = List.of(new Row(1, "a", 10L), new Row(2, "b", 20L), new Row(3, "c", 30L)); |
| 47 | + |
| 48 | + private static final ReentrantLock IN_PROCESS = new ReentrantLock(); |
| 49 | + |
| 50 | + /** One token's state, loaded for the duration of {@link #withPartition}. */ |
| 51 | + static final class Partition { |
| 52 | + final TreeMap<Integer, Row> committed = new TreeMap<>(); |
| 53 | + final Map<String, TreeMap<Integer, Row>> staged = new LinkedHashMap<>(); |
| 54 | + final List<Event> events = new ArrayList<>(); |
| 55 | + long seq; |
| 56 | + |
| 57 | + void reset() { |
| 58 | + committed.clear(); |
| 59 | + for (Row r : INITIAL) committed.put(r.id(), r); |
| 60 | + staged.clear(); |
| 61 | + events.clear(); |
| 62 | + seq = 0; |
| 63 | + } |
| 64 | + |
| 65 | + /** The rows a scan in {@code txId} sees: committed, overlaid with its staged changes. */ |
| 66 | + TreeMap<Integer, Row> view(String txId) { |
| 67 | + TreeMap<Integer, Row> out = new TreeMap<>(committed); |
| 68 | + if (txId != null && staged.containsKey(txId)) out.putAll(staged.get(txId)); |
| 69 | + return out; |
| 70 | + } |
| 71 | + |
| 72 | + void event(String kind, String txId, boolean ok) { |
| 73 | + events.add(new Event(++seq, kind, txId, ok)); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + private TxFixState() {} |
| 78 | + |
| 79 | + static Path dir() { |
| 80 | + String d = System.getenv("VGI_TXFIX_STATE_DIR"); |
| 81 | + return d != null && !d.isBlank() ? Path.of(d) : Path.of(System.getProperty("java.io.tmpdir"), "vgi-txfix"); |
| 82 | + } |
| 83 | + |
| 84 | + private static String partitionName(String token) { |
| 85 | + try { |
| 86 | + byte[] digest = MessageDigest.getInstance("SHA-256").digest( |
| 87 | + (token == null ? "\0null" : "t:" + token).getBytes(StandardCharsets.UTF_8)); |
| 88 | + return HexFormat.of().formatHex(digest, 0, 16); |
| 89 | + } catch (java.security.NoSuchAlgorithmException e) { |
| 90 | + throw new IllegalStateException(e); |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + /** Run {@code body} on the token's partition under its lock, saving whatever it changed. */ |
| 95 | + static <T> T withPartition(String token, Function<Partition, T> body) { |
| 96 | + Path dir = dir(); |
| 97 | + String name = partitionName(token); |
| 98 | + IN_PROCESS.lock(); |
| 99 | + try { |
| 100 | + Files.createDirectories(dir); |
| 101 | + try (FileChannel lockChannel = FileChannel.open(dir.resolve(name + ".lock"), |
| 102 | + StandardOpenOption.CREATE, StandardOpenOption.WRITE); |
| 103 | + FileLock ignored = lockChannel.lock()) { |
| 104 | + Path file = dir.resolve(name + ".state"); |
| 105 | + Partition p = new Partition(); |
| 106 | + if (Files.exists(file)) load(p, Files.readAllLines(file, StandardCharsets.UTF_8)); |
| 107 | + else p.reset(); |
| 108 | + T result = body.apply(p); |
| 109 | + Path tmp = dir.resolve(name + ".state.tmp"); |
| 110 | + Files.write(tmp, save(p), StandardCharsets.UTF_8); |
| 111 | + Files.move(tmp, file, java.nio.file.StandardCopyOption.REPLACE_EXISTING, |
| 112 | + java.nio.file.StandardCopyOption.ATOMIC_MOVE); |
| 113 | + return result; |
| 114 | + } |
| 115 | + } catch (IOException e) { |
| 116 | + throw new IllegalStateException("txfix: state I/O failed: " + e.getMessage(), e); |
| 117 | + } finally { |
| 118 | + IN_PROCESS.unlock(); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + private static String enc(String s) { |
| 123 | + return s == null ? "\\N" : URLEncoder.encode(s, StandardCharsets.UTF_8); |
| 124 | + } |
| 125 | + |
| 126 | + private static String dec(String s) { |
| 127 | + return "\\N".equals(s) ? null : URLDecoder.decode(s, StandardCharsets.UTF_8); |
| 128 | + } |
| 129 | + |
| 130 | + private static Long decLong(String s) { |
| 131 | + return "\\N".equals(s) ? null : Long.valueOf(s); |
| 132 | + } |
| 133 | + |
| 134 | + private static List<String> save(Partition p) { |
| 135 | + List<String> out = new ArrayList<>(); |
| 136 | + out.add("seq\t" + p.seq); |
| 137 | + for (Row r : p.committed.values()) { |
| 138 | + out.add("row\t" + r.id() + "\t" + enc(r.name()) + "\t" + (r.qty() == null ? "\\N" : r.qty())); |
| 139 | + } |
| 140 | + for (Map.Entry<String, TreeMap<Integer, Row>> e : p.staged.entrySet()) { |
| 141 | + for (Row r : e.getValue().values()) { |
| 142 | + out.add("staged\t" + e.getKey() + "\t" + r.id() + "\t" + enc(r.name()) + "\t" |
| 143 | + + (r.qty() == null ? "\\N" : r.qty())); |
| 144 | + } |
| 145 | + } |
| 146 | + for (Event ev : p.events) { |
| 147 | + out.add("event\t" + ev.seq() + "\t" + ev.kind() + "\t" + enc(ev.txId()) + "\t" + ev.ok()); |
| 148 | + } |
| 149 | + return out; |
| 150 | + } |
| 151 | + |
| 152 | + private static void load(Partition p, List<String> lines) { |
| 153 | + for (String line : lines) { |
| 154 | + String[] f = line.split("\t", -1); |
| 155 | + switch (f[0]) { |
| 156 | + case "seq" -> p.seq = Long.parseLong(f[1]); |
| 157 | + case "row" -> p.committed.put(Integer.parseInt(f[1]), |
| 158 | + new Row(Integer.parseInt(f[1]), dec(f[2]), decLong(f[3]))); |
| 159 | + case "staged" -> p.staged.computeIfAbsent(f[1], k -> new TreeMap<>()).put(Integer.parseInt(f[2]), |
| 160 | + new Row(Integer.parseInt(f[2]), dec(f[3]), decLong(f[4]))); |
| 161 | + case "event" -> p.events.add(new Event(Long.parseLong(f[1]), f[2], dec(f[3]), |
| 162 | + Boolean.parseBoolean(f[4]))); |
| 163 | + default -> { } |
| 164 | + } |
| 165 | + } |
| 166 | + } |
| 167 | +} |
0 commit comments