Overview
The API lives in two packages, dev.flintmc.api and dev.flintmc.api.event. They are the only server classes a plugin can see: each plugin runs in its own class loader, which refuses every other server class. To learn how to set up and build a plugin, start with Writing a plugin.
Three ideas run through the whole API:
- Everything goes through the context. A plugin gets a
Contextwhen it’s enabled, and every service comes from it. - Handles, not objects. The context and everything it returns stop working the moment the plugin instance is retired by an unload or a reload. After that, every call throws
IllegalStateException, so forgotten code can’t act on the server. - Cleanup is automatic. Listeners, commands, tasks and threads registered through the context are removed when the instance is retired.
Threads
The server runs 20 ticks per second on one main thread. Listeners, scheduled tasks and commands all run on the main thread, so they never run at the same time as each other. The lifecycle methods (onEnable, onReload, onDisable) run on a short-lived lifecycle thread while the main thread waits, so they don’t overlap with the plugin’s other code either.
Plugin
public interface Plugin
The plugin’s main class implements this interface and has a public no-argument constructor. Every load, reload or unload creates or retires one instance of it.
| Method | When it runs |
|---|---|
void onEnable(Context context) | Once, when the instance is created. Restore state from context.snapshot() and register listeners, commands and tasks. Throwing fails the load or reload; on a reload the previous instance keeps running. |
Snapshot onReload(Context context) | On the instance being replaced, when a reload starts. Return the state the next instance needs, or Snapshot.EMPTY (the default). Throwing cancels the reload. |
void onDisable(Context context) | Once, when the instance is retired: on unload, or after a reload has switched to the new instance. Release anything the server doesn’t track, such as open files. Exceptions are logged and don’t stop the unload. |
Each lifecycle method has a time budget, 2 seconds by default (reload.step-budget-ms). Going over it fails the load or reload.
Rules for hot reloading
onReloadmust not tear anything down. A reload can still fail after it returns, and then this same instance keeps running as if nothing happened. Save state only; clean up inonDisable.- The new
onEnableruns before the oldonDisable. That is what makes rollback possible. So don’t take an exclusive external resource, such as a file lock or a port, inonEnablewhile the old instance still holds it. - Don’t keep the context, or anything it returns, in static fields, and don’t hand it to other code. It belongs to one instance.
- Create threads only through
context.threads(). A thread the server doesn’t know about keeps running after an unload and keeps the plugin’s classes in memory.
Before loading a jar, the server scans it for code that breaks these rules. See Hot reloading.
flint-plugin.properties
Every plugin jar has this file at its root:
name=hello
version=1.0.0
main=com.example.hello.HelloPlugin
# Optional: the plugin is safe to hot-reload even if the safety scan flags it.
hot-reload: true
| Key | Meaning |
|---|---|
name | Required. 1 to 32 lowercase letters, digits, _ or -. A reload must keep the same name. |
version | Required. Any text. |
main | Required. The fully qualified name of the class that implements Plugin. |
hot-reload | Optional, false by default. true overrides the safety scan’s findings, but not a leak the server actually observed. |
Context
public interface Context
What one plugin instance can use from the server. Each instance gets its own.
| Method | Returns |
|---|---|
String pluginName() | The name from flint-plugin.properties. |
String pluginVersion() | The version from flint-plugin.properties. |
Snapshot snapshot() | The state the previous instance returned from onReload, or Snapshot.EMPTY after a fresh load. |
Log log() | A logger tagged with the plugin’s name. |
Events events() | Listening for and posting events. |
Scheduler scheduler() | Running code later or repeatedly on the main thread. |
Commands commands() | Registering commands. |
Players players() | Looking up online players and messaging them. |
Threads threads() | Creating threads the server can stop when the plugin is retired. |
Snapshot
public final class Snapshot
An immutable, versioned set of key-value pairs that carries a plugin’s state across a reload. Values can only be strings, longs, doubles, booleans and byte arrays. That’s deliberate: a snapshot outlives the class loader of the instance that made it, so it must never hold an object of a plugin class. Turn anything richer into these types yourself.
The version is your own schema version. Bump it when the layout changes, and have onEnable handle or ignore snapshots of older versions.
@Override
public Snapshot onReload(Context context) {
return Snapshot.builder(1)
.putLong("count", count)
.putString("owner", owner)
.build();
}
@Override
public void onEnable(Context context) {
Snapshot state = context.snapshot();
if (state.version() == 1) {
count = state.getLong("count", 0);
owner = state.getString("owner", "nobody");
}
}
| Member | Description |
|---|---|
static Snapshot EMPTY | What a freshly loaded plugin gets: version 0, no keys. |
static Builder builder(int version) | Starts a snapshot. The version must be at least 1. |
int version() | The schema version, or 0 for EMPTY. |
boolean isEmpty(), Set<String> keys(), boolean contains(String key) | What’s in it. |
String getString(String key, String fallback)long getLong(String key, long fallback)double getDouble(String key, double fallback)boolean getBoolean(String key, boolean fallback) | The value under key, or fallback if there is none or it has another type. |
byte[] getBytes(String key) | A copy of the bytes under key, or null. |
Builder.putString, putLong, putDouble, putBoolean, putBytes | Add a value. Putting a key twice keeps the last value. |
Builder.build() | Makes the snapshot. |
Events
public interface Events · public interface Event · @Subscribe
Listeners always run on the main thread. A listener for a type also receives its subtypes. There are two ways to listen:
// A lambda per event type.
context.events().listen(PlayerChatEvent.class, event -> {
if (event.message().contains("darn")) {
event.setMessage(event.message().replace("darn", "****"));
}
});
// Or every public @Subscribe method of an object.
context.events().register(new Object() {
@Subscribe
public void onJoin(PlayerJoinEvent event) {
context.log().info(event.playerName() + " joined");
}
});
| Method | Description |
|---|---|
<E extends Event> Registration listen(Class<E> type, Consumer<? super E> listener) | Calls listener for every event of type or a subtype. |
Registration register(Object listener) | Registers every public method of listener annotated with @Subscribe. Each must take exactly one parameter whose type implements Event. Throws IllegalArgumentException if a method has the wrong shape or there are none. |
void post(Event event) | Delivers event to all listeners. On the main thread this happens before post returns; from any other thread the event is queued for the main thread. |
Your own events implement Event. Keep them as plain data: an event can be queued and delivered later, possibly to a newer instance of a plugin after a reload. While a plugin is being reloaded its listeners receive nothing; events that arrive meanwhile are delivered once the reload finishes, to the new instance if it succeeded or to the old one if it was rolled back.
Built-in events
All are posted on the main thread. Player events carry the player’s UUID and name rather than a player object, so they stay plain data across reloads. Ask context.players() for a handle when you need one.
PlayerChatEvent
A player sent a chat message. Posted before the message is broadcast. After every listener has run, the server shows <name> message to everyone, unless the event was cancelled.
| Method | Description |
|---|---|
UUID playerId(), String playerName() | Who sent it. |
String message() | The message as it will be broadcast. |
void setMessage(String message) | Replaces the message. |
boolean isCancelled(), void setCancelled(boolean cancelled) | A cancelled message isn’t broadcast. Later listeners still see the event and may un-cancel it. |
PlayerJoinEvent
record PlayerJoinEvent(UUID playerId, String playerName). A player has joined and is in the world. Posted after the join message.
PlayerQuitEvent
record PlayerQuitEvent(UUID playerId, String playerName). A player has left. By the time listeners run, the player is no longer in context.players().
TickEvent
record TickEvent(long tick). Posted once per server tick, after scheduled tasks have run. Ticks are numbered from 1.
Commands
public interface Commands · public interface Command · public interface CommandSource
Players run a command by typing /name in chat; the console runs it without the slash. Commands run on the main thread and get the words after the name as a list.
// Anyone may run /hello.
context.commands().register("hello", "Say hello",
(source, args) -> source.reply("Hello, " + source.name()));
// Only the console and operators may run /secret.
context.commands().register("secret", "Operators only", "myplugin.secret",
(source, args) -> source.reply("You found it."));
| Method | Description |
|---|---|
Registration register(String name, String description, Command command) | Registers a command anyone may run. |
Registration register(String name, String description, String permission, Command command) | Registers a command only sources with permission may run. Today that means the console and operators. |
void Command.execute(CommandSource source, List<String> args) | Runs the command. It may throw; the error is logged and the sender told. |
String CommandSource.name() | Who ran it: a player’s name, or the console. |
void CommandSource.reply(String message) | Answers them. |
boolean CommandSource.hasPermission(String permission) | Whether they may use something guarded by permission. The console and operators may use everything; other players nothing that needs a permission. |
Names are lowercase letters, digits, _ or -, at most 32 characters. register throws IllegalArgumentException if the name is invalid or another plugin already uses it. The description is the line help shows. Players’ clients complete a plugin command’s name but not yet its arguments.
Players
public interface Players · public interface Player
context.events().listen(PlayerJoinEvent.class, event ->
context.players().get(event.playerId())
.ifPresent(player -> player.sendMessage("Welcome!")));
| Method | Description |
|---|---|
Optional<Player> get(UUID uuid) | The online player with this UUID. |
Optional<Player> byName(String name) | The online player with this name, ignoring case. |
Collection<Player> online() | Every online player, at the time of the call. |
void broadcast(String message) | Shows a message to every online player. |
Player
A Player is a handle to one connection. Once that player leaves, isOnline() is false and its actions do nothing, even if the same player joins again; ask context.players() for a fresh handle. Like every handle, it throws once your plugin instance is retired, so don’t keep handles from before a reload.
| Method | Description |
|---|---|
UUID uuid(), String name() | Who it is. |
boolean isOnline() | Whether this connection is still open. |
boolean isOperator() | Whether the player is a server operator. |
void sendMessage(String message) | Shows a message in the player’s chat. Does nothing if they’ve left. |
void kick(String reason) | Disconnects the player. Does nothing if they’ve left. |
On a server without networking there are no players: lookups come back empty.
Scheduler
public interface Scheduler
Runs code on the main thread, counted in ticks (20 per second). Tasks don’t run while their plugin is being reloaded.
// Every minute, starting in one minute.
context.scheduler().runRepeating(1200, 1200, () -> context.log().info("Still here"));
| Method | Description |
|---|---|
Registration runLater(long delayTicks, Runnable task) | Runs task once, delayTicks ticks from now. 0 or 1 means the next tick. |
Registration runRepeating(long delayTicks, long periodTicks, Runnable task) | Runs task every periodTicks ticks (at least 1), starting delayTicks ticks from now. |
Threads
public interface Threads
Use this instead of new Thread or an executor. When the plugin instance is retired, its threads are interrupted and the server waits briefly for them to finish, so write thread code that exits promptly when interrupted.
Thread worker = context.threads().newThread("myplugin-worker", () -> {
while (!Thread.currentThread().isInterrupted()) {
// ...
}
});
worker.start();
| Method | Description |
|---|---|
Thread newThread(String name, Runnable task) | Creates a daemon thread that runs task. It’s returned unstarted; call start() on it. |
Your threads run alongside the main thread, so share data with your listeners and commands safely. To hand work back to the main thread, post an event: from any other thread, it’s queued and delivered on the main thread.
Log
public interface Log
Writes to the server log, tagged with the plugin’s name: info(String message), warn(String message) and error(String message, Throwable error).
Registration
public interface Registration
Something a plugin registered: a listener, task, command or thread. The server cancels every registration of an instance when it’s retired, so you only need these to remove something earlier.
| Method | Description |
|---|---|
void cancel() | Removes the registration. Does nothing if it was already cancelled. |
boolean isActive() | False once it’s been cancelled or its plugin instance retired. |
A complete plugin
This is the counter plugin from examples/counter-plugin in the repository. count adds one, count show prints the counter and how many ticks the plugin has seen, and count reset sets it back to zero. The counter survives reloads.
public final class CounterPlugin implements Plugin {
// Bump when the snapshot layout changes, and teach restore() to read the old layout.
private static final int STATE_VERSION = 1;
private long count;
private long ticksSeen;
@Override
public void onEnable(Context context) {
restore(context);
context.events().listen(TickEvent.class, event -> ticksSeen++);
context.commands().register("count", "count [show | reset] - a counter that survives reloads",
(source, args) -> handle(source, args));
context.scheduler().runRepeating(1200, 1200,
() -> context.log().info("Count is " + count + " after " + ticksSeen + " ticks"));
context.log().info("Counter enabled at count " + count);
}
@Override
public Snapshot onReload(Context context) {
return Snapshot.builder(STATE_VERSION)
.putLong("count", count)
.putLong("ticksSeen", ticksSeen)
.build();
}
@Override
public void onDisable(Context context) {
context.log().info("Counter disabled at count " + count);
}
private void restore(Context context) {
Snapshot state = context.snapshot();
if (state.isEmpty()) {
return;
}
if (state.version() != STATE_VERSION) {
context.log().warn("Ignoring a state snapshot with unknown version " + state.version());
return;
}
count = state.getLong("count", 0);
ticksSeen = state.getLong("ticksSeen", 0);
}
private void handle(CommandSource source, List<String> args) {
String action = args.isEmpty() ? "add" : args.get(0);
switch (action) {
case "add" -> {
count++;
source.reply("count = " + count);
}
case "show" -> source.reply("count = " + count + ", ticks seen = " + ticksSeen);
case "reset" -> {
count = 0;
source.reply("count = 0");
}
default -> source.reply("Usage: count [show | reset]");
}
}
}