BlueGit

timfa containerpipes

Fix sleeping-probe ConcurrentModificationException and isolate transfer failures.

Wakeups during a probe no longer mutate the sleeping map while it is iterated, and a single bad container no longer aborts the whole network.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-08-17 · 3 months ago

Hash
901a6bef806f90f6e0eea3b20a1228c916f20d4b
Parent
199cc6c6
2 files changed +151 −61
src/main/java/nl/timfalken/containerpipes/HopperStyleEndpoints.java +7 −1
@@ -46,7 +46,13 @@ public final class HopperStyleEndpoints {
46 46 public static Inventory inventoryOf(Block block) {
47 47 if (block == null) return null;
48 48 if (isComposter(block)) return null;
49 BlockState state = block.getState();
49 BlockState state;
50 try {
51 // Live tile entity: snapshot inventories can throw on getHolder/getStorageContents.
52 state = block.getState(false);
53 } catch (Throwable ignored) {
54 state = block.getState();
55 }
50 56 if (state instanceof org.bukkit.block.Chest chest) return chest.getInventory();
51 57 if (state instanceof Container container) return container.getInventory();
52 58 if (state instanceof Jukebox jukebox) return jukebox.getInventory();
@@ -46,7 +46,13 @@ public final class HopperStyleEndpoints {
46 public static Inventory inventoryOf(Block block) {
46 public static Inventory inventoryOf(Block block) {
47 if (block == null) return null;
47 if (block == null) return null;
48 if (isComposter(block)) return null;
48 if (isComposter(block)) return null;
49 BlockState state = block.getState();
49 BlockState state;
50 try {
51 // Live tile entity: snapshot inventories can throw on getHolder/getStorageContents.
52 state = block.getState(false);
53 } catch (Throwable ignored) {
54 state = block.getState();
55 }
50 if (state instanceof org.bukkit.block.Chest chest) return chest.getInventory();
56 if (state instanceof org.bukkit.block.Chest chest) return chest.getInventory();
51 if (state instanceof Container container) return container.getInventory();
57 if (state instanceof Container container) return container.getInventory();
52 if (state instanceof Jukebox jukebox) return jukebox.getInventory();
58 if (state instanceof Jukebox jukebox) return jukebox.getInventory();
src/main/java/nl/timfalken/containerpipes/OptimizedTransferPlanner.java +144 −60
@@ -21,10 +21,12 @@ import org.bukkit.inventory.Inventory;
21 21 import org.bukkit.inventory.InventoryHolder;
22 22 import org.bukkit.inventory.ItemStack;
23 23 import org.bukkit.inventory.JukeboxInventory;
24 import org.bukkit.plugin.Plugin;
24 25
25 26 import java.lang.reflect.*;
26 27 import java.util.*;
27 28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.logging.Level;
28 30
29 31 /**
30 32 * Direct Paper-API transfer planner.
@@ -121,8 +123,16 @@ public final class OptimizedTransferPlanner {
121 123
122 124 void tick() {
123 125 logicalTick += schedulerInterval;
124 reloadConfigIfNeeded();
125 rebuild(false);
126 try {
127 reloadConfigIfNeeded();
128 } catch (Throwable t) {
129 log(plugin, "Could not reload transfer config", t);
130 }
131 try {
132 rebuild(false);
133 } catch (Throwable t) {
134 log(plugin, "Could not rebuild pipe groups", t);
135 }
126 136 cycleDestinations.clear();
127 137
128 138 List<Group> cycle = new ArrayList<>(active);
@@ -134,33 +144,48 @@ public final class OptimizedTransferPlanner {
134 144 // through-container can therefore keep flowing while it also receives.
135 145 for (Group group : cycle) {
136 146 if (!active.contains(group) || groups.get(group.key) != group) continue;
137 group.prepareCycleBudget();
147 try {
148 group.prepareCycleBudget();
149 } catch (Throwable t) {
150 log(plugin, "Could not read source inventory at " + formatKey(group.key), t);
151 group.cacheDirty = true;
152 sleepGroup(group);
153 }
138 154 }
139 155
140 156 for (Group group : cycle) {
141 157 if (!active.contains(group) || groups.get(group.key) != group) continue;
142 158
143 RunResult result = group.run();
144 if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
145 // STALE_CACHE already rebuilt from the real inventory. Keep the
146 // group active so the corrected contents are retried next cycle.
147 group.failed = 0;
148 } else if (++group.failed >= idleAfter) {
149 Inventory source = inventoryAt(group.connections.get(0).source);
150 if (source != null && group.refreshRealInventoryIfChanged(source)) {
151 // A direct, non-event mutation introduced/rearranged items.
152 // Do not sleep on stale knowledge; retry on the normal cadence.
159 try {
160 RunResult result = group.run();
161 if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
162 // STALE_CACHE already rebuilt from the real inventory. Keep the
163 // group active so the corrected contents are retried next cycle.
153 164 group.failed = 0;
154 } else {
155 active.remove(group);
156 sleeping.put(group, logicalTick + sleepProbe);
165 } else if (++group.failed >= idleAfter) {
166 Inventory source = inventoryAt(group.connections.get(0).source);
167 if (source != null && group.refreshRealInventoryIfChanged(source)) {
168 // A direct, non-event mutation introduced/rearranged items.
169 // Do not sleep on stale knowledge; retry on the normal cadence.
170 group.failed = 0;
171 } else {
172 sleepGroup(group);
173 }
157 174 }
175 } catch (Throwable t) {
176 log(plugin, "Transfer failed at " + formatKey(group.key), t);
177 group.cacheDirty = true;
178 sleepGroup(group);
158 179 }
159 180 }
160 181
161 182 int sleepingBatchInterval = Math.max(1, config().getInt("performance.sleeping-probe-batch-interval-ticks", 5));
162 183 if (logicalTick >= nextSleepingBatchTick) {
163 probeSleepingBatch();
184 try {
185 probeSleepingBatch();
186 } catch (Throwable t) {
187 log(plugin, "Sleeping transfer probe failed", t);
188 }
164 189 nextSleepingBatchTick = logicalTick + sleepingBatchInterval;
165 190 }
166 191
@@ -174,6 +199,11 @@ public final class OptimizedTransferPlanner {
174 199 }
175 200 }
176 201
202 void sleepGroup(Group group) {
203 active.remove(group);
204 sleeping.put(group, logicalTick + sleepProbe);
205 }
206
177 207 void reloadConfigIfNeeded() {
178 208 if (logicalTick < nextConfigReloadTick) return;
179 209 reloadConfig();
@@ -183,27 +213,38 @@ public final class OptimizedTransferPlanner {
183 213 void probeSleepingBatch() {
184 214 rebuild(false);
185 215 if (sleeping.isEmpty()) return;
186 int processed = 0;
187 List<Group> activate = new ArrayList<>();
188 List<Group> requeue = new ArrayList<>();
216
217 // Snapshot due groups first. run() can wake other sleeping sources
218 // (destination fill, afterTransfer), which would otherwise CME the
219 // LinkedHashMap iterator.
220 List<Group> due = new ArrayList<>(sleepBatchSize);
189 221 Iterator<Map.Entry<Group, Long>> it = sleeping.entrySet().iterator();
190 while (it.hasNext() && processed < sleepBatchSize) {
222 while (it.hasNext() && due.size() < sleepBatchSize) {
191 223 Map.Entry<Group, Long> entry = it.next();
192 224 if (entry.getValue() > logicalTick) continue;
193 Group group = entry.getKey();
194 225 it.remove();
195 processed++;
226 due.add(entry.getKey());
227 }
228
229 List<Group> activate = new ArrayList<>();
230 List<Group> requeue = new ArrayList<>();
231 for (Group group : due) {
196 232 if (groups.get(group.key) != group) continue;
197 // A sleeping probe is the final safety net for direct inventory
198 // mutations by other plugins that do not emit Bukkit events. Always
199 // read the real inventory here instead of trusting an old clean cache.
200 group.cacheDirty = true;
201 group.prepareCycleBudget();
202 RunResult result = group.run();
203 if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
204 group.failed = 0;
205 activate.add(group);
206 } else {
233 try {
234 // A sleeping probe is the final safety net for direct inventory
235 // mutations by other plugins that do not emit Bukkit events. Always
236 // read the real inventory here instead of trusting an old clean cache.
237 group.cacheDirty = true;
238 group.prepareCycleBudget();
239 RunResult result = group.run();
240 if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
241 group.failed = 0;
242 activate.add(group);
243 } else {
244 requeue.add(group);
245 }
246 } catch (Throwable t) {
247 log(plugin, "Sleeping probe failed at " + formatKey(group.key), t);
207 248 requeue.add(group);
208 249 }
209 250 }
@@ -244,14 +285,18 @@ public final class OptimizedTransferPlanner {
244 285 }
245 286
246 287 for (Group group : groups.values()) {
247 group.rebuildCache();
248 wakeIndex.computeIfAbsent(group.key, ignored -> new LinkedHashSet<>()).add(group);
249 for (ContainerKey destination : group.destinationKeys) {
250 wakeIndex.computeIfAbsent(destination, ignored -> new LinkedHashSet<>()).add(group);
288 try {
289 group.rebuildCache();
290 wakeIndex.computeIfAbsent(group.key, ignored -> new LinkedHashSet<>()).add(group);
291 for (ContainerKey destination : group.destinationKeys) {
292 wakeIndex.computeIfAbsent(destination, ignored -> new LinkedHashSet<>()).add(group);
293 }
294 // Rebuilds are infrequent and should never make a usable pipe wait for
295 // the emergency probe. Start rebuilt groups active.
296 active.add(group);
297 } catch (Throwable t) {
298 log(plugin, "Could not index destinations for " + formatKey(group.key), t);
251 299 }
252 // Rebuilds are infrequent and should never make a usable pipe wait for
253 // the emergency probe. Start rebuilt groups active.
254 active.add(group);
255 300 }
256 301 }
257 302
@@ -675,6 +720,7 @@ public final class OptimizedTransferPlanner {
675 720 }
676 721
677 722 ItemStack[] cloneContents(ItemStack[] input) {
723 if (input == null) return new ItemStack[0];
678 724 ItemStack[] copy = new ItemStack[input.length];
679 725 for (int i = 0; i < input.length; i++) copy[i] = input[i] == null ? null : input[i].clone();
680 726 return copy;
@@ -903,7 +949,12 @@ public final class OptimizedTransferPlanner {
903 949 }
904 950
905 951 Inventory inventoryOf(Block block) {
906 return HopperStyleEndpoints.inventoryOf(block);
952 try {
953 return HopperStyleEndpoints.inventoryOf(block);
954 } catch (Throwable t) {
955 log(plugin, "Could not open inventory at " + block.getX() + "," + block.getY() + "," + block.getZ(), t);
956 return null;
957 }
907 958 }
908 959
909 960 Block blockAt(ContainerKey key) {
@@ -928,21 +979,36 @@ public final class OptimizedTransferPlanner {
928 979
929 980 ContainerKey inventoryKey(Inventory inventory) {
930 981 if (inventory == null) return null;
931 InventoryHolder holder = inventory.getHolder();
932 if (holder instanceof DoubleChest doubleChest) {
933 ContainerKey left = holderKey(doubleChest.getLeftSide());
934 ContainerKey right = holderKey(doubleChest.getRightSide());
935 if (left == null) return right;
936 if (right == null) return left;
937 int wc = left.world.compareTo(right.world);
938 return wc < 0 || (wc == 0 && Long.compareUnsigned(left.packed, right.packed) <= 0) ? left : right;
939 }
940 Location location = inventory.getLocation();
941 if (location != null && location.getWorld() != null) {
942 return new ContainerKey(location.getWorld().getUID(),
943 pack(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
982 try {
983 InventoryHolder holder = inventory.getHolder();
984 if (holder instanceof DoubleChest doubleChest) {
985 ContainerKey left = holderKey(doubleChest.getLeftSide());
986 ContainerKey right = holderKey(doubleChest.getRightSide());
987 if (left == null) return right;
988 if (right == null) return left;
989 int wc = left.world.compareTo(right.world);
990 return wc < 0 || (wc == 0 && Long.compareUnsigned(left.packed, right.packed) <= 0) ? left : right;
991 }
992 Location location = inventory.getLocation();
993 if (location != null && location.getWorld() != null) {
994 return new ContainerKey(location.getWorld().getUID(),
995 pack(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
996 }
997 return holderKey(holder);
998 } catch (Throwable t) {
999 try {
1000 Location location = inventory.getLocation();
1001 if (location != null && location.getWorld() != null) {
1002 return new ContainerKey(location.getWorld().getUID(),
1003 pack(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
1004 }
1005 } catch (Throwable ignored) {}
1006 return null;
944 1007 }
945 return holderKey(holder);
1008 }
1009
1010 String formatKey(ContainerKey key) {
1011 return unpackX(key.packed()) + "," + unpackY(key.packed()) + "," + unpackZ(key.packed());
946 1012 }
947 1013
948 1014 ContainerKey holderKey(InventoryHolder holder) {
@@ -1083,17 +1149,31 @@ public final class OptimizedTransferPlanner {
1083 1149 }
1084 1150
1085 1151 private static Method findMethod(Class<?> owner, String name, Class<?>[] parameterTypes) throws Exception {
1152 Method fallback = null;
1086 1153 for (Class<?> type = owner; type != null; type = type.getSuperclass()) {
1087 1154 for (Method method : type.getDeclaredMethods()) {
1088 if (method.getName().equals(name) && compatible(method.getParameterTypes(), parameterTypes)) return method;
1155 if (!method.getName().equals(name) || !compatible(method.getParameterTypes(), parameterTypes)) continue;
1156 if (exact(method.getParameterTypes(), parameterTypes)) return method;
1157 if (fallback == null) fallback = method;
1089 1158 }
1090 1159 }
1091 1160 for (Method method : owner.getMethods()) {
1092 if (method.getName().equals(name) && compatible(method.getParameterTypes(), parameterTypes)) return method;
1161 if (!method.getName().equals(name) || !compatible(method.getParameterTypes(), parameterTypes)) continue;
1162 if (exact(method.getParameterTypes(), parameterTypes)) return method;
1163 if (fallback == null) fallback = method;
1093 1164 }
1165 if (fallback != null) return fallback;
1094 1166 throw new NoSuchMethodException(owner.getName() + "." + name);
1095 1167 }
1096 1168
1169 private static boolean exact(Class<?>[] actual, Class<?>[] requested) {
1170 if (actual.length != requested.length) return false;
1171 for (int index = 0; index < actual.length; index++) {
1172 if (wrap(actual[index]) != wrap(requested[index])) return false;
1173 }
1174 return true;
1175 }
1176
1097 1177 private static boolean compatible(Class<?>[] actual, Class<?>[] requested) {
1098 1178 if (actual.length != requested.length) return false;
1099 1179 for (int index = 0; index < actual.length; index++) {
@@ -1113,11 +1193,15 @@ public final class OptimizedTransferPlanner {
1113 1193 }
1114 1194
1115 1195 private static void log(Object plugin, String message, Throwable throwable) {
1196 String detail = message + ": " + throwable;
1116 1197 try {
1117 Object logger = call(plugin, "getLogger");
1118 call(logger, "log", new Class<?>[]{java.util.logging.Level.class, String.class, Throwable.class},
1119 java.util.logging.Level.WARNING, message, throwable);
1198 if (plugin instanceof Plugin bukkitPlugin) {
1199 bukkitPlugin.getLogger().log(Level.WARNING, detail, throwable);
1200 return;
1201 }
1120 1202 } catch (Throwable ignored) {}
1203 System.err.println("[ContainerPipes] " + detail);
1204 if (throwable != null) throwable.printStackTrace();
1121 1205 }
1122 1206
1123 1207 private record MethodKey(Class<?> owner, String name, List<Class<?>> parameters) {}
@@ -21,10 +21,12 @@ import org.bukkit.inventory.Inventory;
21import org.bukkit.inventory.InventoryHolder;
21import org.bukkit.inventory.InventoryHolder;
22import org.bukkit.inventory.ItemStack;
22import org.bukkit.inventory.ItemStack;
23import org.bukkit.inventory.JukeboxInventory;
23import org.bukkit.inventory.JukeboxInventory;
24import org.bukkit.plugin.Plugin;
24
25
25import java.lang.reflect.*;
26import java.lang.reflect.*;
26import java.util.*;
27import java.util.*;
27import java.util.concurrent.ConcurrentHashMap;
28import java.util.concurrent.ConcurrentHashMap;
29import java.util.logging.Level;
28
30
29/**
31/**
30 * Direct Paper-API transfer planner.
32 * Direct Paper-API transfer planner.
@@ -121,8 +123,16 @@ public final class OptimizedTransferPlanner {
121
123
122 void tick() {
124 void tick() {
123 logicalTick += schedulerInterval;
125 logicalTick += schedulerInterval;
124 reloadConfigIfNeeded();
126 try {
125 rebuild(false);
127 reloadConfigIfNeeded();
128 } catch (Throwable t) {
129 log(plugin, "Could not reload transfer config", t);
130 }
131 try {
132 rebuild(false);
133 } catch (Throwable t) {
134 log(plugin, "Could not rebuild pipe groups", t);
135 }
126 cycleDestinations.clear();
136 cycleDestinations.clear();
127
137
128 List<Group> cycle = new ArrayList<>(active);
138 List<Group> cycle = new ArrayList<>(active);
@@ -134,33 +144,48 @@ public final class OptimizedTransferPlanner {
134 // through-container can therefore keep flowing while it also receives.
144 // through-container can therefore keep flowing while it also receives.
135 for (Group group : cycle) {
145 for (Group group : cycle) {
136 if (!active.contains(group) || groups.get(group.key) != group) continue;
146 if (!active.contains(group) || groups.get(group.key) != group) continue;
137 group.prepareCycleBudget();
147 try {
148 group.prepareCycleBudget();
149 } catch (Throwable t) {
150 log(plugin, "Could not read source inventory at " + formatKey(group.key), t);
151 group.cacheDirty = true;
152 sleepGroup(group);
153 }
138 }
154 }
139
155
140 for (Group group : cycle) {
156 for (Group group : cycle) {
141 if (!active.contains(group) || groups.get(group.key) != group) continue;
157 if (!active.contains(group) || groups.get(group.key) != group) continue;
142
158
143 RunResult result = group.run();
159 try {
144 if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
160 RunResult result = group.run();
145 // STALE_CACHE already rebuilt from the real inventory. Keep the
161 if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
146 // group active so the corrected contents are retried next cycle.
162 // STALE_CACHE already rebuilt from the real inventory. Keep the
147 group.failed = 0;
163 // group active so the corrected contents are retried next cycle.
148 } else if (++group.failed >= idleAfter) {
149 Inventory source = inventoryAt(group.connections.get(0).source);
150 if (source != null && group.refreshRealInventoryIfChanged(source)) {
151 // A direct, non-event mutation introduced/rearranged items.
152 // Do not sleep on stale knowledge; retry on the normal cadence.
153 group.failed = 0;
164 group.failed = 0;
154 } else {
165 } else if (++group.failed >= idleAfter) {
155 active.remove(group);
166 Inventory source = inventoryAt(group.connections.get(0).source);
156 sleeping.put(group, logicalTick + sleepProbe);
167 if (source != null && group.refreshRealInventoryIfChanged(source)) {
168 // A direct, non-event mutation introduced/rearranged items.
169 // Do not sleep on stale knowledge; retry on the normal cadence.
170 group.failed = 0;
171 } else {
172 sleepGroup(group);
173 }
157 }
174 }
175 } catch (Throwable t) {
176 log(plugin, "Transfer failed at " + formatKey(group.key), t);
177 group.cacheDirty = true;
178 sleepGroup(group);
158 }
179 }
159 }
180 }
160
181
161 int sleepingBatchInterval = Math.max(1, config().getInt("performance.sleeping-probe-batch-interval-ticks", 5));
182 int sleepingBatchInterval = Math.max(1, config().getInt("performance.sleeping-probe-batch-interval-ticks", 5));
162 if (logicalTick >= nextSleepingBatchTick) {
183 if (logicalTick >= nextSleepingBatchTick) {
163 probeSleepingBatch();
184 try {
185 probeSleepingBatch();
186 } catch (Throwable t) {
187 log(plugin, "Sleeping transfer probe failed", t);
188 }
164 nextSleepingBatchTick = logicalTick + sleepingBatchInterval;
189 nextSleepingBatchTick = logicalTick + sleepingBatchInterval;
165 }
190 }
166
191
@@ -174,6 +199,11 @@ public final class OptimizedTransferPlanner {
174 }
199 }
175 }
200 }
176
201
202 void sleepGroup(Group group) {
203 active.remove(group);
204 sleeping.put(group, logicalTick + sleepProbe);
205 }
206
177 void reloadConfigIfNeeded() {
207 void reloadConfigIfNeeded() {
178 if (logicalTick < nextConfigReloadTick) return;
208 if (logicalTick < nextConfigReloadTick) return;
179 reloadConfig();
209 reloadConfig();
@@ -183,27 +213,38 @@ public final class OptimizedTransferPlanner {
183 void probeSleepingBatch() {
213 void probeSleepingBatch() {
184 rebuild(false);
214 rebuild(false);
185 if (sleeping.isEmpty()) return;
215 if (sleeping.isEmpty()) return;
186 int processed = 0;
216
187 List<Group> activate = new ArrayList<>();
217 // Snapshot due groups first. run() can wake other sleeping sources
188 List<Group> requeue = new ArrayList<>();
218 // (destination fill, afterTransfer), which would otherwise CME the
219 // LinkedHashMap iterator.
220 List<Group> due = new ArrayList<>(sleepBatchSize);
189 Iterator<Map.Entry<Group, Long>> it = sleeping.entrySet().iterator();
221 Iterator<Map.Entry<Group, Long>> it = sleeping.entrySet().iterator();
190 while (it.hasNext() && processed < sleepBatchSize) {
222 while (it.hasNext() && due.size() < sleepBatchSize) {
191 Map.Entry<Group, Long> entry = it.next();
223 Map.Entry<Group, Long> entry = it.next();
192 if (entry.getValue() > logicalTick) continue;
224 if (entry.getValue() > logicalTick) continue;
193 Group group = entry.getKey();
194 it.remove();
225 it.remove();
195 processed++;
226 due.add(entry.getKey());
227 }
228
229 List<Group> activate = new ArrayList<>();
230 List<Group> requeue = new ArrayList<>();
231 for (Group group : due) {
196 if (groups.get(group.key) != group) continue;
232 if (groups.get(group.key) != group) continue;
197 // A sleeping probe is the final safety net for direct inventory
233 try {
198 // mutations by other plugins that do not emit Bukkit events. Always
234 // A sleeping probe is the final safety net for direct inventory
199 // read the real inventory here instead of trusting an old clean cache.
235 // mutations by other plugins that do not emit Bukkit events. Always
200 group.cacheDirty = true;
236 // read the real inventory here instead of trusting an old clean cache.
201 group.prepareCycleBudget();
237 group.cacheDirty = true;
202 RunResult result = group.run();
238 group.prepareCycleBudget();
203 if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
239 RunResult result = group.run();
204 group.failed = 0;
240 if (result == RunResult.MOVED || result == RunResult.STALE_CACHE) {
205 activate.add(group);
241 group.failed = 0;
206 } else {
242 activate.add(group);
243 } else {
244 requeue.add(group);
245 }
246 } catch (Throwable t) {
247 log(plugin, "Sleeping probe failed at " + formatKey(group.key), t);
207 requeue.add(group);
248 requeue.add(group);
208 }
249 }
209 }
250 }
@@ -244,14 +285,18 @@ public final class OptimizedTransferPlanner {
244 }
285 }
245
286
246 for (Group group : groups.values()) {
287 for (Group group : groups.values()) {
247 group.rebuildCache();
288 try {
248 wakeIndex.computeIfAbsent(group.key, ignored -> new LinkedHashSet<>()).add(group);
289 group.rebuildCache();
249 for (ContainerKey destination : group.destinationKeys) {
290 wakeIndex.computeIfAbsent(group.key, ignored -> new LinkedHashSet<>()).add(group);
250 wakeIndex.computeIfAbsent(destination, ignored -> new LinkedHashSet<>()).add(group);
291 for (ContainerKey destination : group.destinationKeys) {
292 wakeIndex.computeIfAbsent(destination, ignored -> new LinkedHashSet<>()).add(group);
293 }
294 // Rebuilds are infrequent and should never make a usable pipe wait for
295 // the emergency probe. Start rebuilt groups active.
296 active.add(group);
297 } catch (Throwable t) {
298 log(plugin, "Could not index destinations for " + formatKey(group.key), t);
251 }
299 }
252 // Rebuilds are infrequent and should never make a usable pipe wait for
253 // the emergency probe. Start rebuilt groups active.
254 active.add(group);
255 }
300 }
256 }
301 }
257
302
@@ -675,6 +720,7 @@ public final class OptimizedTransferPlanner {
675 }
720 }
676
721
677 ItemStack[] cloneContents(ItemStack[] input) {
722 ItemStack[] cloneContents(ItemStack[] input) {
723 if (input == null) return new ItemStack[0];
678 ItemStack[] copy = new ItemStack[input.length];
724 ItemStack[] copy = new ItemStack[input.length];
679 for (int i = 0; i < input.length; i++) copy[i] = input[i] == null ? null : input[i].clone();
725 for (int i = 0; i < input.length; i++) copy[i] = input[i] == null ? null : input[i].clone();
680 return copy;
726 return copy;
@@ -903,7 +949,12 @@ public final class OptimizedTransferPlanner {
903 }
949 }
904
950
905 Inventory inventoryOf(Block block) {
951 Inventory inventoryOf(Block block) {
906 return HopperStyleEndpoints.inventoryOf(block);
952 try {
953 return HopperStyleEndpoints.inventoryOf(block);
954 } catch (Throwable t) {
955 log(plugin, "Could not open inventory at " + block.getX() + "," + block.getY() + "," + block.getZ(), t);
956 return null;
957 }
907 }
958 }
908
959
909 Block blockAt(ContainerKey key) {
960 Block blockAt(ContainerKey key) {
@@ -928,21 +979,36 @@ public final class OptimizedTransferPlanner {
928
979
929 ContainerKey inventoryKey(Inventory inventory) {
980 ContainerKey inventoryKey(Inventory inventory) {
930 if (inventory == null) return null;
981 if (inventory == null) return null;
931 InventoryHolder holder = inventory.getHolder();
982 try {
932 if (holder instanceof DoubleChest doubleChest) {
983 InventoryHolder holder = inventory.getHolder();
933 ContainerKey left = holderKey(doubleChest.getLeftSide());
984 if (holder instanceof DoubleChest doubleChest) {
934 ContainerKey right = holderKey(doubleChest.getRightSide());
985 ContainerKey left = holderKey(doubleChest.getLeftSide());
935 if (left == null) return right;
986 ContainerKey right = holderKey(doubleChest.getRightSide());
936 if (right == null) return left;
987 if (left == null) return right;
937 int wc = left.world.compareTo(right.world);
988 if (right == null) return left;
938 return wc < 0 || (wc == 0 && Long.compareUnsigned(left.packed, right.packed) <= 0) ? left : right;
989 int wc = left.world.compareTo(right.world);
939 }
990 return wc < 0 || (wc == 0 && Long.compareUnsigned(left.packed, right.packed) <= 0) ? left : right;
940 Location location = inventory.getLocation();
991 }
941 if (location != null && location.getWorld() != null) {
992 Location location = inventory.getLocation();
942 return new ContainerKey(location.getWorld().getUID(),
993 if (location != null && location.getWorld() != null) {
943 pack(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
994 return new ContainerKey(location.getWorld().getUID(),
995 pack(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
996 }
997 return holderKey(holder);
998 } catch (Throwable t) {
999 try {
1000 Location location = inventory.getLocation();
1001 if (location != null && location.getWorld() != null) {
1002 return new ContainerKey(location.getWorld().getUID(),
1003 pack(location.getBlockX(), location.getBlockY(), location.getBlockZ()));
1004 }
1005 } catch (Throwable ignored) {}
1006 return null;
944 }
1007 }
945 return holderKey(holder);
1008 }
1009
1010 String formatKey(ContainerKey key) {
1011 return unpackX(key.packed()) + "," + unpackY(key.packed()) + "," + unpackZ(key.packed());
946 }
1012 }
947
1013
948 ContainerKey holderKey(InventoryHolder holder) {
1014 ContainerKey holderKey(InventoryHolder holder) {
@@ -1083,17 +1149,31 @@ public final class OptimizedTransferPlanner {
1083 }
1149 }
1084
1150
1085 private static Method findMethod(Class<?> owner, String name, Class<?>[] parameterTypes) throws Exception {
1151 private static Method findMethod(Class<?> owner, String name, Class<?>[] parameterTypes) throws Exception {
1152 Method fallback = null;
1086 for (Class<?> type = owner; type != null; type = type.getSuperclass()) {
1153 for (Class<?> type = owner; type != null; type = type.getSuperclass()) {
1087 for (Method method : type.getDeclaredMethods()) {
1154 for (Method method : type.getDeclaredMethods()) {
1088 if (method.getName().equals(name) && compatible(method.getParameterTypes(), parameterTypes)) return method;
1155 if (!method.getName().equals(name) || !compatible(method.getParameterTypes(), parameterTypes)) continue;
1156 if (exact(method.getParameterTypes(), parameterTypes)) return method;
1157 if (fallback == null) fallback = method;
1089 }
1158 }
1090 }
1159 }
1091 for (Method method : owner.getMethods()) {
1160 for (Method method : owner.getMethods()) {
1092 if (method.getName().equals(name) && compatible(method.getParameterTypes(), parameterTypes)) return method;
1161 if (!method.getName().equals(name) || !compatible(method.getParameterTypes(), parameterTypes)) continue;
1162 if (exact(method.getParameterTypes(), parameterTypes)) return method;
1163 if (fallback == null) fallback = method;
1093 }
1164 }
1165 if (fallback != null) return fallback;
1094 throw new NoSuchMethodException(owner.getName() + "." + name);
1166 throw new NoSuchMethodException(owner.getName() + "." + name);
1095 }
1167 }
1096
1168
1169 private static boolean exact(Class<?>[] actual, Class<?>[] requested) {
1170 if (actual.length != requested.length) return false;
1171 for (int index = 0; index < actual.length; index++) {
1172 if (wrap(actual[index]) != wrap(requested[index])) return false;
1173 }
1174 return true;
1175 }
1176
1097 private static boolean compatible(Class<?>[] actual, Class<?>[] requested) {
1177 private static boolean compatible(Class<?>[] actual, Class<?>[] requested) {
1098 if (actual.length != requested.length) return false;
1178 if (actual.length != requested.length) return false;
1099 for (int index = 0; index < actual.length; index++) {
1179 for (int index = 0; index < actual.length; index++) {
@@ -1113,11 +1193,15 @@ public final class OptimizedTransferPlanner {
1113 }
1193 }
1114
1194
1115 private static void log(Object plugin, String message, Throwable throwable) {
1195 private static void log(Object plugin, String message, Throwable throwable) {
1196 String detail = message + ": " + throwable;
1116 try {
1197 try {
1117 Object logger = call(plugin, "getLogger");
1198 if (plugin instanceof Plugin bukkitPlugin) {
1118 call(logger, "log", new Class<?>[]{java.util.logging.Level.class, String.class, Throwable.class},
1199 bukkitPlugin.getLogger().log(Level.WARNING, detail, throwable);
1119 java.util.logging.Level.WARNING, message, throwable);
1200 return;
1201 }
1120 } catch (Throwable ignored) {}
1202 } catch (Throwable ignored) {}
1203 System.err.println("[ContainerPipes] " + detail);
1204 if (throwable != null) throwable.printStackTrace();
1121 }
1205 }
1122
1206
1123 private record MethodKey(Class<?> owner, String name, List<Class<?>> parameters) {}
1207 private record MethodKey(Class<?> owner, String name, List<Class<?>> parameters) {}