platform-paper - Paper / Folia Plugin
platform-paper is the plugin itself.
It is the layer that bridges to the platform APIs — Bukkit / Paper / Folia, Adventure, Brigadier, Plugin Messaging — and delegates domain models, algorithms, and the protocol to engine.
The paper side acts as an adapter absorbing "the reality of Bukkit / Folia", connecting engine's pure models to platform concerns (scheduler, threads, events).
Entry point and DI (Service Container)
Features are assembled via manual DI, without an external DI framework. The key idea is separating "the responsibility of construction" from "the responsibility of holding".
LunaticChat(JavaPlugin+Listener) — the plugin entry pointServiceInitializer— handles service construction, initialization order, and shutdownServiceContainer— an immutabledata classholding the constructed servicesPluginCoroutineScope—SupervisorJob+Dispatchers.Default; used for non-blocking work such asUpdateChecker
Lifecycle
The onEnable flow:
saveDefaultConfig()→ buildLunaticChatConfigurationviaConfigManager- Initialize
HttpClient(CIO)andPluginCoroutineScope ServiceInitializer.initialize()→ receive aServiceContainer- Move services into the public properties used by commands
schedulePeriodicTasks()→registerCommands()→registerEventListeners()- Start
UpdateCheckerifcheckForUpdatesis enabled
onDisable runs pluginScope.cancel() → serviceInitializer.shutdown(), closing settings, caches, channels, logs, and the Velocity connection in order.
ServiceContainer and ServiceInitializer
ServiceContainer holds always-available services (languageManager / playerSettingsManager / directMessageHandler) as non-null, and feature-gated ones (channelManager / velocityConnectionManager, etc.) as nullable fields (default null). The aim is to eliminate null-assertions (!!) from the codebase.
ServiceInitializer.initialize() creates services in dependency order.
LanguageManager(before commands; a prerequisite for all features)PlayerSettingsManager(always needed, e.g. for DM notifications)- Japanese conversion (optional)
- Channel group —
ChannelManager/ChannelMembershipManager/ChannelMessageHandler/ChannelNotificationHandler, plusChannelMessageLoggerwhen logging is enabled (optional) DirectMessageHandler(depends on settings, romaji, language)- Velocity integration (optional)
- Cross-server chat (only when velocity is enabled,
crossServerGlobalChatis on, and the velocity manager is non-null)
Feature Gating
This initialize() is where feature toggling actually happens. Japanese conversion / Channel group / Velocity integration / Cross-server chat are created only when their config flag is true, and are null otherwise.
config flag
→ ServiceInitializer creates a nullable service
→ stored in a nullable field on ServiceContainer
→ command / listener / SettingHandler registration branches on a null checkA disabled feature's service simply does not exist at the type level, and its code path is never built. The presence of a feature is expressed through Kotlin's null-safety.
For the design rationale, see the Design Overview.
Command framework (annotation-driven + Brigadier)
A command's definition and its metadata (permission, aliases, player-only) are declared together in one place, then read via Kotlin reflection and mapped onto the Brigadier tree.
Annotations
@Command(name, aliases, description)— command name, aliases, description@Permission(KClass<out LunaticChatPermissionNode>)— required permission (specified by type via the engine's permission node)@PlayerOnly— a player-only marker
LunaticCommand
The abstract base for all commands. It lazily reads the annotations on the class, and buildWithChecks() wraps the subclass's buildCommand() to inject shared behavior.
- If
@Deprecatedis present, it swaps in a handler that returns an error message at runtime - If
@Permissionis present, it attaches Brigadier's.requires { source.sender.hasPermission(perm) } handleResult()converts the engine'sCommandResultinto an Adventure message plus theIntfromtoBrigadierResult()withAliases()clones a Brigadier node to create alias nodes, andapplyMethodPermission()reflects a method-level@Permission
CommandRegistry
register / registerAll accumulate commands, and initialize() registers a handler on Paper's LifecycleEvents.COMMANDS. The actual Brigadier tree construction (buildWithChecks().build()) happens inside that lifecycle event.
Convention: root and nested subcommands
- Root command — annotate the class with
@Command - Nested subcommand — no
@Command; apply permission via abuild()method plus a method-level@PermissionandapplyMethodPermission("build", …)
Command hierarchy
| Command | Aliases | Registration condition |
|---|---|---|
lc (→ settings / status / channel) | lunaticchat | Always |
channel (14 subcommands) | ch | When channelChat is enabled |
tell | t / msg / m / w / whisper | Always |
reply | r | When quickReplies is enabled |
lcv (→ status) | lunaticvelocity | When velocity is enabled |
settings iterates SettingKey.values() to dynamically generate on/off/status nodes for each key and delegates to SettingHandlerRegistry. Adding a setting is a three-step process: "add a SettingKey → implement a Handler → register it in the Registry".
Chat processing
Routing (PlayerChatListener)
This is where routing happens, deciding "local (channel) vs. global (possibly via the proxy)". It hooks AsyncChatEvent at EventPriority.HIGHEST, ignoreCancelled = true.
Flow:
- Serialize the message to plain text and check for a leading
!(the force-global prefix) - If it is
!with an empty body, cancel the event and return (don't emit an empty message) - If the sender has romaji conversion enabled, run it through
convertWithRomaji - Determine whether the player has an active channel via
channelManager.getPlayerChannel()
Branches:
- Active channel and no
!→event.isCancelled = true+viewers().clear()+message(empty)to stop normal chat, then route toChannelMessageHandler.sendChannelMessage()(local to the server) - Otherwise (no active channel, or a
!prefix) →handleGlobalChat(). If velocity cross-server is enabled, send toCrossServerChatManager.sendGlobalMessage()while also displaying normal chat; otherwise, normal chat only
Direct messages (DirectMessageHandler)
Manages /tell・/reply state. Two ConcurrentHashMaps, lastMessager / lastRecipient, track reply targets, and getReplyTarget() returns an online player in the order "whoever messaged me → whoever I messaged".
sendDirectMessage() applies romaji conversion per the sender's settings → delivers a hover-annotated copy to spy players (excluding sender and recipient) → sends the formatted message to sender and recipient plus a notification sound (settings-dependent). The message carries a ClickEvent.suggestCommand that fills in /tell <sender>.
Channel chat (ChannelMessageHandler)
sendChannelMessage() resolves the active channel via channelManager.getPlayerChannelContext() (doing nothing if absent), then delivers to spies (excluding the sender and members) → delivers to all channel members plus a receiver notification sound → writes an NDJSON log via the engine's ChannelMessageLogEntry.create() when logging is enabled.
Channel state itself is managed by the chat/channel package.
ChannelManager— the single source of truth for channels. It holds state inchannelsCache/membersCache/activeChannels(ConcurrentHashMap), and its CRUD returnskotlin.Result, wrapping engine exceptions on failure. It checks config limits (0 = unlimited)ChannelMembershipManager— the business logic for join/leave/switch/role.joinChannel()checks existence / already-active / BAN / private-invite / already-a-member / membership limit in orderChannelStorage— persistsChannelDataas JSON (channels.json)ChannelMessageLogger— an asynchronous NDJSON logger with daily rotation, a size cap, and periodic deletion of files past the retention period
Listener registration
EventListenerRegistry(object) —SpyPermissionManagerandPlayerPresenceListenerare always registered;PlayerChatListeneris registered only when channel / velocity cross-server / romaji is enabled (Feature Gating again)PlayerPresenceListener— on Join: update notification, nightly warning, active-channel restoration notice; on Quit: clear DM references, deactivate the active channel, and save settingsSpyPermissionManager(object : Listener) — caches holders of theSpypermission on join/quit; referenced by the DM and channel handlers
config
ConfigManager— reads the mainconfig.ymlfrom Bukkit'sFileConfigurationby dotted keys and hand-assemblesLunaticChatConfiguration(note: this path is not KAML)- Feature defaults:
quickReplies=true,japaneseConversion=false,channelChat=false,velocityIntegration=false - Under
config/key:FeaturesConfig/ChannelChatFeatureConfig/JapaneseConversionFeatureConfig/VelocityIntegrationConfig/QuickRepliesFeatureConfig/MessageFormatConfig/ChannelMessageLoggingConfig
Implementation note
ChannelChatFeatureConfig.messageLogging is not loaded by ConfigManager and stays at its default values (enabled=true, retention=30, 100MB). Whether this is intentional needs confirmation — decide whether to fix it or document it as intended behavior.
i18n
Language(enum) —EN/JA; unknown codes fall back to ENLanguageManager— loadsresources/languages/with KAML at startup and flattens the nested YAML into dotted keys (toggle.on, etc.).getMessage(key, placeholders)resolves with selected-language → EN fallback and substitutes{placeholder}, returning the key itself if not found. A missing EN is a fatal errorMessageFormatter(object) — produces an AdventureComponentwith a[LC]prefix and highlights{braces}placeholders detected by regex
converter (paper side) — engine integration
The paper side handles the platform concerns of "cache management, timeouts, Bukkit scheduling", and delegates the conversion algorithm and API calls to engine.
RomanjiConverter— the two-stage conversion orchestrator. Per word: cache lookup → engineKanaConverterfor romaji→hiragana → engineGoogleIMEClientfor hiragana→kanji. Falls back to hiragana on API failureConversionCache— persists engineCacheDataas JSON. In-memory cache plus debounced save (a FIXME notes that eviction onmaxEntriesoverflow is effectively random due toConcurrentHashMapordering)RomajiConversionHelper—convertWithRomaji(). Calls synchronously viarunBlocking+withTimeoutOrNull(default 1000ms), returning"original §e(converted)"on success and the original text on failure/timeout
Velocity integration (Paper side)
Using the engine's protocol, it communicates with the proxy over Bukkit's Plugin Messaging Channel (lunaticchat:main). The actual cross-server routing is handled by the Velocity side; paper is responsible for "sending, receiving, deduplication, and formatted display".
VelocityConnectionManager(PluginMessageListener) — managesConnectionState(DISCONNECTED / HANDSHAKING / CONNECTED / FAILED). It encodes and sends the engine'sPluginMessage.Handshake, timing out after 5 seconds. To avoid a circular dependency,CrossServerChatManageris injected afterward (setter injection)- The handshake runs only once, triggered by the first player join (
AtomicBoolean). It is scheduled 1 second after the join viaasyncScheduler, and the result is received asHandshakeResult.Success/Error CrossServerChatManager— the send/receive and deduplication of global chat. On send, it registers the generatedmessageIdin the cache immediately to prevent an echo on its own server (stage one); on receive, it prevents duplicate display with a dedup cache keyed bymessageId(TTL 60s, oldest-first cleanup when overcacheSize). Bukkit API calls are moved to the main thread viascheduler.runTask
settings / common
PlayerSettingsManager— manages three boolean settings inConcurrentHashMaps. Uses the engine DTOs; unset values default to trueYamlPlayerSettingsStorage— reads/writesplayer-settings.yamlwith KAML. Recovers from a backup on load failure; debounced save (5s)UpdateChecker— hits the GitHub Releases API via Ktor and compares semver. The result is a sealedUpdateCheckResultSoundCollector— AdventureSoundconstants for notifications plus Player extension functionsPermissionCollector— a DSL that collects permissions via@PermissionDsl+ the+LunaticChatPermissionNodeoperator.requirePermissionthrows the engine'sRequirePermissionException