Skip to content

Commit ec2b8fb

Browse files
committed
Coordinate YAML publication across same-path documents
1 parent 1711be5 commit ec2b8fb

3 files changed

Lines changed: 109 additions & 2 deletions

File tree

‎SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,22 @@ public final class YamlConfigDocument implements ConfigDocument {
5858
public static final int DEFAULT_MAX_BYTES = 1024 * 1024;
5959
private static final int MAX_NODES = 100_000;
6060
private static final int MAX_DEPTH = 64;
61+
// Bounded same-classloader coordination, shared by every document for a canonical path.
62+
private static final Object[] WRITE_LOCKS = new Object[64];
63+
static {
64+
for (int index = 0; index < WRITE_LOCKS.length; index++) WRITE_LOCKS[index] = new Object();
65+
}
6166
private final Path path;
6267
private final int maxBytes;
68+
private final Object writeLock;
6369
private ConfigurationNode root;
6470
private String revision;
6571
private boolean editing;
6672

6773
private YamlConfigDocument(Path path, int maxBytes) {
6874
this.path = path;
6975
this.maxBytes = maxBytes;
76+
this.writeLock = WRITE_LOCKS[Math.floorMod(path.hashCode(), WRITE_LOCKS.length)];
7077
}
7178

7279
public static YamlConfigDocument open(Path path) throws IOException { return open(path, DEFAULT_MAX_BYTES); }
@@ -93,7 +100,7 @@ synchronized ConfigSnapshot initializeFrom(byte[] bytes) throws IOException {
93100
if (bytes.length > maxBytes) throw new IOException("Default configuration exceeds byte limit");
94101
ConfigurationNode candidate = parse(bytes);
95102
ConfigSnapshot result = new ConfigSnapshot(revisionOf(bytes), new ConfigurateConfigView(candidate.copy()));
96-
replace(bytes);
103+
replace(bytes, true);
97104
root = candidate;
98105
revision = result.revision();
99106
return result;
@@ -183,6 +190,16 @@ private byte[] serialize(ConfigurationNode candidate) throws IOException {
183190
}
184191

185192
private void replace(byte[] encoded) throws IOException {
193+
replace(encoded, false);
194+
}
195+
196+
private void replace(byte[] encoded, boolean initializeOnly) throws IOException {
197+
synchronized (writeLock) {
198+
replaceLocked(encoded, initializeOnly);
199+
}
200+
}
201+
202+
private void replaceLocked(byte[] encoded, boolean initializeOnly) throws IOException {
186203
requireUnchanged();
187204
Set<PosixFilePermission> permissions = null;
188205
if (Files.getFileAttributeView(path.getParent(), java.nio.file.attribute.PosixFileAttributeView.class) != null) {
@@ -199,7 +216,16 @@ private void replace(byte[] encoded) throws IOException {
199216
channel.force(true);
200217
}
201218
requireUnchanged();
202-
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
219+
if (initializeOnly) {
220+
// ATOMIC_MOVE is allowed to replace an existing target even without REPLACE_EXISTING.
221+
// A hard link publishes the complete staged inode only if the destination is absent.
222+
try { Files.createLink(path, temporary); }
223+
catch (UnsupportedOperationException unsupported) {
224+
throw new IOException("Atomic missing-file initialization is not supported", unsupported);
225+
}
226+
} else {
227+
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
228+
}
203229
} finally {
204230
Files.deleteIfExists(temporary);
205231
}

‎SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
import java.nio.file.attribute.PosixFileAttributeView;
1313
import java.nio.file.attribute.PosixFilePermission;
1414
import java.util.Set;
15+
import java.util.concurrent.CyclicBarrier;
16+
import java.util.concurrent.Executors;
17+
import java.util.concurrent.TimeUnit;
1518

1619
import org.junit.jupiter.api.Test;
1720
import org.junit.jupiter.api.io.TempDir;
@@ -140,6 +143,78 @@ class YamlConfigurationTest {
140143
assertEquals(8, YamlConfiguration.load(path()).getInt("Points"));
141144
}
142145

146+
@Test void simultaneousFirstLoadsCannotBothPublishDifferentDefaults() throws Exception {
147+
var workers = Executors.newFixedThreadPool(2);
148+
try {
149+
for (int trial = 0; trial < 50; trial++) {
150+
Path path = directory.resolve("initialize-" + trial + ".yml");
151+
var gate = new CyclicBarrier(2);
152+
var first = workers.submit(() -> initialize(path, "Points: 1\n", gate));
153+
var second = workers.submit(() -> initialize(path, "Points: 2\n", gate));
154+
Integer one = first.get(10, TimeUnit.SECONDS);
155+
Integer two = second.get(10, TimeUnit.SECONDS);
156+
assertNotEquals(one == null, two == null, "Exactly one missing-file initializer must succeed");
157+
assertEquals(one == null ? two.intValue() : one.intValue(), YamlConfiguration.load(path).getInt("Points"));
158+
}
159+
} finally {
160+
workers.shutdownNow();
161+
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
162+
}
163+
}
164+
165+
@Test void simultaneousSameRevisionEditsCannotBothSucceedAndLoseOneChange() throws Exception {
166+
var workers = Executors.newFixedThreadPool(2);
167+
try {
168+
for (int trial = 0; trial < 50; trial++) {
169+
Path path = directory.resolve("update-" + trial + ".yml");
170+
Files.writeString(path, "First: 0\nSecond: 0\n");
171+
var first = YamlConfiguration.load(path);
172+
var second = YamlConfiguration.load(path);
173+
var gate = new CyclicBarrier(2);
174+
var one = workers.submit(() -> editAtBarrier(first, "First", gate));
175+
var two = workers.submit(() -> editAtBarrier(second, "Second", gate));
176+
boolean firstSucceeded = one.get(10, TimeUnit.SECONDS);
177+
boolean secondSucceeded = two.get(10, TimeUnit.SECONDS);
178+
assertNotEquals(firstSucceeded, secondSucceeded, "One stale writer must be rejected");
179+
var disk = YamlConfiguration.load(path);
180+
assertEquals(firstSucceeded ? 1 : 0, disk.getInt("First"));
181+
assertEquals(secondSucceeded ? 1 : 0, disk.getInt("Second"));
182+
}
183+
} finally {
184+
workers.shutdownNow();
185+
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
186+
}
187+
}
188+
189+
private static Integer initialize(Path path, String text, CyclicBarrier gate) throws Exception {
190+
InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)) {
191+
@Override public byte[] readNBytes(int limit) throws IOException {
192+
await(gate);
193+
return super.readNBytes(limit);
194+
}
195+
};
196+
try { return YamlConfiguration.load(path, stream).getInt("Points"); }
197+
catch (IOException stale) { return null; }
198+
}
199+
200+
private static boolean editAtBarrier(YamlConfiguration config, String key, CyclicBarrier gate) throws Exception {
201+
try {
202+
config.update(edit -> {
203+
try { await(gate); } catch (IOException failure) { throw new AssertionError(failure); }
204+
edit.set(key, 1);
205+
});
206+
return true;
207+
} catch (IOException stale) { return false; }
208+
}
209+
210+
private static void await(CyclicBarrier gate) throws IOException {
211+
try { gate.await(5, TimeUnit.SECONDS); }
212+
catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException(interrupted); }
213+
catch (java.util.concurrent.BrokenBarrierException | java.util.concurrent.TimeoutException failure) {
214+
throw new IOException(failure);
215+
}
216+
}
217+
143218
private static final class TrackedStream extends ByteArrayInputStream {
144219
private final int initialSize;
145220
private boolean closed;

‎docs/neoforge-configuration.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ bounded validation. Existing files, including intentionally empty files, are nev
9898
replaced or merged with resource defaults. An existing file does not require the
9999
resource to exist. There is no resource default-tree overlay; use getter defaults
100100
for absent options and explicit updates for intentional migrations.
101+
Resource initialization atomically publishes a staged file only if absent, using
102+
a same-directory hard link; unsupported filesystems fail without an unsafe fallback.
101103

102104
`load(path, inputStream)` also supports missing-file defaults and always closes the
103105
supplied stream, including on failure. Read/close failures precede initialization.
@@ -150,6 +152,10 @@ temporary sibling followed by atomic replacement. Failed updates retain the acti
150152
snapshot. External edits, stale revisions, serialization limits and filesystem
151153
failures are reported instead of truncating the original file. Reload after an
152154
external edit before retrying. Old snapshots remain detached across updates.
155+
Document instances from the same defining classloader coordinate final revision
156+
checks and publication by canonical path, so stale same-process writers cannot
157+
both succeed and silently lose one edit. Cross-process writer exclusion remains
158+
the application's responsibility.
153159

154160
Defaults are 1 MiB input/output (configurable up to 16 MiB), 64 levels and 100,000
155161
nodes. The parent directory must exist and be trusted; the application owns

0 commit comments

Comments
 (0)