fix: make config pack registration thread-safe

This commit is contained in:
Zoe Gidiere committed 2026-11-09 16:34:50 -07:00
1 parent bebcb775fc
commit 2f36b2d5c4
5 files changed
+413 -45

No files matched your search

@@ -40,6 +40,8 @@ public class TerraScriptAddon implements AddonInitializer {
.then(event -> {
CheckedRegistry<Structure> structureRegistry = event.getPack().getOrCreateRegistry(Structure.class);
CheckedRegistry<LootTable> lootRegistry = event.getPack().getOrCreateRegistry(LootTable.class);
// Pack registries must not be created from worker threads.
CheckedRegistry<FunctionBuilder> 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);
@@ -111,7 +111,12 @@ public class ConfigPackImpl implements ConfigPack {
private final BiomeTagIndex biomeTagIndex = new BiomeTagIndex();
private final Map<Type, CheckedRegistryImpl<?>> 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<Type, CheckedRegistryImpl<?>> registryMap = new ConcurrentHashMap<>();
private final Map<Type, ShortcutHolder<?>> shortcuts = new HashMap<>();
private final OpenRegistry<ConfigType<?, ?>> configTypeRegistry;
@@ -266,33 +271,41 @@ public class ConfigPackImpl implements ConfigPack {
@Override
public <T> ConfigPackImpl applyLoader(Type type, TypeLoader<T> loader) {
abstractConfigLoader.registerLoader(type, loader);
selfLoader.registerLoader(type, loader);
synchronized(registrationLock) {
abstractConfigLoader.registerLoader(type, loader);
selfLoader.registerLoader(type, loader);
}
return this;
}
@Override
public <T> ConfigPackImpl applyLoader(Type type, Supplier<ObjectTemplate<T>> 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<RegistryKey> 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<RegistryKey> 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 <T> CheckedRegistry<T> getOrCreateRegistry(TypeKey<T> typeKey) {
return (CheckedRegistry<T>) registryMap.computeIfAbsent(typeKey.getType(), c -> {
Type c = typeKey.getType();
CheckedRegistryImpl<?> existing = registryMap.get(c);
if(existing != null) return (CheckedRegistry<T>) existing;
synchronized(registrationLock) {
existing = registryMap.get(c);
if(existing != null) return (CheckedRegistry<T>) existing;
OpenRegistry<T> 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<T> checked = new CheckedRegistryImpl<>(registry);
registryMap.put(c, checked);
return checked;
}
}
@Override
@@ -371,11 +391,16 @@ public class ConfigPackImpl implements ConfigPack {
@SuppressWarnings("rawtypes")
@Override
public <T> ConfigPack registerShortcut(TypeKey<T> clazz, String shortcut, ShortcutLoader<T> 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);
}
};
}
@@ -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.
* <p>
* {@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 <T>
*/
public class OpenRegistryImpl<T> implements OpenRegistry<T> {
private static final Entry<?> NULL = new Entry<>(null);
private final Map<RegistryKey, Entry<T>> objects;
private final ListMultimap<String, Pair<RegistryKey, Entry<T>>> objectIDs = Multimaps.newListMultimap(new ConcurrentHashMap<>(),
ArrayList::new);
/** Lists are immutable and replaced on write. */
private final Map<String, List<Pair<RegistryKey, Entry<T>>>> objectIDs = new ConcurrentHashMap<>();
private final TypeKey<T> typeKey;
/** Not {@code this}: {@code ConfigRegistry.loadAll} holds the monitor while workers register. */
private final Object mutationLock = new Object();
public OpenRegistryImpl(TypeKey<T> typeKey) {
this(new ConcurrentHashMap<>(), typeKey);
@@ -92,22 +96,34 @@ public class OpenRegistryImpl<T> implements OpenRegistry<T> {
@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<T> 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<RegistryKey, Entry<T>> pair = Pair.of(identifier, value);
objectIDs.merge(identifier.getID(), List.of(pair), (existing, added) -> {
List<Pair<RegistryKey, Entry<T>>> 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<T> implements OpenRegistry<T> {
@Override
public Map<RegistryKey, T> 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);
}
@@ -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<TypeKey<Object>> 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<TypeKey<Object>> keys, ExecutorService executor, int iteration) throws Exception {
CountDownLatch gate = new CountDownLatch(1);
List<Future<List<CheckedRegistry<Object>>>> futures = new ArrayList<>();
for(int thread = 0; thread < THREADS; thread++) {
int id = thread;
futures.add(executor.submit(() -> {
List<Integer> order = new ArrayList<>();
for(int i = 0; i < TYPES; i++) order.add(i);
Collections.shuffle(order, new Random(iteration * 31L + id));
List<CheckedRegistry<Object>> seen = new ArrayList<>(Collections.nCopies(TYPES, null));
gate.await();
for(int i : order) {
TypeKey<Object> 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<List<CheckedRegistry<Object>>> results = new ArrayList<>();
for(Future<List<CheckedRegistry<Object>>> 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<Type, TypeLoader<?>> selfLoaders = loaders(field(pack, "selfLoader", ConfigLoader.class));
Map<Type, TypeLoader<?>> 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<Object> registry = pack.getRegistry(type);
assertNotNull(registry, "Iteration " + iteration + ": registry lost for " + type.getTypeName());
for(List<CheckedRegistry<Object>> 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<Object>) 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<TypeKey<Object>> typeKeys() throws ClassNotFoundException {
List<TypeKey<Object>> 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<Object>) Class.forName("[".repeat(depth) + component)));
}
}
return keys;
}
@SuppressWarnings("unchecked")
private static Map<Type, TypeLoader<?>> loaders(ConfigLoader loader) throws ReflectiveOperationException {
return field(loader, "loaders", Map.class);
}
private static <T> T field(Object owner, String name, Class<T> 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);
}
}
}
@@ -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<String> failures = new ArrayList<>();
try {
for(int iteration = 0; iteration < ITERATIONS; iteration++) {
ConfigRegistry registry = new ConfigRegistry();
RegistryKey key = RegistryKey.of("terra", "PACK");
List<ConfigPack> packs = new ArrayList<>();
for(int thread = 0; thread < THREADS; thread++) packs.add(pack());
List<Object> results = race(executor, THREADS, thread -> registry.registerChecked(key, packs.get(thread)));
List<ConfigPack> 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<String> failures = new ArrayList<>();
try {
for(int iteration = 0; iteration < ITERATIONS; iteration++) {
ConfigRegistry registry = new ConfigRegistry();
List<ConfigPack> packs = new ArrayList<>();
for(int thread = 0; thread < THREADS; thread++) packs.add(pack());
List<Object> 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<RegistryKey, ConfigPack> 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<Object> race(ExecutorService executor, int threads, ThreadAction action) throws Exception {
CountDownLatch ready = new CountDownLatch(threads);
CountDownLatch gate = new CountDownLatch(1);
List<Future<Object>> 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<Object> results = new ArrayList<>();
for(Future<Object> 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);
}
}