From 8ba526a0a45ed82c2c83f55abe6dab5f404dc1df Mon Sep 17 00:00:00 2001 From: BenCodez <17074231+BenCodez@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:56:25 +0000 Subject: [PATCH 1/4] Document neutral YAML consumption for NeoForge --- .../tests/shared/NativeYamlFixture.java | 104 ++++++++++++++ .../tests/shared/NativeYamlTest.java | 51 +++++++ .../tests/shared/SharedArtifactTest.java | 3 + .../tests/shared/SharedRuntimeClasspath.java | 3 +- docs/neoforge-configuration.md | 131 ++++++++++++++++++ docs/platform-neutral-configuration.md | 5 + 6 files changed, 296 insertions(+), 1 deletion(-) create mode 100644 SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlFixture.java create mode 100644 SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlTest.java create mode 100644 docs/neoforge-configuration.md diff --git a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlFixture.java b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlFixture.java new file mode 100644 index 0000000..fa1179e --- /dev/null +++ b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlFixture.java @@ -0,0 +1,104 @@ +package com.bencodez.simpleapi.tests.shared; + +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; +import java.util.Map; + +import com.bencodez.simpleapi.core.config.CaseInsensitiveConfigView; +import com.bencodez.simpleapi.core.config.ConfigurateConfigView; +import com.bencodez.simpleapi.core.config.ConfigurateStructuredConfigView; +import com.bencodez.simpleapi.core.config.StructuredConfigView.Kind; +import com.bencodez.simpleapi.core.config.YamlConfigDocument; + +/** Exercises the native YAML consumption contract without any platform or JUnit classes. */ +public final class NativeYamlFixture { + private NativeYamlFixture() { } + + public static void run() throws Exception { + var directory = Files.createTempDirectory("simpleapi-native-yaml-"); + var path = directory.resolve("settings.yml"); + try { + var missing = YamlConfigDocument.open(path); + require("missing".equals(missing.snapshot().revision()) && !Files.exists(path), "Read created a file"); + String original = """ + Points: 7 + Quoted: '12' + Enabled: false + Empty: [] + Rewards: + 10: + Commands: [say voted, 2, true] + 'some.site': + Value: literal + Unknown: preserve + """; + Files.writeString(path, original); + var document = YamlConfigDocument.open(path, 1024); + var before = document.snapshot(); + var typed = before.view(); + require(typed.getInt("Points", -1) == 7, "Numeric read changed"); + require(typed.getInt("Quoted", 99) == 99, "Quoted number was coerced"); + require(!typed.getBoolean("Enabled", true), "False was replaced with a default"); + require(typed.getInt("Absent", 42) == 42 && !typed.contains("Absent"), "Missing default changed"); + require(typed.getInt("points", 99) == 99, "Ordinary reads lost case sensitivity"); + require(typed.getStringList("Rewards.10.Commands").equals(List.of("say voted", "2", "true")), + "Legacy scalar-list conversion changed"); + var structured = new ConfigurateStructuredConfigView((ConfigurateConfigView) typed); + require(structured.kind("Empty") == Kind.LIST && structured.kind("Absent") == Kind.MISSING, + "Empty and missing values became indistinguishable"); + require("literal".equals(structured.at("some.site").getString("Value", "")), "Literal key split"); + var insensitive = new CaseInsensitiveConfigView(structured); + require(insensitive.getInt("POINTS", -1) == 7, "Case-insensitive wrapper failed"); + var exported = structured.snapshotValues(); + try { + exported.put("Points", 99); + throw new AssertionError("Structured export is mutable"); + } catch (UnsupportedOperationException expected) { } + var after = document.update(before.revision(), edit -> { + edit.set("Points", 8); + edit.set("Rewards.10.Commands", List.of("say updated")); + edit.setAt(Map.of("Value", "updated literal"), "some.site"); + }); + require(before.view().getInt("Points", -1) == 7 && exported.get("Points").equals(7), + "A published snapshot changed after editing"); + require("preserve".equals(after.view().getString("Unknown", "")), "Unknown key lost"); + var reopened = YamlConfigDocument.open(path).snapshot(); + require(after.revision().equals(reopened.revision()) && reopened.view().getInt("Points", -1) == 8, + "Persisted revision/value mismatch"); + require(reopened.view().getConfigurationSection("Rewards").getKeys(false).equals(java.util.Set.of("10")), + "Numeric key duplicated"); + require("updated literal".equals(new ConfigurateStructuredConfigView( + (ConfigurateConfigView) reopened.view()).at("some.site").getString("Value", "")), + "Literal edit did not survive reopening"); + String lastGood = Files.readString(path); + expectIo(() -> document.update(after.revision(), edit -> edit.set("Large", "x".repeat(2048)))); + require(lastGood.equals(Files.readString(path)), "Failed bounded write changed file bytes"); + require(after.revision().equals(document.snapshot().revision()), "Failed write published state"); + String malformed = "Points: [unterminated"; + Files.writeString(path, malformed); + expectIo(document::reload); + require(after.revision().equals(document.snapshot().revision()) + && document.snapshot().view().getInt("Points", -1) == 8, "Failed reload published state"); + expectIo(() -> document.update(after.revision(), edit -> edit.set("Points", 9))); + require(malformed.equals(Files.readString(path)), "Stale write overwrote malformed external edit"); + expectIo(() -> YamlConfigDocument.open(path)); + Files.writeString(path, "Points: 11\n"); + require(document.reload().view().getInt("Points", -1) == 11, "Reload failed to recover"); + } finally { + Files.deleteIfExists(path); + Files.deleteIfExists(directory); + } + } + + @FunctionalInterface private interface IoOperation { void run() throws IOException; } + + private static void expectIo(IoOperation operation) throws IOException { + try { operation.run(); } catch (IOException expected) { return; } + throw new AssertionError("Expected IOException"); + } + + private static void require(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } +} diff --git a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlTest.java b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlTest.java new file mode 100644 index 0000000..87ab108 --- /dev/null +++ b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlTest.java @@ -0,0 +1,51 @@ +package com.bencodez.simpleapi.tests.shared; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFileAttributeView; +import java.nio.file.attribute.PosixFilePermission; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.bencodez.simpleapi.core.config.YamlConfigDocument; + +class NativeYamlTest { + @TempDir Path directory; + + @Test void nativeYamlConsumptionContract() throws Exception { + NativeYamlFixture.run(); + } + + @Test void unwritableParentPreservesFileAndSnapshotAndAllowsRetry() throws Exception { + assumeTrue(Files.getFileAttributeView(directory, PosixFileAttributeView.class) != null); + Path path = directory.resolve("settings.yml"); + String original = "Points: 7\n"; + Files.writeString(path, original); + var document = YamlConfigDocument.open(path); + var before = document.snapshot(); + var permissions = Files.getPosixFilePermissions(directory); + try { + Files.setPosixFilePermissions(directory, + Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_EXECUTE)); + assumeTrue(!Files.isWritable(directory), "Process can bypass directory permissions"); + assertThrows(IOException.class, + () -> document.update(before.revision(), edit -> edit.set("Points", 8))); + assertEquals(original, Files.readString(path)); + assertEquals(before.revision(), document.snapshot().revision()); + assertEquals(7, document.snapshot().view().getInt("Points", -1)); + try (var children = Files.list(directory)) { assertEquals(List.of(path), children.toList()); } + } finally { + Files.setPosixFilePermissions(directory, permissions); + } + assertEquals(8, document.update(before.revision(), edit -> edit.set("Points", 8)) + .view().getInt("Points", -1)); + assertEquals(8, YamlConfigDocument.open(path).snapshot().view().getInt("Points", -1)); + } +} diff --git a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedArtifactTest.java b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedArtifactTest.java index 8744267..720c7e6 100644 --- a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedArtifactTest.java +++ b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedArtifactTest.java @@ -56,6 +56,9 @@ public class SharedArtifactTest { Class fixture = loader.loadClass(NativeConfigFixture.class.getName()); assertSame(loader, fixture.getClassLoader()); fixture.getMethod("run").invoke(null); + Class yamlFixture = loader.loadClass(NativeYamlFixture.class.getName()); + assertSame(loader, yamlFixture.getClassLoader()); + yamlFixture.getMethod("run").invoke(null); } System.out.println("Shared classifier: " + classes.size() + " classes linked; native configuration smoke passed"); } diff --git a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedRuntimeClasspath.java b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedRuntimeClasspath.java index e82e46c..50344e3 100644 --- a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedRuntimeClasspath.java +++ b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedRuntimeClasspath.java @@ -37,7 +37,8 @@ public static void assertPlatformsAbsent() throws Exception { public static void requirePlatformsAbsent(ClassLoader loader) throws Exception { for (String type : new String[] { "org.bukkit.Bukkit", "net.minecraft.server.MinecraftServer", "net.md_5.bungee.api.ProxyServer", "com.velocitypowered.api.proxy.ProxyServer", - "net.fabricmc.api.ModInitializer", "net.minecraftforge.fml.ModList" }) { + "net.fabricmc.api.ModInitializer", "net.minecraftforge.fml.ModList", + "net.neoforged.fml.ModList", "net.neoforged.neoforge.common.NeoForge" }) { try { loader.loadClass(type); throw new AssertionError("Platform leaked into shared classpath: " + type); diff --git a/docs/neoforge-configuration.md b/docs/neoforge-configuration.md new file mode 100644 index 0000000..e14d213 --- /dev/null +++ b/docs/neoforge-configuration.md @@ -0,0 +1,131 @@ +# YAML configuration in a NeoForge consumer + +Use SimpleAPI's existing platform-neutral YAML API from the `shared` classifier. +No SimpleAPI loader adapter, second YAML parser, or NeoForge dependency is needed +for this configuration path. The mod supplies its configuration directory and +owns lifecycle scheduling. Existing Bukkit/proxy consumers keep their current +dependencies, configuration files and APIs. + +## Dependency baseline + +The current SimpleAPI POM selects Java 21, SimpleAPI `1.0.2-SNAPSHOT`, and +Configurate `4.2.0`. Use the version actually built/published for your integration; +this guide does not claim a new artifact has been released. It does not select a +Minecraft/NeoForge version or certify a mod runtime. + +For a Gradle Kotlin DSL consumer, using the existing SimpleAPI Maven repository: + +```kotlin +repositories { + maven("https://nexus.bencodez.com/repository/maven-public/") + mavenCentral() +} + +dependencies { + implementation("com.bencodez:simpleapi:1.0.2-SNAPSHOT:shared") { + isTransitive = false + } + implementation("org.spongepowered:configurate-yaml:4.2.0") +} +``` + +Disable transitives **only on SimpleAPI**: a classifier uses the full project's +POM and otherwise brings platform dependencies. Keep Configurate's own transitives. +Do not place the full and shared SimpleAPI JARs together in the native runtime. +Hikari/JDBC are unnecessary for this YAML-only path; consumers using the shared SQL +API must add its dependencies separately, as described in [shared-libraries.md](shared-libraries.md). + +`implementation` configures compilation/runtime resolution in Gradle. The mod's +build must also arrange delivery of SimpleAPI shared, Configurate and its runtime +dependencies using its chosen loader packaging mechanism. Dependency resolution +alone does not prove these libraries are embedded in the final mod JAR. Verify the +final packaged mod independently; SimpleAPI's headless tests do not launch NeoForge. + +## Open, read, update and reload + +Call this on the application's configuration I/O worker. `configDirectory` is a +trusted, application-owned `Path` supplied by the mod; no loader class is imported +by SimpleAPI. Do not use Bukkit `YMLFile`, `VelocityYMLFile` or native platform +configuration objects in this path. + +```java +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import com.bencodez.simpleapi.core.config.YamlConfigDocument; +import com.bencodez.simpleapi.file.config.ConfigSnapshot; + +static YamlConfigDocument openSettings(Path configDirectory) throws IOException { + Files.createDirectories(configDirectory); // Application-owned setup + return YamlConfigDocument.open(configDirectory.resolve("settings.yml")); +} + +static ConfigSnapshot initialize(YamlConfigDocument document) throws IOException { + ConfigSnapshot before = document.snapshot(); + // Seed defaults only for a missing file; do not replace an existing config. + if (!before.revision().equals("missing")) return before; + return document.update(before.revision(), edit -> { + edit.set("Points", 1); + edit.set("Rewards.Commands", List.of("say voted")); + }); +} +``` + +Use `snapshot.view().getInt("Points", 1)` for a numeric read with a fallback. +Numeric/boolean scalar getters are strict: a quoted `'12'` is not a number. +Existing list conversions remain supported. Missing values use getter/annotation +defaults; an explicit empty list remains distinct from a missing value when read +through a structured view. Reads are case-sensitive by default. + +For structured or case-insensitive access, wrap the existing snapshot view: + +```java +import com.bencodez.simpleapi.core.config.CaseInsensitiveConfigView; +import com.bencodez.simpleapi.core.config.ConfigurateConfigView; +import com.bencodez.simpleapi.core.config.ConfigurateStructuredConfigView; + +var structured = new ConfigurateStructuredConfigView( + (ConfigurateConfigView) snapshot.view()); // Snapshot from core YamlConfigDocument +var insensitive = new CaseInsensitiveConfigView(structured); +int points = insensitive.getInt("points", 1); +var literalSite = structured.at("some.site"); // One literal key, not a dotted path +``` + +Case-insensitive wrapping is opt-in; enumeration retains original spelling and the +first enumerated key wins case collisions. Numeric YAML keys remain addressable +by string paths. Use `edit.setAt(value, "some.site", "Commands")` for literal key +segments containing dots. Structured exports are detached, bounded plain-data trees; +native platform objects are rejected. Existing annotation types and +`core.config.AnnotationBinder` can bind ordinary option classes from these views. + +All open/reload/update operations are synchronous. A missing file opens empty +without creating it. Malformed initial YAML throws `IOException`; do not silently +replace it with defaults. On reload, call `document.reload()` and validate the +returned snapshot before publishing application settings. A reload exception +retains the last valid document snapshot and must abort runtime reconfiguration. +Application validation/publication remains the consumer's responsibility. + +Updates require the snapshot revision, retain unknown keys, and use a bounded +temporary sibling followed by atomic replacement. Failed updates retain the active +snapshot. External edits, stale revisions, serialization limits and filesystem +failures are reported instead of truncating the original file. Reload after an +external edit before retrying. Old snapshots remain detached across updates. + +Defaults are 1 MiB input/output (configurable up to 16 MiB), 64 levels and 100,000 +nodes. The parent directory must exist and be trusted; the application owns +cross-process writer exclusion. Inline comment/format preservation, Bukkit default +overlays and native serialized items are not promised. See the full persistence +contract in [shared-libraries.md](shared-libraries.md). + +## Verification and remaining integration + +`NativeYamlTest` exercises this contract directly. The normal Maven `package` +phase also runs `NativeYamlFixture` against the actual shared JAR with only neutral +runtime libraries, explicitly rejecting Bukkit, proxy, Minecraft and mod-loader +classes. Existing tests cover legacy facades and Bukkit configuration parity. + +This consumption path supplies YAML configuration only. Mod entrypoints, event +registration, scheduler ownership, players, permissions, commands, rewards and +final dependency embedding belong to the native integration and require separate +design/tests. No native server acceptance is implied by shared class-loading tests. diff --git a/docs/platform-neutral-configuration.md b/docs/platform-neutral-configuration.md index d6587f6..c6e4713 100644 --- a/docs/platform-neutral-configuration.md +++ b/docs/platform-neutral-configuration.md @@ -22,3 +22,8 @@ mvn -B -f SimpleAPI/pom.xml clean package The same POM attaches a platform-neutral `shared` JAR; there are no child modules. See `shared-libraries.md` for dependency exclusions, package compatibility, configuration persistence guarantees, and packaged headless verification. + +For a NeoForge consumer, [neoforge-configuration.md](neoforge-configuration.md) +documents the existing shared YAML API, explicit Gradle dependency baseline, +configuration lifecycle and the boundary between headless verification and native +mod packaging. From 1711be58e5bf446f465228f704bcb8424b2a1381 Mon Sep 17 00:00:00 2001 From: BenCodez <17074231+BenCodez@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:26:49 +0000 Subject: [PATCH 2/4] Add neutral YAML configuration facade for native consumers --- .../core/config/YamlConfigDocument.java | 13 ++ .../core/config/YamlConfiguration.java | 145 +++++++++++++++++ .../tests/shared/NativeYamlApiFixture.java | 82 ++++++++++ .../tests/shared/SharedArtifactTest.java | 3 + .../tests/shared/YamlConfigurationTest.java | 149 ++++++++++++++++++ .../test/resources/native-yaml-defaults.yml | 13 ++ docs/neoforge-configuration.md | 106 +++++++++---- 7 files changed, 479 insertions(+), 32 deletions(-) create mode 100644 SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfiguration.java create mode 100644 SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlApiFixture.java create mode 100644 SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java create mode 100644 SimpleAPI/src/test/resources/native-yaml-defaults.yml diff --git a/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java b/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java index f1b42e0..f8f20f7 100644 --- a/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java +++ b/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java @@ -86,6 +86,19 @@ public static YamlConfigDocument open(Path path, int maxBytes) throws IOExceptio @Override public Path path() { return path; } + /** Seeds a missing document using the same parser, limits and atomic replacement as updates. */ + synchronized ConfigSnapshot initializeFrom(byte[] bytes) throws IOException { + if (editing) throw new IllegalStateException("Cannot initialize inside an edit callback"); + if (!revision.equals("missing")) return snapshot(); + if (bytes.length > maxBytes) throw new IOException("Default configuration exceeds byte limit"); + ConfigurationNode candidate = parse(bytes); + ConfigSnapshot result = new ConfigSnapshot(revisionOf(bytes), new ConfigurateConfigView(candidate.copy())); + replace(bytes); + root = candidate; + revision = result.revision(); + return result; + } + @Override public synchronized ConfigSnapshot snapshot() { return new ConfigSnapshot(revision, new ConfigurateConfigView(root.copy())); } diff --git a/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfiguration.java b/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfiguration.java new file mode 100644 index 0000000..8e35eea --- /dev/null +++ b/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfiguration.java @@ -0,0 +1,145 @@ +package com.bencodez.simpleapi.core.config; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.function.Consumer; + +import com.bencodez.simpleapi.file.config.ConfigEditor; +import com.bencodez.simpleapi.file.config.ConfigSnapshot; + +/** + * Platform-neutral YAML file facade with typed reads and atomic, revision-checked + * persistence. All file operations are synchronous; the caller owns its I/O thread + * and trusted parent directory. Existing files are never automatically rewritten. + * + *

Resource defaults initialize missing files only, not a read-time overlay. + * Getter defaults, strict scalar reads, legacy list conversions and literal keys + * follow the existing configuration views. Sections and snapshots are detached; + * obtain them again after a successful reload/update. Writes are immediately + * persisted, not staged in a mutable configuration tree. Formatting/inline comment + * preservation across edits is not promised.

+ */ +public final class YamlConfiguration implements StructuredConfigView { + private final YamlConfigDocument document; + private volatile ConfigSnapshot current; + private volatile boolean ignoreCase; + + private YamlConfiguration(YamlConfigDocument document) { + this.document = document; + publish(document.snapshot()); + } + + /** Reads an existing file, or an empty missing document without creating it. */ + public static YamlConfiguration load(Path path) throws IOException { + return load(path, YamlConfigDocument.DEFAULT_MAX_BYTES); + } + + public static YamlConfiguration load(Path path, int maxBytes) throws IOException { + return new YamlConfiguration(YamlConfigDocument.open(path, maxBytes)); + } + + /** + * Initializes a missing file from a classpath resource. An existing file is + * loaded without opening the resource. Resource names follow Class.getResourceAsStream. + */ + public static YamlConfiguration load(Path path, Class resourceOwner, String resourceName) throws IOException { + Objects.requireNonNull(resourceOwner, "resourceOwner"); + Objects.requireNonNull(resourceName, "resourceName"); + YamlConfiguration configuration = load(path); + if (configuration.current.revision().equals("missing")) { + byte[] bytes; + try (InputStream defaults = resourceOwner.getResourceAsStream(resourceName)) { + if (defaults == null) throw new IOException("Default YAML resource is missing"); + bytes = defaults.readNBytes(YamlConfigDocument.DEFAULT_MAX_BYTES + 1); + } + configuration.publish(configuration.document.initializeFrom(bytes)); + } + return configuration; + } + + /** The supplied stream is consumed only for a missing file and always closed, including on failure. */ + public static YamlConfiguration load(Path path, InputStream defaults) throws IOException { + return load(path, defaults, YamlConfigDocument.DEFAULT_MAX_BYTES); + } + + public static YamlConfiguration load(Path path, InputStream defaults, int maxBytes) throws IOException { + Objects.requireNonNull(defaults, "defaults"); + YamlConfiguration configuration; + byte[] bytes = null; + try (defaults) { + configuration = load(path, maxBytes); + if (configuration.current.revision().equals("missing")) bytes = defaults.readNBytes(maxBytes + 1); + } + if (bytes != null) configuration.publish(configuration.document.initializeFrom(bytes)); + return configuration; + } + + public Path path() { return document.path(); } + public ConfigSnapshot snapshot() { return current; } + public StructuredConfigView getData() { return (StructuredConfigView) current.view(); } + public boolean isIgnoreCase() { return ignoreCase; } + + /** Opt-in read policy only. Edits always use exact keys; use setAt for literal segments. */ + public synchronized void setIgnoreCase(boolean ignoreCase) { + this.ignoreCase = ignoreCase; + publish(document.snapshot()); + } + + /** Failed reloads leave both the active snapshot and file untouched. */ + public synchronized ConfigSnapshot reload() throws IOException { return publish(document.reload()); } + + /** Atomically persists an edit using the active revision. Failed edits publish nothing. */ + public synchronized ConfigSnapshot update(Consumer edit) throws IOException { + return update(current.revision(), edit); + } + + public synchronized ConfigSnapshot update(String expectedRevision, Consumer edit) throws IOException { + return publish(document.update(expectedRevision, edit)); + } + + /** Immediately persists a value; null removes it. This is not an in-memory-only setter. */ + public ConfigSnapshot set(String path, Object value) throws IOException { + return update(edit -> edit.set(path, value)); + } + + public ConfigSnapshot setAt(Object value, String... keys) throws IOException { + return update(edit -> edit.setAt(value, keys)); + } + + /** Explicitly saves the current document, including creation of an empty missing file. */ + public ConfigSnapshot save() throws IOException { return update(edit -> { }); } + + private ConfigSnapshot publish(ConfigSnapshot snapshot) { + StructuredConfigView view = new ConfigurateStructuredConfigView((ConfigurateConfigView) snapshot.view()); + if (ignoreCase) view = new CaseInsensitiveConfigView(view); + current = new ConfigSnapshot(snapshot.revision(), view); + return current; + } + + public String getString(String path) { return getString(path, null); } + public boolean getBoolean(String path) { return getBoolean(path, false); } + public int getInt(String path) { return getInt(path, 0); } + public long getLong(String path) { return getLong(path, 0L); } + public double getDouble(String path) { return getDouble(path, 0D); } + + @Override public boolean contains(String path) { return getData().contains(path); } + @Override public String getString(String path, String fallback) { return getData().getString(path, fallback); } + @Override public boolean getBoolean(String path, boolean fallback) { return getData().getBoolean(path, fallback); } + @Override public int getInt(String path, int fallback) { return getData().getInt(path, fallback); } + @Override public long getLong(String path, long fallback) { return getData().getLong(path, fallback); } + @Override public double getDouble(String path, double fallback) { return getData().getDouble(path, fallback); } + @Override public List getStringList(String path) { return getData().getStringList(path); } + @Override public List getIntegerList(String path) { return getData().getIntegerList(path); } + @Override public boolean isConfigurationSection(String path) { return getData().isConfigurationSection(path); } + @Override public StructuredConfigView getConfigurationSection(String path) { return getData().getConfigurationSection(path); } + @Override public Set getKeys(boolean deep) { return getData().getKeys(deep); } + @Override public Kind kind(String path) { return getData().kind(path); } + @Override public Kind kindAt(String... keys) { return getData().kindAt(keys); } + @Override public Object value(String path) { return getData().value(path); } + @Override public Object valueAt(String... keys) { return getData().valueAt(keys); } + @Override public StructuredConfigView at(String... keys) { return getData().at(keys); } +} diff --git a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlApiFixture.java b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlApiFixture.java new file mode 100644 index 0000000..3866420 --- /dev/null +++ b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/NativeYamlApiFixture.java @@ -0,0 +1,82 @@ +package com.bencodez.simpleapi.tests.shared; + +import java.io.IOException; +import java.nio.file.Files; +import java.util.List; +import java.util.Map; + +import com.bencodez.simpleapi.core.config.StructuredConfigView.Kind; +import com.bencodez.simpleapi.core.config.YamlConfiguration; + +/** A native consumer uses only the public facade: no Configurate nodes or casts. */ +public final class NativeYamlApiFixture { + private NativeYamlApiFixture() { } + + public static void run() throws Exception { + var directory = Files.createTempDirectory("simpleapi-yaml-api-"); + var path = directory.resolve("settings.yml"); + try { + var missing = YamlConfiguration.load(path); + require(!Files.exists(path) && missing.getInt("PointsOnVote", 3) == 3, "Missing read changed disk"); + var config = YamlConfiguration.load(path, NativeYamlApiFixture.class, "/native-yaml-defaults.yml"); + byte[] resource; + try (var defaults = NativeYamlApiFixture.class.getResourceAsStream("/native-yaml-defaults.yml")) { + resource = defaults.readAllBytes(); + } + require(java.util.Arrays.equals(resource, Files.readAllBytes(path)), "Initial resource bytes changed"); + require(config.getInt("PointsOnVote") == 1 && config.getBoolean("ProcessRewards"), "Typed options failed"); + require(config.getLong("PointsOnVote") == 1L && config.getDouble("PointsOnVote") == 1D, "Numeric reads failed"); + require(config.getInt("Quoted", 99) == 99, "Quoted scalar was coerced"); + require(config.kind("Empty") == Kind.LIST && config.kind("Absent") == Kind.MISSING, "Empty/missing lost"); + require(config.getString("Absent") == null && !config.getBoolean("Absent"), "Convenience defaults changed"); + var sites = config.getConfigurationSection("VoteSites"); + require(sites.at("some.site").getStringList("Rewards.Commands").equals(List.of("say voted")), + "Literal site/list traversal failed"); + var before = config.snapshot(); + require(config.getInt("pointsonvote", 99) == 99, "Default reads are not case-sensitive"); + config.setIgnoreCase(true); + require(config.getInt("POINTSONVOTE") == 1, "Opt-in case policy failed"); + require(config.at("votesites", "SOME.SITE").getBoolean("enabled", false), "Case/literal traversal failed"); + config.setIgnoreCase(false); + config.update(edit -> { + edit.set("PointsOnVote", 4); + edit.set("Unknown", "preserve"); + edit.set("Milestones.10.Points", 3); + edit.setAt(List.of("say updated"), "VoteSites", "some.site", "Rewards", "Commands"); + }); + require(before.view().getInt("PointsOnVote", 0) == 1, "Snapshot was not detached"); + require(sites.at("some.site").getStringList("Rewards.Commands").equals(List.of("say voted")), + "Retained section changed"); + config.setAt(Map.of("Enabled", false), "another.site"); + config.save(); + var reopened = YamlConfiguration.load(path, NativeYamlApiFixture.class, "/missing-resource.yml"); + require(reopened.getInt("PointsOnVote") == 4 && "preserve".equals(reopened.getString("Unknown")), + "Existing file overwritten by defaults"); + require(reopened.getConfigurationSection("Milestones").getKeys(false).equals(java.util.Set.of("10")), + "Numeric key duplicated"); + require(!reopened.at("another.site").getBoolean("Enabled", true), "Literal setter failed"); + String bytes = Files.readString(path); + try { + config.update(before.revision(), edit -> edit.set("PointsOnVote", 8)); + throw new AssertionError("Stale snapshot accepted"); + } catch (IOException expected) { } + require(bytes.equals(Files.readString(path)), "Stale write changed file"); + var lastGood = config.snapshot(); + Files.writeString(path, "PointsOnVote: [unterminated"); + try { config.reload(); throw new AssertionError("Malformed reload accepted"); } + catch (IOException expected) { } + require(config.snapshot() == lastGood && config.getInt("PointsOnVote") == 4, "Failed reload changed active data"); + try { config.save(); throw new AssertionError("Save overwrote external malformed edit"); } + catch (IOException expected) { } + Files.writeString(path, "PointsOnVote: 9\n"); + require(config.reload().view().getInt("PointsOnVote", 0) == 9, "Reload did not recover"); + } finally { + Files.deleteIfExists(path); + Files.deleteIfExists(directory); + } + } + + private static void require(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } +} diff --git a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedArtifactTest.java b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedArtifactTest.java index 720c7e6..a5f6c9d 100644 --- a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedArtifactTest.java +++ b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/SharedArtifactTest.java @@ -59,6 +59,9 @@ public class SharedArtifactTest { Class yamlFixture = loader.loadClass(NativeYamlFixture.class.getName()); assertSame(loader, yamlFixture.getClassLoader()); yamlFixture.getMethod("run").invoke(null); + Class apiFixture = loader.loadClass(NativeYamlApiFixture.class.getName()); + assertSame(loader, apiFixture.getClassLoader()); + apiFixture.getMethod("run").invoke(null); } System.out.println("Shared classifier: " + classes.size() + " classes linked; native configuration smoke passed"); } diff --git a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java new file mode 100644 index 0000000..f41fb4a --- /dev/null +++ b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java @@ -0,0 +1,149 @@ +package com.bencodez.simpleapi.tests.shared; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFileAttributeView; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import com.bencodez.simpleapi.core.config.YamlConfiguration; + +class YamlConfigurationTest { + @TempDir Path directory; + private Path path() { return directory.resolve("settings.yml"); } + + @Test void publicApiSupportsNativeConsumerWithoutConfiguratePlumbing() throws Exception { + NativeYamlApiFixture.run(); + } + + @Test void existingEmptyFileIsNotReplacedAndUnusedStreamIsClosedWithoutReading() throws Exception { + Files.writeString(path(), ""); + var defaults = new TrackedStream("Points: 7\n"); + var config = YamlConfiguration.load(path(), defaults); + assertTrue(defaults.closed); + assertEquals(defaults.initialSize, defaults.available()); + assertEquals(99, config.getInt("Points", 99)); + assertEquals("", Files.readString(path())); + assertNotEquals("missing", config.snapshot().revision()); + } + + @Test void invalidDefaultsAndMissingResourcesLeaveMissingFileUntouched() throws Exception { + for (String invalid : new String[] {"Points: [unterminated", "[1, 2]"}) { + var stream = new TrackedStream(invalid); + assertThrows(IOException.class, () -> YamlConfiguration.load(path(), stream)); + assertTrue(stream.closed); + assertFalse(Files.exists(path())); + } + assertThrows(IOException.class, () -> YamlConfiguration.load(path(), getClass(), "/missing.yml")); + assertFalse(Files.exists(path())); + } + + @Test void resourceReadAndCloseFailuresDoNotCreateFile() { + InputStream readFailure = new InputStream() { + @Override public int read() throws IOException { throw new IOException("synthetic read failure"); } + }; + assertThrows(IOException.class, () -> YamlConfiguration.load(path(), readFailure)); + InputStream closeFailure = new ByteArrayInputStream("Points: 7\n".getBytes(StandardCharsets.UTF_8)) { + @Override public void close() throws IOException { throw new IOException("synthetic close failure"); } + }; + assertThrows(IOException.class, () -> YamlConfiguration.load(path(), closeFailure)); + assertFalse(Files.exists(path())); + } + + @Test void defaultResourceAndEditedOutputAreBoundedWithoutPublishingChanges() throws Exception { + var large = new TrackedStream("Points: " + "x".repeat(1024)); + assertThrows(IOException.class, () -> YamlConfiguration.load(path(), large, 64)); + assertTrue(large.closed); + assertEquals(large.initialSize - 65, large.available(), "Resource read must be bounded"); + assertFalse(Files.exists(path())); + var config = YamlConfiguration.load(path(), new TrackedStream("Points: 7\n"), 64); + var before = config.snapshot(); + String bytes = Files.readString(path()); + assertThrows(IOException.class, () -> config.set("Large", "x".repeat(128))); + assertSame(before, config.snapshot()); + assertEquals(bytes, Files.readString(path())); + assertThrows(IllegalArgumentException.class, () -> config.set("Native", new Object())); + assertSame(before, config.snapshot()); + assertEquals(bytes, Files.readString(path())); + } + + @Test void resourceCannotOverwriteFileCreatedDuringInitialization() { + InputStream defaults = new ByteArrayInputStream("Points: 7\n".getBytes(StandardCharsets.UTF_8)) { + @Override public byte[] readNBytes(int length) throws IOException { + try { Files.writeString(path(), "Points: 42\n"); } + catch (IOException failure) { throw new AssertionError(failure); } + return super.readNBytes(length); + } + }; + assertThrows(IOException.class, () -> YamlConfiguration.load(path(), defaults)); + assertDoesNotThrow(() -> assertEquals("Points: 42\n", Files.readString(path()))); + } + + @Test void malformedExistingFileDoesNotFallBackToResourceAndClosesSuppliedStream() throws Exception { + String malformed = "Points: [unterminated"; + Files.writeString(path(), malformed); + var defaults = new TrackedStream("Points: 7\n"); + assertThrows(IOException.class, () -> YamlConfiguration.load(path(), defaults)); + assertTrue(defaults.closed); + assertEquals(malformed, Files.readString(path())); + } + + @Test void casingIsReadOnlyOptInAndCaseCollisionsUseFirstEnumeratedKey() throws Exception { + Files.writeString(path(), "Points: 7\nPOINTS: 9\n"); + var config = YamlConfiguration.load(path()); + var exact = config.snapshot(); + config.setIgnoreCase(true); + assertEquals(7, config.getInt("POINTS")); + assertEquals(9, exact.view().getInt("POINTS", 0)); + config.set("POINTS", 10); // Editing uses exact keys even with case-insensitive reads. + config.setIgnoreCase(false); + assertEquals(7, config.getInt("Points")); + assertEquals(10, config.getInt("POINTS")); + assertEquals(Set.of("Points", "POINTS"), config.getKeys(false)); + } + + @Test void explicitSaveCreatesMissingEmptyFileButDoesNotCreateParents() throws Exception { + var config = YamlConfiguration.load(path()); + assertFalse(Files.exists(path())); + config.save(); + assertTrue(Files.isRegularFile(path())); + assertTrue(YamlConfiguration.load(path()).getKeys(false).isEmpty()); + assertThrows(IOException.class, () -> YamlConfiguration.load(directory.resolve("missing/settings.yml"))); + assertFalse(Files.exists(directory.resolve("missing"))); + } + + @Test void unwritableParentLeavesActiveSnapshotAndDiskUnchangedThenRetrySucceeds() throws Exception { + assumeTrue(Files.getFileAttributeView(directory, PosixFileAttributeView.class) != null); + var config = YamlConfiguration.load(path(), new TrackedStream("Points: 7\n")); + var before = config.snapshot(); + String bytes = Files.readString(path()); + var permissions = Files.getPosixFilePermissions(directory); + try { + Files.setPosixFilePermissions(directory, + Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_EXECUTE)); + assumeTrue(!Files.isWritable(directory), "Process can bypass directory permissions"); + assertThrows(IOException.class, () -> config.set("Points", 8)); + assertSame(before, config.snapshot()); + assertEquals(bytes, Files.readString(path())); + } finally { Files.setPosixFilePermissions(directory, permissions); } + config.set("Points", 8); + assertEquals(8, YamlConfiguration.load(path()).getInt("Points")); + } + + private static final class TrackedStream extends ByteArrayInputStream { + private final int initialSize; + private boolean closed; + TrackedStream(String text) { super(text.getBytes(StandardCharsets.UTF_8)); initialSize = count; } + @Override public void close() throws IOException { closed = true; super.close(); } + } +} diff --git a/SimpleAPI/src/test/resources/native-yaml-defaults.yml b/SimpleAPI/src/test/resources/native-yaml-defaults.yml new file mode 100644 index 0000000..ace7324 --- /dev/null +++ b/SimpleAPI/src/test/resources/native-yaml-defaults.yml @@ -0,0 +1,13 @@ +# Synthetic native consumer defaults +PointsOnVote: 1 +ProcessRewards: true +Empty: [] +Quoted: '12' +VoteSites: + 'some.site': + Enabled: true + Rewards: + Commands: [say voted] +Milestones: + 10: + Points: 2 diff --git a/docs/neoforge-configuration.md b/docs/neoforge-configuration.md index e14d213..6706295 100644 --- a/docs/neoforge-configuration.md +++ b/docs/neoforge-configuration.md @@ -1,6 +1,8 @@ # YAML configuration in a NeoForge consumer -Use SimpleAPI's existing platform-neutral YAML API from the `shared` classifier. +Use `com.bencodez.simpleapi.core.config.YamlConfiguration` from the `shared` +classifier for direct file/resource loading, typed reads, sections and atomic +persistence over the existing neutral document and views. No SimpleAPI loader adapter, second YAML parser, or NeoForge dependency is needed for this configuration path. The mod supplies its configuration directory and owns lifecycle scheduling. Existing Bukkit/proxy consumers keep their current @@ -53,60 +55,97 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; -import com.bencodez.simpleapi.core.config.YamlConfigDocument; -import com.bencodez.simpleapi.file.config.ConfigSnapshot; +import com.bencodez.simpleapi.core.config.YamlConfiguration; -static YamlConfigDocument openSettings(Path configDirectory) throws IOException { - Files.createDirectories(configDirectory); // Application-owned setup - return YamlConfigDocument.open(configDirectory.resolve("settings.yml")); -} +final class NativeSettings { + private final YamlConfiguration yaml; + + NativeSettings(Path configDirectory) throws IOException { + Files.createDirectories(configDirectory); // Application-owned setup + yaml = YamlConfiguration.load(configDirectory.resolve("settings.yml"), + NativeSettings.class, "/native-settings.yml"); + } + + int pointsOnVote() { return yaml.getInt("PointsOnVote", 1); } + + List commands(String siteKey) { + var sites = yaml.getConfigurationSection("VoteSites"); + var site = sites == null ? null : sites.at(siteKey); // Literal key, including dots + return site == null ? List.of() : site.getStringList("Rewards.Commands"); + } + + void changeCommands(String siteKey, List commands) throws IOException { + yaml.setAt(commands, "VoteSites", siteKey, "Rewards", "Commands"); + } -static ConfigSnapshot initialize(YamlConfigDocument document) throws IOException { - ConfigSnapshot before = document.snapshot(); - // Seed defaults only for a missing file; do not replace an existing config. - if (!before.revision().equals("missing")) return before; - return document.update(before.revision(), edit -> { - edit.set("Points", 1); - edit.set("Rewards.Commands", List.of("say voted")); - }); + void reload() throws IOException { yaml.reload(); } } ``` -Use `snapshot.view().getInt("Points", 1)` for a numeric read with a fallback. +Bundle `/native-settings.yml` in the consumer's resources, for example: + +```yaml +PointsOnVote: 1 +VoteSites: + 'some.site': + Rewards: + Commands: [say voted] +``` + +`load(path)` reads a missing document without creating it. The classpath-resource +overload initializes missing files only, preserving initial resource bytes after +bounded validation. Existing files, including intentionally empty files, are never +replaced or merged with resource defaults. An existing file does not require the +resource to exist. There is no resource default-tree overlay; use getter defaults +for absent options and explicit updates for intentional migrations. + +`load(path, inputStream)` also supports missing-file defaults and always closes the +supplied stream, including on failure. Read/close failures precede initialization. +Plain load and stream load accept an optional final byte-limit argument. + +Use `yaml.getInt("PointsOnVote", 1)` for a numeric read with a fallback. Numeric/boolean scalar getters are strict: a quoted `'12'` is not a number. Existing list conversions remain supported. Missing values use getter/annotation defaults; an explicit empty list remains distinct from a missing value when read through a structured view. Reads are case-sensitive by default. -For structured or case-insensitive access, wrap the existing snapshot view: +The facade implements `StructuredConfigView` directly. No Configurate nodes or +casts are needed. String/boolean/int/long/double reads also have one-argument +conveniences using null/false/zero defaults. For structured or case-insensitive access: ```java -import com.bencodez.simpleapi.core.config.CaseInsensitiveConfigView; -import com.bencodez.simpleapi.core.config.ConfigurateConfigView; -import com.bencodez.simpleapi.core.config.ConfigurateStructuredConfigView; - -var structured = new ConfigurateStructuredConfigView( - (ConfigurateConfigView) snapshot.view()); // Snapshot from core YamlConfigDocument -var insensitive = new CaseInsensitiveConfigView(structured); -int points = insensitive.getInt("points", 1); -var literalSite = structured.at("some.site"); // One literal key, not a dotted path +yaml.setIgnoreCase(true); +int points = yaml.getInt("pointsonvote", 1); +var literalSite = yaml.at("votesites", "some.site"); // Literal segments +var stable = yaml.snapshot(); // Detached revision and view ``` Case-insensitive wrapping is opt-in; enumeration retains original spelling and the first enumerated key wins case collisions. Numeric YAML keys remain addressable -by string paths. Use `edit.setAt(value, "some.site", "Commands")` for literal key +by string paths. The casing option affects reads only; edits always use exact keys. +Use `yaml.setAt(value, "some.site", "Commands")` for literal key segments containing dots. Structured exports are detached, bounded plain-data trees; native platform objects are rejected. Existing annotation types and `core.config.AnnotationBinder` can bind ordinary option classes from these views. -All open/reload/update operations are synchronous. A missing file opens empty +`getData()`, `snapshot()` and sections are detached read views. Retained views do +not change after reload/update or a casing-policy change; reacquire them when +needed. Direct facade getters follow the latest successful operation. + +All load/reload/update operations are synchronous. A missing file opens empty without creating it. Malformed initial YAML throws `IOException`; do not silently -replace it with defaults. On reload, call `document.reload()` and validate the +replace it with defaults. On reload, call `yaml.reload()` and validate the returned snapshot before publishing application settings. A reload exception retains the last valid document snapshot and must abort runtime reconfiguration. Application validation/publication remains the consumer's responsibility. -Updates require the snapshot revision, retain unknown keys, and use a bounded +`set`, `setAt`, `update` and `save` immediately persist; there is no mutable pending +tree. Use `update(edit -> ...)` for a multi-key transaction, or +`update(snapshot.revision(), edit -> ...)` to reject a stale application edit. +A null value removes the selected key. `save()` explicitly rewrites current data +or creates an empty missing file. Use `yaml.reload()` for external changes. + +Updates check the snapshot revision, retain unknown keys, and use a bounded temporary sibling followed by atomic replacement. Failed updates retain the active snapshot. External edits, stale revisions, serialization limits and filesystem failures are reported instead of truncating the original file. Reload after an @@ -120,8 +159,11 @@ contract in [shared-libraries.md](shared-libraries.md). ## Verification and remaining integration -`NativeYamlTest` exercises this contract directly. The normal Maven `package` -phase also runs `NativeYamlFixture` against the actual shared JAR with only neutral +`YamlConfigurationTest` exercises the production facade, resource read/close errors, +empty existing files, bounded writes, casing, initialization races and real +unwritable-parent rollback/retry. The existing `NativeYamlTest` document regressions +are retained. The normal Maven `package` phase also runs `NativeYamlApiFixture` +and `NativeYamlFixture` against the actual shared JAR with only neutral runtime libraries, explicitly rejecting Bukkit, proxy, Minecraft and mod-loader classes. Existing tests cover legacy facades and Bukkit configuration parity. From ec2b8fb309a2f2db632b3c55028b628a385e9ca9 Mon Sep 17 00:00:00 2001 From: BenCodez <17074231+BenCodez@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:37:54 +0000 Subject: [PATCH 3/4] Coordinate YAML publication across same-path documents --- .../core/config/YamlConfigDocument.java | 30 +++++++- .../tests/shared/YamlConfigurationTest.java | 75 +++++++++++++++++++ docs/neoforge-configuration.md | 6 ++ 3 files changed, 109 insertions(+), 2 deletions(-) diff --git a/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java b/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java index f8f20f7..ecc6030 100644 --- a/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java +++ b/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java @@ -58,8 +58,14 @@ public final class YamlConfigDocument implements ConfigDocument { public static final int DEFAULT_MAX_BYTES = 1024 * 1024; private static final int MAX_NODES = 100_000; private static final int MAX_DEPTH = 64; + // Bounded same-classloader coordination, shared by every document for a canonical path. + private static final Object[] WRITE_LOCKS = new Object[64]; + static { + for (int index = 0; index < WRITE_LOCKS.length; index++) WRITE_LOCKS[index] = new Object(); + } private final Path path; private final int maxBytes; + private final Object writeLock; private ConfigurationNode root; private String revision; private boolean editing; @@ -67,6 +73,7 @@ public final class YamlConfigDocument implements ConfigDocument { private YamlConfigDocument(Path path, int maxBytes) { this.path = path; this.maxBytes = maxBytes; + this.writeLock = WRITE_LOCKS[Math.floorMod(path.hashCode(), WRITE_LOCKS.length)]; } 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 { if (bytes.length > maxBytes) throw new IOException("Default configuration exceeds byte limit"); ConfigurationNode candidate = parse(bytes); ConfigSnapshot result = new ConfigSnapshot(revisionOf(bytes), new ConfigurateConfigView(candidate.copy())); - replace(bytes); + replace(bytes, true); root = candidate; revision = result.revision(); return result; @@ -183,6 +190,16 @@ private byte[] serialize(ConfigurationNode candidate) throws IOException { } private void replace(byte[] encoded) throws IOException { + replace(encoded, false); + } + + private void replace(byte[] encoded, boolean initializeOnly) throws IOException { + synchronized (writeLock) { + replaceLocked(encoded, initializeOnly); + } + } + + private void replaceLocked(byte[] encoded, boolean initializeOnly) throws IOException { requireUnchanged(); Set permissions = null; if (Files.getFileAttributeView(path.getParent(), java.nio.file.attribute.PosixFileAttributeView.class) != null) { @@ -199,7 +216,16 @@ private void replace(byte[] encoded) throws IOException { channel.force(true); } requireUnchanged(); - Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + if (initializeOnly) { + // ATOMIC_MOVE is allowed to replace an existing target even without REPLACE_EXISTING. + // A hard link publishes the complete staged inode only if the destination is absent. + try { Files.createLink(path, temporary); } + catch (UnsupportedOperationException unsupported) { + throw new IOException("Atomic missing-file initialization is not supported", unsupported); + } + } else { + Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } } finally { Files.deleteIfExists(temporary); } diff --git a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java index f41fb4a..175e6f6 100644 --- a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java +++ b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java @@ -12,6 +12,9 @@ import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermission; import java.util.Set; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -140,6 +143,78 @@ class YamlConfigurationTest { assertEquals(8, YamlConfiguration.load(path()).getInt("Points")); } + @Test void simultaneousFirstLoadsCannotBothPublishDifferentDefaults() throws Exception { + var workers = Executors.newFixedThreadPool(2); + try { + for (int trial = 0; trial < 50; trial++) { + Path path = directory.resolve("initialize-" + trial + ".yml"); + var gate = new CyclicBarrier(2); + var first = workers.submit(() -> initialize(path, "Points: 1\n", gate)); + var second = workers.submit(() -> initialize(path, "Points: 2\n", gate)); + Integer one = first.get(10, TimeUnit.SECONDS); + Integer two = second.get(10, TimeUnit.SECONDS); + assertNotEquals(one == null, two == null, "Exactly one missing-file initializer must succeed"); + assertEquals(one == null ? two.intValue() : one.intValue(), YamlConfiguration.load(path).getInt("Points")); + } + } finally { + workers.shutdownNow(); + assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS)); + } + } + + @Test void simultaneousSameRevisionEditsCannotBothSucceedAndLoseOneChange() throws Exception { + var workers = Executors.newFixedThreadPool(2); + try { + for (int trial = 0; trial < 50; trial++) { + Path path = directory.resolve("update-" + trial + ".yml"); + Files.writeString(path, "First: 0\nSecond: 0\n"); + var first = YamlConfiguration.load(path); + var second = YamlConfiguration.load(path); + var gate = new CyclicBarrier(2); + var one = workers.submit(() -> editAtBarrier(first, "First", gate)); + var two = workers.submit(() -> editAtBarrier(second, "Second", gate)); + boolean firstSucceeded = one.get(10, TimeUnit.SECONDS); + boolean secondSucceeded = two.get(10, TimeUnit.SECONDS); + assertNotEquals(firstSucceeded, secondSucceeded, "One stale writer must be rejected"); + var disk = YamlConfiguration.load(path); + assertEquals(firstSucceeded ? 1 : 0, disk.getInt("First")); + assertEquals(secondSucceeded ? 1 : 0, disk.getInt("Second")); + } + } finally { + workers.shutdownNow(); + assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS)); + } + } + + private static Integer initialize(Path path, String text, CyclicBarrier gate) throws Exception { + InputStream stream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)) { + @Override public byte[] readNBytes(int limit) throws IOException { + await(gate); + return super.readNBytes(limit); + } + }; + try { return YamlConfiguration.load(path, stream).getInt("Points"); } + catch (IOException stale) { return null; } + } + + private static boolean editAtBarrier(YamlConfiguration config, String key, CyclicBarrier gate) throws Exception { + try { + config.update(edit -> { + try { await(gate); } catch (IOException failure) { throw new AssertionError(failure); } + edit.set(key, 1); + }); + return true; + } catch (IOException stale) { return false; } + } + + private static void await(CyclicBarrier gate) throws IOException { + try { gate.await(5, TimeUnit.SECONDS); } + catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new IOException(interrupted); } + catch (java.util.concurrent.BrokenBarrierException | java.util.concurrent.TimeoutException failure) { + throw new IOException(failure); + } + } + private static final class TrackedStream extends ByteArrayInputStream { private final int initialSize; private boolean closed; diff --git a/docs/neoforge-configuration.md b/docs/neoforge-configuration.md index 6706295..f61421b 100644 --- a/docs/neoforge-configuration.md +++ b/docs/neoforge-configuration.md @@ -98,6 +98,8 @@ bounded validation. Existing files, including intentionally empty files, are nev replaced or merged with resource defaults. An existing file does not require the resource to exist. There is no resource default-tree overlay; use getter defaults for absent options and explicit updates for intentional migrations. +Resource initialization atomically publishes a staged file only if absent, using +a same-directory hard link; unsupported filesystems fail without an unsafe fallback. `load(path, inputStream)` also supports missing-file defaults and always closes the 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 snapshot. External edits, stale revisions, serialization limits and filesystem failures are reported instead of truncating the original file. Reload after an external edit before retrying. Old snapshots remain detached across updates. +Document instances from the same defining classloader coordinate final revision +checks and publication by canonical path, so stale same-process writers cannot +both succeed and silently lose one edit. Cross-process writer exclusion remains +the application's responsibility. Defaults are 1 MiB input/output (configurable up to 16 MiB), 64 levels and 100,000 nodes. The parent directory must exist and be trusted; the application owns From ea69f3b693f3b2e60b71b3e4bcd2f722ddff155e Mon Sep 17 00:00:00 2001 From: BenCodez <17074231+BenCodez@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:54:15 +0000 Subject: [PATCH 4/4] Preserve YAML publication results across aliases and cleanup faults --- SimpleAPI/pom.xml | 6 +++ .../core/config/YamlConfigDocument.java | 13 +++-- .../tests/shared/YamlConfigurationTest.java | 52 +++++++++++++++++++ docs/neoforge-configuration.md | 6 ++- 4 files changed, 73 insertions(+), 4 deletions(-) diff --git a/SimpleAPI/pom.xml b/SimpleAPI/pom.xml index d261276..699c9d3 100644 --- a/SimpleAPI/pom.xml +++ b/SimpleAPI/pom.xml @@ -309,6 +309,12 @@ 5.24.0 test + + com.google.jimfs + jimfs + 1.3.2 + test + com.zaxxer HikariCP diff --git a/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java b/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java index ecc6030..ba59660 100644 --- a/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java +++ b/SimpleAPI/src/main/java/com/bencodez/simpleapi/core/config/YamlConfigDocument.java @@ -58,7 +58,7 @@ public final class YamlConfigDocument implements ConfigDocument { public static final int DEFAULT_MAX_BYTES = 1024 * 1024; private static final int MAX_NODES = 100_000; private static final int MAX_DEPTH = 64; - // Bounded same-classloader coordination, shared by every document for a canonical path. + // Serialize publication per canonical parent, including case-alias target names. private static final Object[] WRITE_LOCKS = new Object[64]; static { for (int index = 0; index < WRITE_LOCKS.length; index++) WRITE_LOCKS[index] = new Object(); @@ -73,7 +73,7 @@ public final class YamlConfigDocument implements ConfigDocument { private YamlConfigDocument(Path path, int maxBytes) { this.path = path; this.maxBytes = maxBytes; - this.writeLock = WRITE_LOCKS[Math.floorMod(path.hashCode(), WRITE_LOCKS.length)]; + this.writeLock = WRITE_LOCKS[Math.floorMod(path.getParent().hashCode(), WRITE_LOCKS.length)]; } 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 : Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); } Path temporary = Files.createTempFile(path.getParent(), ".simpleapi-config-", ".tmp"); + boolean committed = false; try { if (permissions != null) Files.setPosixFilePermissions(temporary, permissions); try (FileChannel channel = FileChannel.open(temporary, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) { @@ -226,8 +227,14 @@ private void replaceLocked(byte[] encoded, boolean initializeOnly) throws IOExce } else { Files.move(temporary, path, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } + committed = true; } finally { - Files.deleteIfExists(temporary); + try { Files.deleteIfExists(temporary); } + catch (IOException | SecurityException cleanupFailure) { + // Publication already succeeded: do not report a failed write or retain old active data. + // An unremovable staged sibling may require application-owned directory cleanup. + if (!committed) throw cleanupFailure; + } } } diff --git a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java index 175e6f6..be16413 100644 --- a/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java +++ b/SimpleAPI/src/test/java/com/bencodez/simpleapi/tests/shared/YamlConfigurationTest.java @@ -2,6 +2,8 @@ import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.argThat; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -20,6 +22,8 @@ import org.junit.jupiter.api.io.TempDir; import com.bencodez.simpleapi.core.config.YamlConfiguration; +import com.google.common.jimfs.Configuration; +import com.google.common.jimfs.Jimfs; class YamlConfigurationTest { @TempDir Path directory; @@ -197,6 +201,54 @@ private static Integer initialize(Path path, String text, CyclicBarrier gate) th catch (IOException stale) { return null; } } + @Test void caseAliasTargetsOnCaseInsensitiveStoreCannotLoseConcurrentEdits() throws Exception { + var workers = Executors.newFixedThreadPool(2); + try (var filesystem = Jimfs.newFileSystem(Configuration.osX().toBuilder() + .setPathEqualityUsesCanonicalForm(false).build())) { + Path parent = filesystem.getPath("/config"); + Files.createDirectory(parent); + for (int trial = 0; trial < 50; trial++) { + Path firstPath = parent.resolve("Settings-" + trial + ".yml"); + Path secondPath = parent.resolve("settings-" + trial + ".yml"); + Files.writeString(firstPath, "First: 0\nSecond: 0\n"); + assertNotEquals(firstPath, secondPath, "Paths must retain spelling-sensitive equality"); + assertNotEquals(firstPath.hashCode(), secondPath.hashCode()); + assertTrue(Files.isSameFile(firstPath, secondPath), "Store must resolve case aliases"); + var first = YamlConfiguration.load(firstPath); + var second = YamlConfiguration.load(secondPath); + var gate = new CyclicBarrier(2); + var one = workers.submit(() -> editAtBarrier(first, "First", gate)); + var two = workers.submit(() -> editAtBarrier(second, "Second", gate)); + boolean firstSucceeded = one.get(10, TimeUnit.SECONDS); + boolean secondSucceeded = two.get(10, TimeUnit.SECONDS); + assertNotEquals(firstSucceeded, secondSucceeded, "Case aliases must share revision coordination"); + var disk = YamlConfiguration.load(firstPath); + assertEquals(firstSucceeded ? 1 : 0, disk.getInt("First")); + assertEquals(secondSucceeded ? 1 : 0, disk.getInt("Second")); + } + } finally { + workers.shutdownNow(); + assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS)); + } + } + + @Test void committedResourceInitializationRemainsSuccessfulAfterUnlinkFailure() throws Exception { + try (var files = mockStatic(Files.class, CALLS_REAL_METHODS)) { + files.when(() -> Files.deleteIfExists(argThat((Path staged) -> staged != null + && staged.getFileName().toString().startsWith(".simpleapi-config-")))) + .thenThrow(new IOException("synthetic staged unlink failure")); + var config = YamlConfiguration.load(path(), new TrackedStream("Points: 7\n")); + assertEquals(7, config.getInt("Points")); + assertEquals(config.snapshot().revision(), YamlConfiguration.load(path()).snapshot().revision()); + assertEquals("Points: 7\n", Files.readString(path())); + } + try (var children = Files.list(directory)) { + var staged = children.filter(file -> file.getFileName().toString().startsWith(".simpleapi-config-")).toList(); + assertEquals(1, staged.size(), "Injected cleanup failure should leave exactly its staged sibling"); + for (Path file : staged) Files.delete(file); + } + } + private static boolean editAtBarrier(YamlConfiguration config, String key, CyclicBarrier gate) throws Exception { try { config.update(edit -> { diff --git a/docs/neoforge-configuration.md b/docs/neoforge-configuration.md index f61421b..c082aba 100644 --- a/docs/neoforge-configuration.md +++ b/docs/neoforge-configuration.md @@ -153,9 +153,13 @@ snapshot. External edits, stale revisions, serialization limits and filesystem failures are reported instead of truncating the original file. Reload after an external edit before retrying. Old snapshots remain detached across updates. Document instances from the same defining classloader coordinate final revision -checks and publication by canonical path, so stale same-process writers cannot +checks and publication by canonical parent directory, including case-alias target +names, so stale same-process writers cannot both succeed and silently lose one edit. Cross-process writer exclusion remains the application's responsibility. +After successful publication, a temporary-sibling deletion failure does not undo +the committed result or make the operation report failure. Such a sibling may +require application-owned directory cleanup after the filesystem fault is resolved. Defaults are 1 MiB input/output (configurable up to 16 MiB), 64 levels and 100,000 nodes. The parent directory must exist and be trusted; the application owns