diff --git a/common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/TerraScriptAddon.java b/common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/TerraScriptAddon.java index 25c4e3ca8..e3adf0b68 100644 --- a/common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/TerraScriptAddon.java +++ b/common/addons/structure-terrascript-loader/src/main/java/com/dfsek/terra/addons/terrascript/TerraScriptAddon.java @@ -40,6 +40,8 @@ public class TerraScriptAddon implements AddonInitializer { .then(event -> { CheckedRegistry structureRegistry = event.getPack().getOrCreateRegistry(Structure.class); CheckedRegistry lootRegistry = event.getPack().getOrCreateRegistry(LootTable.class); + // Pack registries must not be created from worker threads. + CheckedRegistry functionRegistry = event.getPack().getOrCreateRegistry(FunctionBuilder.class); try { FileUtil.filesWithExtension(event.getPack().getRootPath(), ".tesf") .entrySet() @@ -53,11 +55,12 @@ public class TerraScriptAddon implements AddonInitializer { platform, structureRegistry, lootRegistry, - event.getPack().getOrCreateRegistry(FunctionBuilder.class)); + functionRegistry); } catch(ParseException | IOException e) { throw new RuntimeException("Failed to load script \"" + entry.getKey() + "\"", e); } }) + .toList() .forEach(structureRegistry::register); } catch(IOException e) { throw new RuntimeException("Error occurred while reading config pack files", e); diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java index 6bb0ce13d..c5d315c8f 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/config/pack/ConfigPackImpl.java @@ -111,7 +111,12 @@ public class ConfigPackImpl implements ConfigPack { private final BiomeTagIndex biomeTagIndex = new BiomeTagIndex(); - private final Map> registryMap = new HashMap<>(); + /** + * Guards writes to registryMap, shortcuts, configTypes and the loaders' type maps. Reads of registryMap take no lock: + * publish a registry there only after its loaders are registered. + */ + private final Object registrationLock = new Object(); + private final Map> registryMap = new ConcurrentHashMap<>(); private final Map> shortcuts = new HashMap<>(); private final OpenRegistry> configTypeRegistry; @@ -266,33 +271,41 @@ public class ConfigPackImpl implements ConfigPack { @Override public ConfigPackImpl applyLoader(Type type, TypeLoader loader) { - abstractConfigLoader.registerLoader(type, loader); - selfLoader.registerLoader(type, loader); + synchronized(registrationLock) { + abstractConfigLoader.registerLoader(type, loader); + selfLoader.registerLoader(type, loader); + } return this; } @Override public ConfigPackImpl applyLoader(Type type, Supplier> loader) { - abstractConfigLoader.registerLoader(type, loader); - selfLoader.registerLoader(type, loader); + synchronized(registrationLock) { + abstractConfigLoader.registerLoader(type, loader); + selfLoader.registerLoader(type, loader); + } return this; } @Override public void register(TypeRegistry registry) { - registry.registerLoader(ConfigType.class, configTypeRegistry); - registryMap.forEach(registry::registerLoader); - shortcuts.forEach(registry::registerLoader); // overwrite with delegated shortcuts if present + synchronized(registrationLock) { + registry.registerLoader(ConfigType.class, configTypeRegistry); + registryMap.forEach(registry::registerLoader); + shortcuts.forEach(registry::registerLoader); // overwrite with delegated shortcuts if present + } } @Override public ConfigPack registerConfigType(ConfigType type, RegistryKey key, int priority) { - Set contained = new HashSet<>(); - configTypes.forEach((p, configs) -> configs.forEach(pair -> { - if(contained.contains(pair.getLeft())) throw new IllegalArgumentException("Duplicate config key: " + key); - contained.add(key); - })); - configTypes.computeIfAbsent(priority, p -> new ArrayList<>()).add(Pair.of(key, type)); + synchronized(registrationLock) { + Set contained = new HashSet<>(); + configTypes.forEach((p, configs) -> configs.forEach(pair -> { + if(contained.contains(pair.getLeft())) throw new IllegalArgumentException("Duplicate config key: " + key); + contained.add(key); + })); + configTypes.computeIfAbsent(priority, p -> new ArrayList<>()).add(Pair.of(key, type)); + } return this; } @@ -313,7 +326,12 @@ public class ConfigPackImpl implements ConfigPack { @Override public CheckedRegistry getOrCreateRegistry(TypeKey typeKey) { - return (CheckedRegistry) registryMap.computeIfAbsent(typeKey.getType(), c -> { + Type c = typeKey.getType(); + CheckedRegistryImpl existing = registryMap.get(c); + if(existing != null) return (CheckedRegistry) existing; + synchronized(registrationLock) { + existing = registryMap.get(c); + if(existing != null) return (CheckedRegistry) existing; OpenRegistry registry = new OpenRegistryImpl<>(typeKey); selfLoader.registerLoader(c, registry); abstractConfigLoader.registerLoader(c, registry); @@ -339,8 +357,10 @@ public class ConfigPackImpl implements ConfigPack { } } - return new CheckedRegistryImpl<>(registry); - }); + CheckedRegistryImpl checked = new CheckedRegistryImpl<>(registry); + registryMap.put(c, checked); + return checked; + } } @Override @@ -371,11 +391,16 @@ public class ConfigPackImpl implements ConfigPack { @SuppressWarnings("rawtypes") @Override public ConfigPack registerShortcut(TypeKey clazz, String shortcut, ShortcutLoader loader) { - ShortcutHolder holder = shortcuts - .computeIfAbsent(clazz.getType(), c -> new ShortcutHolder<>(getOrCreateRegistry(clazz))) - .register(shortcut, (ShortcutLoader) loader); - selfLoader.registerLoader(clazz.getType(), holder); - abstractConfigLoader.registerLoader(clazz.getType(), holder); + synchronized(registrationLock) { + ShortcutHolder holder = shortcuts.get(clazz.getType()); + if(holder == null) { + holder = new ShortcutHolder<>(getOrCreateRegistry(clazz)); + shortcuts.put(clazz.getType(), holder); + } + holder.register(shortcut, (ShortcutLoader) loader); + selfLoader.registerLoader(clazz.getType(), holder); + abstractConfigLoader.registerLoader(clazz.getType(), holder); + } return this; } @@ -388,15 +413,25 @@ public class ConfigPackImpl implements ConfigPack { return new OpenRegistryImpl<>(new LinkedHashMap<>(), CONFIG_TYPE_TYPE_KEY) { @Override public boolean register(@NotNull RegistryKey key, @NotNull ConfigType value) { - if(!registryMap - .containsKey(value.getTypeKey() - .getType())) { - OpenRegistry openRegistry = new OpenRegistryImpl<>(value.getTypeKey()); - selfLoader.registerLoader(value.getTypeKey().getType(), openRegistry); - abstractConfigLoader.registerLoader(value.getTypeKey().getType(), openRegistry); - registryMap.put(value.getTypeKey().getType(), new CheckedRegistryImpl<>(openRegistry)); + synchronized(registrationLock) { + if(!registryMap + .containsKey(value.getTypeKey() + .getType())) { + OpenRegistry openRegistry = new OpenRegistryImpl<>(value.getTypeKey()); + selfLoader.registerLoader(value.getTypeKey().getType(), openRegistry); + abstractConfigLoader.registerLoader(value.getTypeKey().getType(), openRegistry); + registryMap.put(value.getTypeKey().getType(), new CheckedRegistryImpl<>(openRegistry)); + } + return super.register(key, value); + } + } + + @Override + public void registerChecked(@NotNull RegistryKey key, @NotNull ConfigType value) { + // Same lock order as register: registrationLock, then the registry's own lock. + synchronized(registrationLock) { + super.registerChecked(key, value); } - return super.register(key, value); } }; } diff --git a/common/implementation/base/src/main/java/com/dfsek/terra/registry/OpenRegistryImpl.java b/common/implementation/base/src/main/java/com/dfsek/terra/registry/OpenRegistryImpl.java index 60bea757e..c95588bbf 100644 --- a/common/implementation/base/src/main/java/com/dfsek/terra/registry/OpenRegistryImpl.java +++ b/common/implementation/base/src/main/java/com/dfsek/terra/registry/OpenRegistryImpl.java @@ -20,14 +20,13 @@ package com.dfsek.terra.registry; import com.dfsek.tectonic.api.depth.DepthTracker; import com.dfsek.tectonic.api.exception.LoadException; import com.dfsek.tectonic.api.loader.ConfigLoader; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Multimaps; import org.jetbrains.annotations.NotNull; import java.lang.reflect.AnnotatedType; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -46,15 +45,20 @@ import com.dfsek.terra.api.util.reflection.TypeKey; /** * Registry implementation with read/write access. For internal use only. + *

+ * {@link #registerChecked} calls {@link #register} under a private lock: a subclass that locks in {@code register} must take + * that lock first in {@code registerChecked} too. * * @param */ public class OpenRegistryImpl implements OpenRegistry { private static final Entry NULL = new Entry<>(null); private final Map> objects; - private final ListMultimap>> objectIDs = Multimaps.newListMultimap(new ConcurrentHashMap<>(), - ArrayList::new); + /** Lists are immutable and replaced on write. */ + private final Map>>> objectIDs = new ConcurrentHashMap<>(); private final TypeKey typeKey; + /** Not {@code this}: {@code ConfigRegistry.loadAll} holds the monitor while workers register. */ + private final Object mutationLock = new Object(); public OpenRegistryImpl(TypeKey typeKey) { this(new ConcurrentHashMap<>(), typeKey); @@ -92,22 +96,34 @@ public class OpenRegistryImpl implements OpenRegistry { @Override public void registerChecked(@NotNull RegistryKey identifier, @NotNull T value) throws DuplicateEntryException { - if(objects.containsKey(identifier)) - throw new DuplicateEntryException("Value with identifier \"" + identifier + "\" is already defined in registry."); - register(identifier, value); + synchronized(mutationLock) { + if(objects.containsKey(identifier)) + throw new DuplicateEntryException("Value with identifier \"" + identifier + "\" is already defined in registry."); + register(identifier, value); + } } @Override public void clear() { - objects.clear(); - objectIDs.clear(); + synchronized(mutationLock) { + objects.clear(); + objectIDs.clear(); + } } private boolean register(RegistryKey identifier, Entry value) { - boolean exists = objects.containsKey(identifier); - objects.put(identifier, value); - objectIDs.put(identifier.getID(), Pair.of(identifier, value)); - return exists; + synchronized(mutationLock) { + boolean exists = objects.containsKey(identifier); + objects.put(identifier, value); + Pair> pair = Pair.of(identifier, value); + objectIDs.merge(identifier.getID(), List.of(pair), (existing, added) -> { + List>> merged = new ArrayList<>(existing.size() + 1); + merged.addAll(existing); + merged.add(pair); + return List.copyOf(merged); + }); + return exists; + } } @SuppressWarnings("unchecked") @@ -149,7 +165,7 @@ public class OpenRegistryImpl implements OpenRegistry { @Override public Map getMatches(String id) { return objectIDs - .get(id) + .getOrDefault(id, List.of()) .stream() .collect(HashMap::new, (map, pair) -> map.put(pair.getLeft(), pair.getRight().getValue()), Map::putAll); } diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/config/pack/ConfigPackRegistryConcurrencyTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/config/pack/ConfigPackRegistryConcurrencyTest.java new file mode 100644 index 000000000..6dc4a7a88 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/config/pack/ConfigPackRegistryConcurrencyTest.java @@ -0,0 +1,173 @@ +package com.dfsek.terra.config.pack; + +import com.dfsek.tectonic.api.loader.AbstractConfigLoader; +import com.dfsek.tectonic.api.loader.ConfigLoader; +import com.dfsek.tectonic.api.loader.type.TypeLoader; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.lang.reflect.Field; +import java.lang.reflect.Proxy; +import java.lang.reflect.Type; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import com.dfsek.terra.api.Platform; +import com.dfsek.terra.api.event.EventManager; +import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent; +import com.dfsek.terra.api.registry.CheckedRegistry; +import com.dfsek.terra.api.util.reflection.TypeKey; +import com.dfsek.terra.registry.CheckedRegistryImpl; +import com.dfsek.terra.registry.ShortcutHolder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; + + +class ConfigPackRegistryConcurrencyTest { + private static final int ITERATIONS = 60; + private static final int THREADS = 16; + private static final int TYPES = 96; + private static final int SHORTCUT_TYPES = 8; + + @TempDir + Path packDir; + + @Test + void concurrentRegistryCreation() throws Exception { + Files.writeString(packDir.resolve("pack.yml"), "id: TEST\n"); + List> keys = typeKeys(); + ExecutorService executor = Executors.newFixedThreadPool(THREADS); + try { + for(int iteration = 0; iteration < ITERATIONS; iteration++) { + hammer(newPack(), keys, executor, iteration); + } + } finally { + executor.shutdownNow(); + } + } + + private void hammer(ConfigPackImpl pack, List> keys, ExecutorService executor, int iteration) throws Exception { + CountDownLatch gate = new CountDownLatch(1); + List>>> futures = new ArrayList<>(); + for(int thread = 0; thread < THREADS; thread++) { + int id = thread; + futures.add(executor.submit(() -> { + List order = new ArrayList<>(); + for(int i = 0; i < TYPES; i++) order.add(i); + Collections.shuffle(order, new Random(iteration * 31L + id)); + List> seen = new ArrayList<>(Collections.nCopies(TYPES, null)); + gate.await(); + for(int i : order) { + TypeKey key = keys.get(i); + if(i < SHORTCUT_TYPES) pack.registerShortcut(key, "T" + id, (loader, input, tracker) -> input); + seen.set(i, pack.getOrCreateRegistry(key)); + } + return seen; + })); + } + gate.countDown(); + + List>> results = new ArrayList<>(); + for(Future>> future : futures) { + try { + results.add(future.get(30, TimeUnit.SECONDS)); + } catch(java.util.concurrent.ExecutionException e) { + fail("Iteration " + iteration + ": concurrent registry creation threw", e.getCause()); + } + } + + Map> selfLoaders = loaders(field(pack, "selfLoader", ConfigLoader.class)); + Map> abstractLoaders = loaders( + field(field(pack, "abstractConfigLoader", AbstractConfigLoader.class), "delegate", ConfigLoader.class)); + + for(int i = 0; i < TYPES; i++) { + Type type = keys.get(i).getType(); + CheckedRegistry registry = pack.getRegistry(type); + assertNotNull(registry, "Iteration " + iteration + ": registry lost for " + type.getTypeName()); + for(List> seen : results) { + assertSame(registry, seen.get(i), "Iteration " + iteration + ": registry created twice for " + type.getTypeName()); + } + TypeLoader selfLoader = selfLoaders.get(type); + if(i < SHORTCUT_TYPES) { + ShortcutHolder holder = assertInstanceOf(ShortcutHolder.class, selfLoader, + "Iteration " + iteration + ": shortcut loader missing for " + type.getTypeName()); + assertSame(holder, abstractLoaders.get(type)); + Map shortcuts = field(holder, "shortcuts", Map.class); + assertEquals(THREADS, shortcuts.size(), "Iteration " + iteration + ": shortcuts lost for " + type.getTypeName()); + } else { + Object open = ((CheckedRegistryImpl) registry).getRegistry(); + assertSame(open, selfLoader, "Iteration " + iteration + ": self loader not the registry for " + type.getTypeName()); + assertSame(open, abstractLoaders.get(type), + "Iteration " + iteration + ": abstract loader not the registry for " + type.getTypeName()); + } + } + } + + private ConfigPackImpl newPack() { + ConfigPackImpl[] captured = new ConfigPackImpl[1]; + EventManager events = (EventManager) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ EventManager.class }, + (proxy, method, args) -> { + if(method.getName().equals("callEvent")) { + if(args[0] instanceof ConfigPackPreLoadEvent preLoad) { + captured[0] = (ConfigPackImpl) preLoad.getPack(); + throw new StopLoad(); + } + return args[0]; + } + return null; + }); + Platform platform = (Platform) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ Platform.class }, + (proxy, method, args) -> method.getName().equals("getEventManager") ? events : null); + try { + new ConfigPackImpl(packDir, platform); + fail("pack load should stop at pre-load"); + } catch(StopLoad expected) { + } catch(Exception e) { + throw new AssertionError(e); + } + return captured[0]; + } + + @SuppressWarnings("unchecked") + private static List> typeKeys() throws ClassNotFoundException { + List> keys = new ArrayList<>(); + String[] components = { "Ljava.lang.Object;", "Ljava.lang.String;", "I", "J" }; + for(int depth = 1; keys.size() < TYPES; depth++) { + for(String component : components) { + if(keys.size() < TYPES) keys.add(TypeKey.of((Class) Class.forName("[".repeat(depth) + component))); + } + } + return keys; + } + + @SuppressWarnings("unchecked") + private static Map> loaders(ConfigLoader loader) throws ReflectiveOperationException { + return field(loader, "loaders", Map.class); + } + + private static T field(Object owner, String name, Class type) throws ReflectiveOperationException { + Field field = owner.getClass().getDeclaredField(name); + field.setAccessible(true); + return type.cast(field.get(owner)); + } + + private static final class StopLoad extends RuntimeException { + StopLoad() { + super(null, null, false, false); + } + } +} diff --git a/common/implementation/base/src/test/java/com/dfsek/terra/registry/master/ConfigRegistryConcurrencyTest.java b/common/implementation/base/src/test/java/com/dfsek/terra/registry/master/ConfigRegistryConcurrencyTest.java new file mode 100644 index 000000000..2c2bb3571 --- /dev/null +++ b/common/implementation/base/src/test/java/com/dfsek/terra/registry/master/ConfigRegistryConcurrencyTest.java @@ -0,0 +1,141 @@ +package com.dfsek.terra.registry.master; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import com.dfsek.terra.api.config.ConfigPack; +import com.dfsek.terra.api.registry.exception.DuplicateEntryException; +import com.dfsek.terra.api.registry.key.RegistryKey; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +class ConfigRegistryConcurrencyTest { + private static final int ITERATIONS = 200; + private static final int THREADS = 16; + + @Test + void concurrentDuplicatePacks() throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(THREADS); + List failures = new ArrayList<>(); + try { + for(int iteration = 0; iteration < ITERATIONS; iteration++) { + ConfigRegistry registry = new ConfigRegistry(); + RegistryKey key = RegistryKey.of("terra", "PACK"); + List packs = new ArrayList<>(); + for(int thread = 0; thread < THREADS; thread++) packs.add(pack()); + List results = race(executor, THREADS, thread -> registry.registerChecked(key, packs.get(thread))); + + List winners = new ArrayList<>(); + int duplicates = 0; + for(int thread = 0; thread < THREADS; thread++) { + Object result = results.get(thread); + if(result == null) { + winners.add(packs.get(thread)); + } else if(result instanceof DuplicateEntryException e) { + assertEquals("Value with identifier \"terra:PACK\" is already defined in registry.", e.getMessage()); + duplicates++; + } else { + throw new AssertionError("unexpected failure", (Throwable) result); + } + } + if(winners.size() != 1 || duplicates != THREADS - 1) { + failures.add("iteration " + iteration + ": " + winners.size() + " registered, " + duplicates + " duplicates"); + continue; + } + assertSame(winners.getFirst(), registry.get(key).orElseThrow(), "iteration " + iteration); + assertSame(winners.getFirst(), registry.getByID("PACK").orElseThrow(), "iteration " + iteration); + assertEquals(1, registry.getMatches("PACK").size(), "iteration " + iteration); + } + } finally { + executor.shutdownNow(); + } + assertTrue(failures.isEmpty(), failures.size() + "/" + ITERATIONS + " iterations raced: " + failures); + } + + @Test + void concurrentPacksSharingId() throws Exception { + ExecutorService executor = Executors.newFixedThreadPool(THREADS); + List failures = new ArrayList<>(); + try { + for(int iteration = 0; iteration < ITERATIONS; iteration++) { + ConfigRegistry registry = new ConfigRegistry(); + List packs = new ArrayList<>(); + for(int thread = 0; thread < THREADS; thread++) packs.add(pack()); + List results = race(executor, THREADS, + thread -> registry.registerChecked(RegistryKey.of("ns" + thread, "PACK"), packs.get(thread))); + for(Object result : results) { + if(result != null) throw new AssertionError("unexpected failure", (Throwable) result); + } + + Map matches = registry.getMatches("PACK"); + boolean complete = matches.size() == THREADS; + for(int thread = 0; thread < THREADS && complete; thread++) { + complete = matches.get(RegistryKey.of("ns" + thread, "PACK")) == packs.get(thread); + } + if(!complete) failures.add("iteration " + iteration + ": " + matches.size() + "/" + THREADS + " found by ID"); + assertEquals(THREADS, registry.keys().size(), "iteration " + iteration); + } + } finally { + executor.shutdownNow(); + } + assertTrue(failures.isEmpty(), failures.size() + "/" + ITERATIONS + " iterations lost entries: " + failures); + } + + private static List race(ExecutorService executor, int threads, ThreadAction action) throws Exception { + CountDownLatch ready = new CountDownLatch(threads); + CountDownLatch gate = new CountDownLatch(1); + List> futures = new ArrayList<>(); + for(int thread = 0; thread < threads; thread++) { + int id = thread; + futures.add(executor.submit(() -> { + ready.countDown(); + gate.await(); + try { + action.run(id); + return null; + } catch(RuntimeException e) { + return e; + } + })); + } + ready.await(); + gate.countDown(); + List results = new ArrayList<>(); + for(Future future : futures) { + try { + results.add(future.get(30, TimeUnit.SECONDS)); + } catch(ExecutionException e) { + throw new AssertionError(e.getCause()); + } + } + return results; + } + + private static ConfigPack pack() { + return (ConfigPack) Proxy.newProxyInstance(ConfigRegistryConcurrencyTest.class.getClassLoader(), new Class[]{ ConfigPack.class }, + (proxy, method, args) -> switch(method.getName()) { + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + case "toString" -> "pack@" + Integer.toHexString(System.identityHashCode(proxy)); + default -> null; + }); + } + + @FunctionalInterface + private interface ThreadAction { + void run(int thread); + } +}