taffy-comficonf
Registers a plugin's YAML settings file with the ComfiConf bridge so the server owner edits it in the ComfiConf web config editor.
taffy-comficonf connects one settings file of a plugin to ComfiConf, so the server owner edits it in the web config editor instead of by hand. It gives the plugin:
ComfiConfConnection, which checks that the connection is switched on and that the ComfiConf bridge is installed, enabled and visible to the plugin, runs the plugin's registration, and reports the outcome as aComfiConfStatusthe owner can read.YamlFileProvider, which reads, validates and writes one YAML file, keeps its comments, unknown keys and line endings, and runs the plugin's own reload after each write.ComfiConfRegistration, which registers the provider with the running bridge and returns aComfiConfLink.
The module builds on taffy-config: the reload a provider runs is usually ConfigHolder.reload(), and restart-only settings are read from ConfigHolder.startup(). It also depends on taffy-platform for ErrorReports.
The ComfiConf side of the integration (the schema, ConfigField, SectionMapper, ValidationResult) is the ComfiConf API. Its reference is the ComfiConf developer documentation.
Setup
Gradle
The module is so.alaz.taffy:taffy-comficonf, alaz.taffy.comficonf in the catalog. The ComfiConf API is provided by the bridge plugin at runtime, so the plugin declares it itself as compile-only and for its tests:
plugins {
id("so.alaz.taffy.paper-plugin")
}
dependencies {
compileOnly(alaz.paper.api)
compileOnly(alaz.comficonf.api)
implementation(alaz.taffy.comficonf)
testImplementation(alaz.comficonf.api)
}implementation(alaz.taffy.comficonf) brings taffy-config and taffy-platform with it. The published metadata of taffy-comficonf does not name comficonf-api, so the API never arrives transitively.
Never shade or relocate com.comficonf
A second copy of the API classes never finds the bridge. A plugin jar that bundles its own copy of com.comficonf.api reads NOT_VISIBLE, with a reason naming the copy, and a jar that relocates it reads FAILED. so.alaz.taffy.paper-plugin relocates so.alaz.taffy to <group>.libs.taffy and leaves com.comficonf alone; keep alaz.comficonf.api out of implementation and out of paperPlugin.runtimeLibrary.
paper-plugin.yml
The plugin lists the bridge as an optional server dependency whose classes it sees:
dependencies:
server:
ComfiConf:
load: BEFORE
required: false
join-classpath: trueWithout join-classpath: true the plugin cannot load the bridge's API classes, and the connection reads NOT_VISIBLE.
Which classes may load without the bridge
The server owner may run the plugin without ComfiConf. The public types split in two:
| Type | Names a com.comficonf type | Where the plugin uses it |
|---|---|---|
ComfiConfConnection | no | main class, commands, onDisable |
ComfiConfStatus | no | anywhere |
ComfiConfState | no | anywhere |
ComfiConfLink | no | anywhere, as the supplier's result type |
ComfiConfRegistration | yes | only the plugin's ComfiConf integration class |
YamlFileProvider | yes | only the plugin's ComfiConf integration class |
Loading ComfiConfRegistration or YamlFileProvider on a server without the bridge fails with NoClassDefFoundError. The plugin names them only inside its own integration class, and reaches that class only through the Supplier<ComfiConfLink> it passes to ComfiConfConnection.connect. connect calls the supplier only after every check passed, so the integration class loads only on a server where the bridge is installed, enabled and visible. The plugin's main class, and every class it loads before that call, never name the two API-typed classes.
The integration class
The integration class builds the YamlFileProvider once and returns an API-free supplier that registers it:
package com.example.myplugin;
import com.comficonf.api.ValidationResult;
import com.comficonf.api.bukkit.SectionMapper;
import com.comficonf.api.schema.ConfigField;
import com.comficonf.api.schema.ConfigSchema;
import so.alaz.taffy.comficonf.ComfiConfLink;
import so.alaz.taffy.comficonf.ComfiConfRegistration;
import so.alaz.taffy.comficonf.YamlFileProvider;
import so.alaz.taffy.config.ConfigHolder;
import java.nio.file.Path;
import java.util.function.Supplier;
final class MyComfiConf {
private static final String RESOURCE_ID = "myplugin:config";
private MyComfiConf() {
}
static Supplier<ComfiConfLink> registration(MyPlugin plugin, ConfigHolder<Settings> holder) {
Path file = plugin.getDataFolder().toPath().resolve("config.yml");
SectionMapper mapper = SectionMapper.of(ConfigSchema.of(
ConfigField.string("greeting"),
ConfigField.integer("min-radius").range(1, 64),
ConfigField.integer("radius").range(1, 64),
ConfigField.object("database").fields(
ConfigField.string("host").restartRequired())));
YamlFileProvider provider = YamlFileProvider.builder(file, mapper, holder::reload)
.rules(proposed -> proposed.getLong("min-radius", 1) > proposed.getLong("radius", 64)
? ValidationResult.error("min-radius", "min-radius must not be larger than radius.")
: ValidationResult.ok())
.build(plugin.getLogger());
return () -> ComfiConfRegistration.register(plugin, RESOURCE_ID, "My Plugin",
"Settings of My Plugin.", provider);
}
}ComfiConfRegistration.register(Plugin owner, String id, String displayName, String description, ConfigProvider provider) registers the resource with the running bridge and returns the ComfiConfLink the plugin keeps until onDisable:
| Parameter | Rule |
|---|---|
id | namespace:name, each part matching [a-z0-9][a-z0-9._-]{0,63}. The editor and the change history refer to it, so it never changes once released. |
displayName | The name shown in the editor, at most 80 characters. |
description | The description shown in the editor, at most 500 characters. |
provider | The callbacks of the resource, such as a YamlFileProvider. They run on a bridge worker thread. |
It throws IllegalArgumentException when the id or a text is invalid or the id is already registered, and IllegalStateException when the bridge or owner is not enabled or the bridge's API service is not the one the plugin sees. It is called from onEnable, never from onLoad, a constructor or a static initializer. When it runs inside the supplier given to connect, a thrown exception becomes the FAILED state instead of leaving connect.
At enable
At the end of onEnable, after the settings file loaded and after any migration that writes it, the main class connects. A method that fills the supplier field on its first call keeps the integration class unloaded until connect asks for it:
package com.example.myplugin;
import org.bukkit.plugin.java.JavaPlugin;
import so.alaz.taffy.comficonf.ComfiConfConnection;
import so.alaz.taffy.comficonf.ComfiConfLink;
import so.alaz.taffy.config.ConfigHolder;
import so.alaz.taffy.config.ConfigLoadException;
import so.alaz.taffy.platform.ErrorReports;
import java.util.function.Supplier;
public final class MyPlugin extends JavaPlugin {
private final ErrorReports errors = new ErrorReports();
private ConfigHolder<Settings> holder;
private ComfiConfConnection comfiConf;
private Supplier<ComfiConfLink> comfiConfRegistration;
@Override
public void onEnable() {
try {
holder = ConfigHolder.load(this::readSettings, getLogger()::warning);
} catch (ConfigLoadException e) {
getLogger().severe(e.getMessage());
getServer().getPluginManager().disablePlugin(this);
return;
}
// ... the rest of the plugin's startup ...
comfiConf = ComfiConfConnection.connect(this, errors, holder.startup().comfiConf(),
this::registerComfiConf);
}
private ComfiConfLink registerComfiConf() {
if (comfiConfRegistration == null) {
comfiConfRegistration = MyComfiConf.registration(this, holder);
}
return comfiConfRegistration.get();
}
}Here readSettings() is the plugin's own method that reads config.yml into its Settings record and throws ConfigLoadException when the file cannot be used, so this::readSettings serves as the ConfigHolder.Loader (see taffy-config). Settings has a boolean comfiConf() switch, which the schema above leaves out.
connect(Plugin owner, ErrorReports errors, boolean switchedOn, Supplier<ComfiConfLink> registration) runs on the main thread. Its checks run in this order and stop at the first that fails:
switchedOn is false: the bridge is not looked at, and the state is SWITCHED_OFF.
No plugin named ComfiConf is installed: NOT_INSTALLED. It is installed but not enabled: NOT_ENABLED. Nothing is logged for these two states or for SWITCHED_OFF.
The API is not visible to the plugin, or the plugin's jar holds its own copy: NOT_VISIBLE, with one warning. The installed bridge lacks an API class the plugin was built against: API_MISSING, with one warning that asks the owner to update ComfiConf.
The supplier runs, at most once, on the calling thread. A LinkageError from it whose message names a com.comficonf class, or that has no message, means the bridge lacks an API class: API_MISSING, with the same warning. Any other RuntimeException or LinkageError (a class of the plugin that failed to initialize included), or a null result, logs one warning with the stack, is reported to errors under the source hook.comficonf, and gives FAILED. A supplier that returns a link logs Registered <id> with ComfiConf and gives ON.
connect reads the switch once. A switch kept in the file the provider exposes is either left out of the schema or declared restartRequired() and read from ConfigHolder.startup(), as above. A RuntimeException or LinkageError from the supplier never leaves connect, and connect never returns null: once that line ran, the plugin holds a connection whatever the outcome. The field is still null when onEnable stopped before it.
ComfiConfConnection
| Method | Behaviour |
|---|---|
static ComfiConfConnection connect(Plugin, ErrorReports, boolean, Supplier<ComfiConfLink>) | The checks above, then the registration. Never null. |
ComfiConfStatus status() | The state now, read when asked. Never null. |
@Nullable String resourceId() | The registered resource id, or null when nothing was registered. |
void notifyChanged() | Tells the bridge the settings changed outside ComfiConf, so open editors load the newer values. |
Lock lockFor(Path file) | The lock the plugin holds around its own writes of file. Never null. |
void close() | Unregisters the resource. A second call has no further effect. |
Every method other than connect may be called from any thread. status(), notifyChanged(), lockFor(Path) and close() never pass on a RuntimeException or LinkageError from the link, so a broken bridge cannot break onDisable, a reload command or a diagnostics command. Each logs its first such failure as one warning with the stack on the plugin's logger; later failures of the same method are not logged. notifyChanged() and close() do nothing when no resource was registered and while the bridge plugin is disabled, and notifyChanged() also does nothing once the resource is no longer registered.
ComfiConfLink
ComfiConfLink is the plugin's registration of one resource. It names no com.comficonf type, so classes loaded before the bridge check may hold it. ComfiConfRegistration.register returns one; a test may return its own implementation from the supplier passed to connect.
| Method | Contract |
|---|---|
String resourceId() | The id of the registered resource, namespace:name. |
boolean isRegistered() | Whether the resource is still registered with the bridge. |
void notifyChanged() | Tells the bridge the resource changed outside ComfiConf, so open editors load the newer values. Does nothing once the resource is no longer registered. |
void close() | Unregisters the resource. Calling it more than once has no further effect. |
Lock lockFor(Path file) | The lock an apply of file holds from its revision check to the move of the new content over the file. The same path gives the same lock on every call. Never null. |
Implementations are thread-safe: ComfiConfConnection calls every method from whichever thread calls the connection. The link register returns is thread-safe. While the bridge plugin is enabled, status() reads isRegistered(): false gives NOT_REGISTERED, and a RuntimeException or LinkageError gives FAILED. A null lock or a RuntimeException or LinkageError from lockFor makes the connection give its own lock instead.
Status for the server owner
ComfiConfStatus is a record, ComfiConfStatus(ComfiConfState state, @Nullable String version, @Nullable String reason). version is the bridge's version, null for SWITCHED_OFF, NOT_INSTALLED and NOT_ENABLED. reason is one or more full sentences for the owner on what is missing or what went wrong, and what to do when there is something to do; it is set for NOT_VISIBLE, API_MISSING, NOT_REGISTERED and FAILED. The constructor throws NullPointerException for a null state and IllegalArgumentException for a blank reason.
describe() names the state in a few words. These texts are part of the contract:
ComfiConfState | describe() |
|---|---|
SWITCHED_OFF | ComfiConf switched off |
NOT_INSTALLED | ComfiConf not installed |
NOT_ENABLED | ComfiConf installed but not enabled |
NOT_VISIBLE | ComfiConf <version> not visible to this plugin |
API_MISSING | ComfiConf <version> lacks the API this plugin needs |
NOT_REGISTERED | ComfiConf <version> installed, not registered |
FAILED | ComfiConf <version> could not register this plugin's settings |
ON | ComfiConf on |
A version that was not read shows as unknown. describe() never includes the reason; together the two are the owner's line, with resourceId() for the same line:
ComfiConfStatus status = comfiConf.status();
sender.sendPlainMessage(status.describe());
if (status.reason() != null) {
sender.sendPlainMessage(status.reason());
}A status read after a connect that reached ON moves to NOT_ENABLED while the bridge plugin is disabled, to NOT_REGISTERED while the bridge is enabled but no longer holds the resource (the bridge was reloaded, dropped every registration, or the connection was closed), and to FAILED while the link throws when asked whether it holds the resource. It reads ON again once the bridge is enabled and the link reports the resource registered. Every other state is fixed at connect.
YamlFileProvider
YamlFileProvider implements the ComfiConf ConfigProvider over one YAML file.
| Method | Returns |
|---|---|
static YamlFileProvider.Builder builder(Path file, SectionMapper mapper, Callable<Boolean> activation) | A builder with no plugin rules. |
Builder rules(Function<ConfigValues, ValidationResult> rules) | The same builder. |
YamlFileProvider build(Logger logger) | The provider. |
| Input | Meaning |
|---|---|
file | The settings file. Its file name stands for it in log lines and in the messages the editor shows. |
mapper | The schema of the file and its mapping, a ComfiConf SectionMapper. |
activation | Reads the file into the plugin on the main thread and returns true when the new values are in effect. holder::reload of a ConfigHolder serves. It must not write the file. |
rules | Optional. The plugin's own checks, merged after the mapper's issues by validate. An error refuses the proposal. It runs on the bridge worker thread, must not touch the main thread, and returns a result for every proposal: a null result makes validate throw. |
logger | The plugin's logger. It receives the apply lines and the activation failures with their stacks. |
build reads the file once for the values in effect since startup, so it is called after the plugin loaded the file in onEnable. A file that cannot be read then gives no startup values, and every later restart-only change is reported as waiting. The Builder is not thread-safe: build it on one thread.
What the bridge calls
The bridge calls describe(), read(), validate(ConfigValues) and apply(ApplyContext) on its worker thread, and each call parses its own document.
read()takes the values and the revision from one read of the file, so edits by hand are detected. It throwsIOExceptionwhen the file cannot be read (a missing file included) andConfigLoadExceptionwhen the file is not UTF-8, not valid YAML or larger than 16 MiB. A YAML error names the line and column where the parser gives them and does not quote that line. It throwsIllegalStateExceptionwhen the mapper cannot read a stored value without losing data.validatereturns the text the file cannot store unchanged, then the issues ofrules.applychecks the base revision against the current bytes (a mismatch is a conflict), refuses a proposal the mapper rejects, merges the proposal into the document parsed from the current bytes, refuses a value the file cannot store unchanged, and writes through ComfiConf'sSafeFileWriter, which keeps the 10 newest backups in abackupsfolder beside the file. It then runs the activation on the main thread throughApplyContext.callSync, with no lock held.IOExceptionandConfigLoadExceptionfromapplymean nothing was written.
Only the fields the mapper declares are read and written. Comments, keys the schema does not declare and the file's line endings are kept on every write. A file that is not UTF-8 or not valid YAML is never written.
The apply result
Nothing after the write throws. The result is applied only when the activation returned true and no restart-only change waits. A restart-only change that waits gives savedRestartRequired with the waiting paths. A false or null from the activation, an exception or error it threw, and a callSync that timed out or was interrupted all give savedRestartRequired with the message that the values were saved but not loaded. An activation failure and a timed-out or interrupted callSync are logged as a warning with the stack and never reported to ErrorReports, because the message of a failed loader can quote a configuration value.
Keep the schema and rules as strict as the loader
The result is true only when the schema and rules accept no more than the loader the activation runs. Each schema constraint is no looser than the matching ConfigReader call, or the reader replaces an accepted value with its fallback while the result says applied. rules refuses every proposal the loader rejects, cross-field checks included, or the file is saved with values the loader refuses and the next start of the plugin fails on the file.
The loader the activation runs must not write the file: a write there changes the revision after apply returned it, so the next apply is a conflict. ConfigLoader.load() writes config.yml when the file is missing and when the save of an upgrade failed, so a ConfigHolder whose loader runs it is write-free in the activation only after the startup load and its upgrade succeeded.
Restart-only fields
A changed field declared restartRequired() is reported as waiting for a restart unless its new value equals the value the file held when the provider was built. A change inside an object list has a path through the index of its item, so such a change may be reported as waiting even when its new value equals its startup value. A restart-only change is never reported as in effect while its value differs from the value at startup. The report is true only when the code using a restart-only value reads ConfigHolder.startup(); code reading ConfigHolder.get() sees the new value at once, and the savedRestartRequired result is then untrue.
Reloads and the plugin's own writes
After each successful reload by the plugin's own command, and after each write of the file outside ComfiConf, the plugin calls notifyChanged() so open editors read the new values. It never calls it after an apply, and the provider never calls it.
if (holder.reload() && comfiConf != null) {
comfiConf.notifyChanged();
}A write of the exposed file by the plugin holds the lock lockFor(file) gives, from reading the file anew to saving it. While a resource is registered it is the lock an apply holds from its revision check to the move of the new content over the file, so an apply racing the write reports a conflict instead of replacing it. A write without the lock can be replaced by an apply with no conflict, and a write of values read before an apply reverts that apply.
void setRadius(Path configFile, int radius) throws IOException {
Lock lock = comfiConf.lockFor(configFile);
lock.lock();
try {
YamlConfiguration yaml = YamlConfiguration.loadConfiguration(configFile.toFile());
yaml.set("radius", radius);
yaml.save(configFile.toFile());
} finally {
lock.unlock();
}
holder.reload();
comfiConf.notifyChanged();
}When no resource is registered, and when the link throws (logged once as above), lockFor gives one lock of the connection that no apply takes, so the same code runs without the bridge.
Connecting again
A connection that reads NOT_REGISTERED, for example after ComfiConf was reloaded, stays unregistered: its link never registers again. To register the settings again without a restart, the plugin closes the connection it holds, then connects on the main thread with the same supplier and keeps the new connection:
void reconnectComfiConf() {
if (comfiConf != null) {
comfiConf.close();
}
comfiConf = ComfiConfConnection.connect(this, errors, holder.startup().comfiConf(),
this::registerComfiConf);
}A connect while the old resource is still registered gives FAILED, because the bridge refuses a second resource with the same id. The YamlFileProvider is built once, at the first connect that passed its checks, and every later connect registers that same provider. A provider built later would take the file at that moment as its startup values, so a restart-only change made since the start would no longer be reported as waiting.
At disable
close() is the first step of onDisable, so no apply reaches a plugin that is half disabled. It never passes on a failure of the bridge, so the steps after it run. The field is checked first, because it is still null when onEnable stopped before connect:
@Override
public void onDisable() {
if (comfiConf != null) {
comfiConf.close();
}
// ... the rest of the plugin's shutdown ...
}Testing
testImplementation(alaz.comficonf.api) puts the real API value types on the test classpath. YamlFileProvider.read(), validate and describe() need no bridge, and apply takes an ApplyContext, an interface the test implements with its own callSync. ComfiConfConnection.connect with switchedOn set to false, or on a mocked server whose plugin manager has no ComfiConf plugin, returns a connection whose methods do nothing and whose lockFor still gives a lock. See taffy-test for CapturedLog and the other helpers.
Behaviour summary
| Topic | Fact |
|---|---|
| Threads | connect and a reconnect run on the main thread. Provider callbacks and rules run on a bridge worker thread, and rules must not touch the main thread; the activation runs on the main thread through callSync. Every ComfiConfConnection method other than connect may be called from any thread. |
| Failures | No ComfiConfConnection method passes on a bridge failure. A failed registration is reported to ErrorReports under hook.comficonf; activation failures are logged only. |
| Not bundled | com.comficonf.api is provided by the bridge. It is compile-only in Taffy and in the plugin, never shaded, never relocated, and absent from Taffy's published metadata. |
| One file | One YamlFileProvider exposes one YAML file. The plugin keeps its schema, its field mapping and its resource id. |