Skip to content

Commit ea69f3b

Browse files
committed
Preserve YAML publication results across aliases and cleanup faults
1 parent ec2b8fb commit ea69f3b

4 files changed

Lines changed: 73 additions & 4 deletions

File tree

‎SimpleAPI/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,12 @@
309309
<version>5.24.0</version>
310310
<scope>test</scope>
311311
</dependency>
312+
<dependency>
313+
<groupId>com.google.jimfs</groupId>
314+
<artifactId>jimfs</artifactId>
315+
<version>1.3.2</version>
316+
<scope>test</scope>
317+
</dependency>
312318
<dependency>
313319
<groupId>com.zaxxer</groupId>
314320
<artifactId>HikariCP</artifactId>

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ 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.
61+
// Serialize publication per canonical parent, including case-alias target names.
6262
private static final Object[] WRITE_LOCKS = new Object[64];
6363
static {
6464
for (int index = 0; index < WRITE_LOCKS.length; index++) WRITE_LOCKS[index] = new Object();
@@ -73,7 +73,7 @@ public final class YamlConfigDocument implements ConfigDocument {
7373
private YamlConfigDocument(Path path, int maxBytes) {
7474
this.path = path;
7575
this.maxBytes = maxBytes;
76-
this.writeLock = WRITE_LOCKS[Math.floorMod(path.hashCode(), WRITE_LOCKS.length)];
76+
this.writeLock = WRITE_LOCKS[Math.floorMod(path.getParent().hashCode(), WRITE_LOCKS.length)];
7777
}
7878

7979
public static YamlConfigDocument open(Path path) throws IOException { return open(path, DEFAULT_MAX_BYTES); }
@@ -208,6 +208,7 @@ private void replaceLocked(byte[] encoded, boolean initializeOnly) throws IOExce
208208
: Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS);
209209
}
210210
Path temporary = Files.createTempFile(path.getParent(), ".simpleapi-config-", ".tmp");
211+
boolean committed = false;
211212
try {
212213
if (permissions != null) Files.setPosixFilePermissions(temporary, permissions);
213214
try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
@@ -226,8 +227,14 @@ private void replaceLocked(byte[] encoded, boolean initializeOnly) throws IOExce
226227
} else {
227228
Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
228229
}
230+
committed = true;
229231
} finally {
230-
Files.deleteIfExists(temporary);
232+
try { Files.deleteIfExists(temporary); }
233+
catch (IOException | SecurityException cleanupFailure) {
234+
// Publication already succeeded: do not report a failed write or retain old active data.
235+
// An unremovable staged sibling may require application-owned directory cleanup.
236+
if (!committed) throw cleanupFailure;
237+
}
231238
}
232239
}
233240

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

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import static org.junit.jupiter.api.Assertions.*;
44
import static org.junit.jupiter.api.Assumptions.assumeTrue;
5+
import static org.mockito.Mockito.*;
6+
import static org.mockito.ArgumentMatchers.argThat;
57

68
import java.io.ByteArrayInputStream;
79
import java.io.IOException;
@@ -20,6 +22,8 @@
2022
import org.junit.jupiter.api.io.TempDir;
2123

2224
import com.bencodez.simpleapi.core.config.YamlConfiguration;
25+
import com.google.common.jimfs.Configuration;
26+
import com.google.common.jimfs.Jimfs;
2327

2428
class YamlConfigurationTest {
2529
@TempDir Path directory;
@@ -197,6 +201,54 @@ private static Integer initialize(Path path, String text, CyclicBarrier gate) th
197201
catch (IOException stale) { return null; }
198202
}
199203

204+
@Test void caseAliasTargetsOnCaseInsensitiveStoreCannotLoseConcurrentEdits() throws Exception {
205+
var workers = Executors.newFixedThreadPool(2);
206+
try (var filesystem = Jimfs.newFileSystem(Configuration.osX().toBuilder()
207+
.setPathEqualityUsesCanonicalForm(false).build())) {
208+
Path parent = filesystem.getPath("/config");
209+
Files.createDirectory(parent);
210+
for (int trial = 0; trial < 50; trial++) {
211+
Path firstPath = parent.resolve("Settings-" + trial + ".yml");
212+
Path secondPath = parent.resolve("settings-" + trial + ".yml");
213+
Files.writeString(firstPath, "First: 0\nSecond: 0\n");
214+
assertNotEquals(firstPath, secondPath, "Paths must retain spelling-sensitive equality");
215+
assertNotEquals(firstPath.hashCode(), secondPath.hashCode());
216+
assertTrue(Files.isSameFile(firstPath, secondPath), "Store must resolve case aliases");
217+
var first = YamlConfiguration.load(firstPath);
218+
var second = YamlConfiguration.load(secondPath);
219+
var gate = new CyclicBarrier(2);
220+
var one = workers.submit(() -> editAtBarrier(first, "First", gate));
221+
var two = workers.submit(() -> editAtBarrier(second, "Second", gate));
222+
boolean firstSucceeded = one.get(10, TimeUnit.SECONDS);
223+
boolean secondSucceeded = two.get(10, TimeUnit.SECONDS);
224+
assertNotEquals(firstSucceeded, secondSucceeded, "Case aliases must share revision coordination");
225+
var disk = YamlConfiguration.load(firstPath);
226+
assertEquals(firstSucceeded ? 1 : 0, disk.getInt("First"));
227+
assertEquals(secondSucceeded ? 1 : 0, disk.getInt("Second"));
228+
}
229+
} finally {
230+
workers.shutdownNow();
231+
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
232+
}
233+
}
234+
235+
@Test void committedResourceInitializationRemainsSuccessfulAfterUnlinkFailure() throws Exception {
236+
try (var files = mockStatic(Files.class, CALLS_REAL_METHODS)) {
237+
files.when(() -> Files.deleteIfExists(argThat((Path staged) -> staged != null
238+
&& staged.getFileName().toString().startsWith(".simpleapi-config-"))))
239+
.thenThrow(new IOException("synthetic staged unlink failure"));
240+
var config = YamlConfiguration.load(path(), new TrackedStream("Points: 7\n"));
241+
assertEquals(7, config.getInt("Points"));
242+
assertEquals(config.snapshot().revision(), YamlConfiguration.load(path()).snapshot().revision());
243+
assertEquals("Points: 7\n", Files.readString(path()));
244+
}
245+
try (var children = Files.list(directory)) {
246+
var staged = children.filter(file -> file.getFileName().toString().startsWith(".simpleapi-config-")).toList();
247+
assertEquals(1, staged.size(), "Injected cleanup failure should leave exactly its staged sibling");
248+
for (Path file : staged) Files.delete(file);
249+
}
250+
}
251+
200252
private static boolean editAtBarrier(YamlConfiguration config, String key, CyclicBarrier gate) throws Exception {
201253
try {
202254
config.update(edit -> {

‎docs/neoforge-configuration.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,9 +153,13 @@ snapshot. External edits, stale revisions, serialization limits and filesystem
153153
failures are reported instead of truncating the original file. Reload after an
154154
external edit before retrying. Old snapshots remain detached across updates.
155155
Document instances from the same defining classloader coordinate final revision
156-
checks and publication by canonical path, so stale same-process writers cannot
156+
checks and publication by canonical parent directory, including case-alias target
157+
names, so stale same-process writers cannot
157158
both succeed and silently lose one edit. Cross-process writer exclusion remains
158159
the application's responsibility.
160+
After successful publication, a temporary-sibling deletion failure does not undo
161+
the committed result or make the operation report failure. Such a sibling may
162+
require application-owned directory cleanup after the filesystem fault is resolved.
159163

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

0 commit comments

Comments
 (0)