01 / DEVELOPER GUIDE
RIDDLES QUEUE · JAVA API · 1.15.0 · CONTRACT 3
Integrate game queues, whole-party admission, reserved capacity, persistent recovery, Paper/Folia scheduling, network observations and readiness into your plugin.
Queue owns ordering and capacity. Your game owns permissions, consent, arenas, player movement, match state and rewards. This guide explains the boundary, every public API group and the failure paths you must handle.
01 / DEVELOPER GUIDE
02 / DEVELOPER GUIDE
03 / DEVELOPER GUIDE
04 / DEVELOPER GUIDE
05 / DEVELOPER GUIDE
06 / DEVELOPER GUIDE
Use com.riddleslabs:riddles-queue-api:1.15.0 with provided/compileOnly scope. API contract version remains 3. The 1.15 waiting change does not add methods or change the wire contract, but upgrading from the old 1.13 packages requires a rebuild.
| Before 1.14 | Current |
|---|---|
NexusQueueBridge dependency/loader |
RiddlesQueueBridge |
com.cmriddles.nexusqueuebridge.* |
com.riddleslabs.queue.bridge.* |
NexusQueueBridgeApi |
RiddlesQueueBridgeApi |
com.cmriddles.nexusqueue.* implementation imports |
com.riddleslabs.queue.proxy.*; prefer public API contracts over implementation dependencies |
The unified com.riddleslabs.queue.api.RiddlesQueueApi entry point remains. Acquire the service after the backend enables and check availability/capabilities. Do not shade the API or install it as a separate server plugin. Old compiled bridge integrations are not binary compatible merely because API contract version is still 3.
Built-in waiting is owned by the proxy JAR. It does not become a new local game queue, standalone mode or backend service. Your game still owns transport and verified arrival; network observations, readiness, scheduling, reservations and persistence retain their documented contracts. See owner upgrade instructions and waiting-area limits.
Available in Queue 1.15.0. Paper/Folia plugins use one dependency and one service lookup:
com.riddleslabs.queue.api.RiddlesQueueApi.
For game queues, start with the five-step quickstart, then the complete method and recovery reference. A compiled integration component is included in examples/game-api.
The backend plugin supplies the API at runtime. Server owners install Core and the Queue backend JAR as usual. Do not install the API JAR in plugins/. Developers do not need a Core dependency for Queue integration.
scheduling().forPlugin(owner) provides global, region, entity and async scheduling through Core.games().registerPersistent(owner, options) adds opt-in local persistence and held restart recovery./rqgames gives owners inspection and revision-checked administrative controls.See operations and persistence for the complete workflow and the API audit for coverage and limits.
The artifact is com.riddleslabs:riddles-queue-api:1.15.0. It contains public contracts and models, with no Redis, SQL, Core or queue engine implementation. This release builds it locally; it has not been published to a public Maven repository.
From the Queue workspace, install it into your development machine's Maven repository with JDK 25:
mvn -f RiddlesQueueApi/pom.xml -Dmaven.test.skip=true -DskipITs=true install
Maven consumers:
<dependency>
<groupId>com.riddleslabs</groupId>
<artifactId>riddles-queue-api</artifactId>
<version>1.15.0</version>
<scope>provided</scope>
</dependency>
Gradle consumers, after the local installation above:
repositories { mavenLocal() }
dependencies { compileOnly("com.riddleslabs:riddles-queue-api:1.15.0") }
Continue using your normal Paper API dependency. Do not shade or relocate Queue's API classes into your plugin: the server must use the classes supplied by Queue. API bytecode targets Java 21, consistent with Queue's documented server runtime requirements.
For a native Paper plugin, add this to your paper-plugin.yml:
dependencies:
server:
RiddlesQueueBridge:
load: BEFORE
required: true
join-classpath: true
RiddlesQueueBridge is the current backend loader ID, including standalone mode. Use it in paper-plugin.yml or depend: [RiddlesQueueBridge] in plugin.yml. The backend loads at POSTWORLD; acquire its service after it enables.
If integration is optional, use an optional dependency and isolate Queue-dependent classes until Queue is present. A missing API class cannot be handled merely by checking whether a service lookup returns null.
import com.riddleslabs.queue.api.RiddlesQueueApi;
// In your plugin's onEnable(), after Queue has enabled:
RiddlesQueueApi queue = getServer().getServicesManager()
.load(RiddlesQueueApi.class);
if (queue == null || !queue.isOpen()) {
// Queue may have failed startup. Keep your integration unavailable.
return;
}
One lookup provides the existing capabilities:
| Accessor | Standalone server | Network backend |
|---|---|---|
standalone() |
Local status, counts and capacity | Empty |
network() |
Empty | Queue observations and priority points |
readiness() |
Empty | Game/server readiness registrations and subscriptions |
games() |
Local developer game queues | Local developer game queues |
scheduling() |
Owner-scoped Paper/Folia tasks | Owner-scoped Paper/Folia tasks |
These are grouped interfaces in one API dependency, not extra plugins or separate service lookups. Empty optionals mean the feature is unavailable in that mode. mode() distinguishes network, reconnect and waiting-world operation. capabilities() is an immutable set describing supported interfaces; it does not guarantee transport connectivity or game readiness. isOpen() describes the API lifecycle only.
queue.standalone().ifPresent(local -> {
var status = local.status(playerId); // UUID; null requests aggregate counts
int position = status.position();
int waiting = status.waiting();
int playingAndReserved = status.active();
// Read-only snapshot. Position zero means not currently waiting.
});
The local snapshot is safe to read from any thread. It includes pending gameplay reservations in the active count. State and mode strings retain the existing standalone contract.
queue.network().ifPresent(network -> {
if (!network.isRuntimeAvailable()) return;
network.queueStatus(playerId, "survival").whenComplete((status, failure) -> {
if (failure != null || !status.available()) {
// Show unavailable through your own correctly scheduled UI.
return;
}
// Observe status.position(), status.positionScope(), status.workflow().
// This callback does not promise a player/region thread.
});
});
Availability can change after the check, so handle failed futures and unavailable results. network() also provides queue listings, effective weight and points operations. Prefer the existing operation-ID overloads for retryable point mutations; keep the same operation ID when retrying the same intent. Receipt-capable storage is required. An unknown outcome or NOT_FOUND receipt does not prove that a mutation never committed.
Never call join() or get() on these futures from a tick or region thread. Schedule player/world interactions on the owning entity/region scheduler. This API does not require consumers to use Core for scheduling.
import com.riddleslabs.queue.bridge.api.readiness.ApplicationReadiness;
import java.time.Duration;
import java.util.Set;
var readiness = queue.readiness().orElseThrow(
() -> new IllegalStateException("Readiness requires network backend mode"));
var registration = readiness.register(this, "mygame:arena",
Set.of("RESETTING", "ACCEPTING"));
boolean accepted = registration.publish(new ApplicationReadiness.Observation(
1, System.currentTimeMillis(), ApplicationReadiness.State.STARTING,
"RESETTING", Duration.ofSeconds(15)));
Keep the registration in your plugin, publish increasing sequence numbers, and renew it before its 1–30 second lease expires. Publish READY only when the game can receive players. Inspect the boolean result: rejected observations do not renew the lease. Close registrations and subscriptions on shutdown. A bridge configuration reload changes the registry generation and invalidates old registrations; re-register when the generation changes or the handle closes.
For a provider to gate admission, the owner must configure its ID under admission-report.required-providers in the backend configuration, and enable the relevant network admission/reporting integration. Registering an optional provider alone does not stop incoming players. This existing readiness mechanism is backend-wide, not an independent per-arena match queue.
Readiness subscriptions deliver immutable snapshots on background workers. Updates can coalesce; Update.gap() tells consumers to use the latest snapshot rather than assume every intermediate change was delivered. Do not touch world/player state directly from those callbacks.
isOpen() == false and empty capabilities/accessors after shutdown. Operations already obtained can race shutdown and must handle failure. Existing grouped interfaces retain their original lifecycle semantics.StandaloneQueueApi, RiddlesQueueBridgeApi, ApplicationReadiness, their DTOs and ApiProvider retain their packages and signatures. Existing service registrations remain. Their sources now live in the API module and are bundled into the backend once.Queue 1.15.0 adds owner-managed game queues. Use the single RiddlesQueueApi dependency for lobby queues, arena entry, dungeon groups and event admission. Queue manages ordering and reserved capacity. Your game owns eligibility, consent, arenas, transport, matches and rewards.
Start here. Use the dependency guide for Maven/Gradle and plugin loading declarations, and API reference and recovery rules for the complete contract.
In your plugin's onEnable(), after its required RiddlesQueueBridge dependency:
import com.riddleslabs.queue.api.RiddlesQueueApi;
import com.riddleslabs.queue.api.game.*;
var api = RiddlesQueueApi.find(getServer())
.orElseThrow(() -> new IllegalStateException("Riddles Queue is unavailable"));
GameQueue arena = api.games()
.orElseThrow(() -> new IllegalStateException("Queue 1.15.0+ is required"))
.register(this, QueueOptions.builder("mygame:duos")
.capacity(8)
.minimumAdmissionPlayers(4)
.maxPartySize(2)
.maxWaitingPlayers(100)
.build());
Keep the returned GameQueue field. The namespace prevents ID collisions. Only your registration handle can mutate this queue; public discovery returns read-only counts. Register once, not per command or player.
Game queues work in both standalone and network-backend mode. They are local to this server and are separate from the server-entry queue. In standalone waiting-world mode, admit the player through the server-entry queue before attempting gameplay transport.
After checking your game's permission, eligibility, online status and each party member's consent:
var result = arena.join(playerId);
if (!result.successful()) {
// Translate result.code() for your UI: FULL, PAUSED, PLAYER_ALREADY_QUEUED, etc.
return;
}
TicketSnapshot ticket = result.requireValue();
For a party, keep a stable ticket ID if your application may retry the same request:
var result = arena.join(new JoinRequest(ticketId, Set.of(leaderId, teammateId), 0));
The third argument is a trusted priority weight; higher weights go first, with FIFO among equal weights. Never accept a player's claimed weight directly. Parties join and reserve places together. A player cannot simultaneously occupy another developer game queue on this backend.
Display arena.player(playerId) for position. ticketPosition() counts waiting parties/tickets; playersAhead() counts people. Position is zero when the ticket is no longer waiting. Label the two clearly in your UI.
var offer = arena.reserve(requestId, 4, 8);
if (!offer.successful()) return; // Often NOT_ENOUGH_PLAYERS or NO_CAPACITY.
AdmissionSnapshot admission = offer.requireValue();
if (admission.state() != AdmissionSnapshot.State.OFFERED) return;
var started = arena.begin(admission.id());
if (started.code() != QueueResult.Code.SUCCESS) return;
// Now dispatch your game transport for started.requireValue().players().
Use a new requestId for a new batch and the same ID for a retry of that batch. A retry can return a previously completed or cancelled receipt: inspect its state. Only the first successful begin() authorizes dispatch. ALREADY_APPLIED does not authorize dispatching again.
With minimum 4 and maximum 8, a batch can contain 4–8 players. Use 8, 8 for exactly eight. A party is never split to fill a batch, and the engine does not skip the next party to select smaller groups behind it.
Reserve only after selecting a usable arena. If arena preparation fails before begin(), use cancel(admissionId, REQUEUE) to return everyone to their original order. No teleport starts automatically.
If your game selects players by rating, teams or map preference, pass its chosen whole ticket IDs to reserveTickets(requestId, ticketIds) instead. Queue still checks capacity and reserves the entire selection atomically; your game owns the matching rule.
On a player's owning Paper/Folia thread, perform your teleport or game-entry operation. After verifying arrival, call:
arena.arrived(admissionId, playerId);
If that participant fails to arrive or disconnects during admission:
arena.failed(admissionId, playerId, "TRANSFER_FAILED");
Queue operations themselves are safe from any thread. Your world/player operations are not: use your normal Paper/Folia scheduling. Never block a region/tick thread waiting for a future.
A dispatching batch becomes active after every player is confirmed. Failures and transfer timeouts make the batch HELD, keeping all its slots reserved. Inspect arrived(), failed() and pending() on its admission snapshot to guide recovery. A held batch never automatically becomes active because of a late callback.
If a timed-out batch has subsequently arrived in full, has no failed participants, and your game has reverified everyone, call complete(admissionId). If anyone is marked failed, evacuate the batch and recover it instead.
After a match ends, move each player out of the occupied game slot, then call arena.departed(ticketId, playerId). Also hook confirmed player disconnects. Capture the ticket ID with the player's connection/game session so an old callback cannot remove a newer ticket for the same UUID. Waiting-player departure removes their whole party; active-player departure releases only that player's place.
departed() atomically cancels an undispatched offer before removing the departing party. If dispatch has started, it marks the participant failed, holds all capacity and returns RECOVERY_REQUIRED. Follow recovery in that case. For a voluntary queue-leave request that does not prove actual departure, use leave(); it refuses reserved states. Use its ticket-ID overload for asynchronous requests.
Before disabling your game, stop new work, cancel/fence outstanding transport, evacuate players and close subscriptions, then close the queue. Queues are also withdrawn automatically when their owner disables. Live hot-unloading a game while transfers are in flight is unsupported. These game queues are session state, not a durable match database.
ArenaQueueIntegration.java is a small integration component compiled with the release. It demonstrates:
Implement its Transport interface using your game's scheduler and arrival verification. Connect join() to your menu/NPC/command and departed() to confirmed departures. The example is not a complete minigame, an installable plugin or a test. It has not been run on a server.
This quickstart uses a session queue. For persistent registration, save-before-dispatch, held recovery and execution ownership, follow operations and persistence. Do not switch an existing persistent queue back to register(); it intentionally refuses to ignore saved state.
| QueueOptions builder field | Default | Allowed values |
|---|---|---|
capacity |
16 | 1–4096; includes offered, transferring, held and active players. |
maxWaitingPlayers |
1000 | 1–10000. |
maxPartySize |
1 | 1–64, no greater than capacity. |
minimumAdmissionPlayers |
1 | 1–capacity. |
offerTimeout |
15 seconds | 1 second–5 minutes. |
transferTimeout |
30 seconds | 1 second–5 minutes. |
Use QueueOptions.builder("mygame:arena"). Namespaced IDs match [a-z0-9_.-]{1,32}:[a-z0-9_.-]{1,32}. IDs are unique across owners on this backend. JoinRequest(ticketId, players, priority) contains 1–64 distinct player UUIDs and a priority from 0–1,000,000. Queue-specific party limits still apply. JoinRequest.player() and .party() generate fresh IDs with priority zero; retain an explicit ID when retrying.
| Snapshot | Fields and interpretation |
|---|---|
QueueSnapshot |
ID, revision, open, paused, capacity, waiting players/tickets, occupied, active, held. availableSlots() is max(0, capacity − occupied). |
TicketSnapshot |
ID, players, priority, state, ticket position, players ahead, admission ID. Positions are zero outside waiting. States: WAITING, OFFERED, DISPATCHING, HELD, ACTIVE. |
AdmissionSnapshot |
ID, ticket IDs, players, arrived, failed, state, deadline epoch milliseconds, reason. pending() excludes arrived and failed. States: OFFERED, DISPATCHING, HELD, COMPLETED, CANCELLED, RECOVERED. |
QueueUpdate |
Queue snapshot, change kind, optional ticket/admission IDs, gap flag. Revision is on its snapshot. |
QueueResult<T> |
Code plus nullable value. successful() includes SUCCESS and ALREADY_APPLIED; only SUCCESS from begin authorizes transport. |
An admission's COMPLETED state corresponds to its tickets being ACTIVE. Do not compare ticket and admission state enums as though they are identical. Query results are observations; another thread may change state immediately afterward. Use atomic mutation results to decide what happened.
Pagination offsets are nonnegative and page limits are 1–100. tickets() follows original join order and includes active/held tickets; waiting() follows selection order; admissions() is newest first. Pages read across changes are not a transaction.
Registration and scheduler lookup require a valid enabled plugin lifecycle. Queue operations can return domain failures; invalid arguments and registration errors can throw synchronously. Persistent registration can also fail its returned stage. Check all three paths in your integration.
Use the quickstart first. All types are supplied by the single com.riddleslabs:riddles-queue-api:1.15.0 dependency. API contract version is 3; the new games() method has a default empty implementation to preserve older implementations. Existing standalone, network and readiness contracts retain their original signatures.
New in 1.13: administrator controls, owner scheduling and persistence. Public methods added to existing interfaces have default implementations for binary compatibility; these features originated in 1.13. The examples and imports on this page target 1.15.0; inspect capabilities before use.
| Task | Method | Important behavior |
|---|---|---|
| Discover Queue | RiddlesQueueApi.find(server) |
Optional live entry point; call during the server/plugin lifecycle. |
| Create a queue | api.games().get().register(owner, options) |
Owner-scoped handle, globally unique namespaced ID. |
| List queues | games.snapshots() / find(id) |
Read-only snapshots. |
| Add one player | queue.join(playerId) |
Convenience request with a new ticket ID. |
| Add/retry a party | join(JoinRequest) |
Same ticket ID and same original request are idempotent while retained. |
| Inspect a participant | player(uuid) / ticket(ticketId) |
Immutable ticket and accurate rank population. |
| Browse all tickets/receipts | tickets(offset, limit) / admissions(offset, limit) |
Includes held/active work; limit 1–100. |
| Browse waiting tickets | waiting(offset, limit) |
Ordered pagination; limit 1–100. |
| Remove/release a player | leave(playerId) |
Waiting: entire party. Active: just this player. Reserved states refuse. |
| Fence an asynchronous leave | leave(ticketId, playerId) |
Rejects old work if the player now has a different ticket. |
| Handle confirmed departure | departed(ticketId, playerId) |
Atomically cancels an undispatched offer or holds a dispatched batch and marks this participant failed. |
| Change waiting priority | priority(ticketId, weight) |
FIFO sequence stays unchanged; active/offered tickets refuse. |
| Pause admissions | pause(true) |
Stops joins, reservations and new dispatch; existing transfers can finish. |
| Change capacity | capacity(value) |
Cannot reduce below occupied slots or configured party/minimum batch limits. |
| Reserve a batch | reserve() or reserve(requestId, min, max) |
Atomically charges capacity; no player transport. |
| Apply your matchmaking rules | reserveTickets(requestId, ticketIds) |
Atomically selects whole waiting tickets; explicitly overrides default priority/FIFO. |
| Start dispatch | begin(admissionId) for session queues; beginDurable(id) for persistent queues |
Only SUCCESS authorizes first dispatch. Persistent success follows a saved dispatch snapshot. |
| Record verified arrival | arrived(admissionId, playerId) |
Completes only a dispatching batch; held batches require explicit completion. |
| Record participant failure | failed(admissionId, playerId, reason) |
Clears that participant's arrival, records failure, holds all capacity. |
| Hold uncertain work | hold(admissionId, reason) |
Stops automatic completion and retains all capacity. |
| Complete held work | complete(admissionId) |
Requires all players recorded arrived and no failed players; owner reverifies first. |
| Cancel before dispatch | cancel(id, REQUEUE/REMOVE) |
Cannot cancel dispatched/held work this way. |
| Recover after evacuation | recover(id, recovery) |
Held batches only; caller must prove every player is out and late arrivals are fenced. |
| Inspect admission progress | admission(id) / admissions(limit) |
Who arrived, failed or is pending; reason and deadline. Recent list limit 1–100. |
| Observe updates | subscribe(listener) |
Serial per subscription, bounded background delivery, coalescing. |
| Dispose | close() |
Withdraws the queue; owner must first clean up actual games/players. |
WAITING -> OFFERED -> DISPATCHING -> ACTIVE
| |
| +-> HELD -> verified completion -> ACTIVE
| |
+-> cancel +-> verified evacuation -> requeue/remove
occupiedPlayers includes offered, dispatching, held and active tickets. An offer timeout safely requeues because dispatch has not begun. A transfer timeout only holds capacity. A clock or timer is not proof that a teleport failed.
Reservation and membership decisions are synchronized in memory. Queue never calls game code, blocks on SQL, performs a teleport or waits on a network request while making them. Counts are maintained incrementally; waiting order uses a sorted set. Rank/pagination reads traverse waiting tickets as needed. This describes the implementation, not a measured throughput claim.
Default selection uses highest priority first, then FIFO. Whole parties at the front can leave some capacity unused; default selection does not split or bypass them. Higher-priority traffic can delay lower tiers. Returning a cancelled/evacuated batch to waiting preserves its original sequence and priority.
For rating, team, map or other game-specific matching, use reserveTickets(requestId, ticketIds) after your matchmaker selects whole waiting tickets. This explicitly overrides default ordering, while preserving membership/capacity checks, the configured minimum player count and the same admission/recovery lifecycle. A concurrent leave/reservation causes an explicit failure, not a partial selection. Queue does not calculate ratings or teams for you.
The waiting limit gates new joins. Returning an already reserved batch may temporarily put the waiting count above that limit so existing tickets are not lost. Total tracked membership remains bounded.
state, players, arrived, failed, pending and reason.complete().recover(id, REQUEUE_AFTER_EVACUATION) or REMOVE_AFTER_EVACUATION.Recovery intentionally requires whole-batch evacuation; it does not silently split a partially transferred party. failed() marks a participant as requiring evacuation recovery; a later arrived() for that player returns RECOVERY_REQUIRED. A recovered/cancelled receipt rejects old arrival callbacks. A fresh reservation gets a fresh admission ID.
Queue cannot prove where a player is or cancel another plugin's asynchronous teleport. The game must supply that evidence and fencing. Do not call recovery merely because a timeout elapsed.
| Code | Meaning / normal response |
|---|---|
SUCCESS |
Applied now. |
ALREADY_APPLIED |
Retry of retained work; inspect returned state, do not dispatch twice. |
FULL |
New join exceeds waiting limit. |
PAUSED |
Owner paused new admissions. |
PLAYER_ALREADY_QUEUED |
At least one member already belongs to a developer game queue on this backend. |
NOT_ENOUGH_PLAYERS |
Cannot form the requested batch in order without splitting a party. |
NO_CAPACITY |
Insufficient unreserved slots, or unsafe capacity reduction. |
RECOVERY_REQUIRED |
Work may have started; inspect and reconcile rather than releasing blindly. |
NOT_FOUND |
Unknown player/ticket/admission, including expired history. |
ID_CONFLICT |
Same request ID reused with different arguments. |
INVALID_STATE |
Operation does not apply to this lifecycle state or a recently retired ticket. |
CLOSED |
Queue/service owner stopped. Reacquire/register only at an appropriate lifecycle boundary. |
DURABILITY_REQUIRED |
Use beginDurable() for a persistent queue. |
STORAGE_UNAVAILABLE |
Saving failed; new admissions stop until a successful save. Inspect and retry checkpoint; do not redispatch. |
LIMIT_REACHED |
Registry/receipt/participant bound reached; inspect outstanding work. |
QueueResult.value() is null on failures. Use successful() before reading it. requireValue() is a convenience that throws on failure; avoid it for expected gameplay failures unless already checked. Invalid developer arguments throw IllegalArgumentException; duplicate registration, stopped owners and registration/subscription limits throw IllegalStateException or IllegalArgumentException with an explanation.
Reason codes are uppercase letters/digits/underscores, up to 48 characters. Map codes to your language files. Do not pass chat, usernames or secrets as reasons.
GameQueue.Subscription subscription = arena.subscribe(update -> {
QueueSnapshot counts = update.snapshot();
// Publish immutable data to your UI adapter. No direct Bukkit player/world calls here.
if (update.gap()) {
// Query current tickets/admissions; intermediate changes were coalesced.
}
});
The first update is a snapshot, or a later coalesced update marked with a gap. Updates contain a revision, change kind and optional ticket/admission IDs. They are observations, not a reliable event journal or dispatch authorization. Reserve/begin results are authoritative for starting work. A global snapshot revision can advance while the consumer processes an older notification.
Callbacks are serialized per subscription on a bounded Core worker pool. Different subscriptions can run concurrently. Three consecutive callback failures or worker rejection close that subscription; inspect isOpen() and the console notice. One callback already running can finish after close. Closing the queue prevents future delivery. Do not perform blocking work in callbacks.
All game queue operations are safe from any thread and use only IDs/immutable values. Bukkit world/player work still requires the owning Paper/Folia scheduler. The API has no direct Core dependency for consumers.
Ordinary register() still creates a local session queue. Opt-in registerPersistent() adds local restart recovery, documented in operations and persistence. It does not create shared cross-server authority. Saved receipts remain bounded and are not forever-valid deduplication keys. Existing proxy queue persistence and points receipts are unchanged.
The service withdraws queues when their owner disables and closes its own queues on shutdown. Live hot-unload during a transfer is unsupported: clean up game sessions before disabling. Stored handles become closed and are never rebound to a newly registered queue with the same name.
One dependency: com.riddleslabs:riddles-queue-api:1.15.0. Contract version: 3. Core remains a server dependency of Queue; your plugin uses only Queue's API with provided/compileOnly scope. Examples on this page target Queue 1.15.0 and its renamed packages.
The backend registers /rqgames in standalone and network modes. Bridge diagnostics default to /rq. riddlesqueue.games.view and riddlesqueue.games.admin default to operators. Inspection works in game; mutations are console-only. No console command dispatches or teleports a player.
| Command | Purpose |
|---|---|
rqgames list |
Loaded queues and saved queues awaiting their owning plugin. |
rqgames status game:arena |
Owner, revision, pause, waiting/occupied/held counts, persistence and save health. |
rqgames player game:arena player-uuid |
Exact ticket, party rank, players ahead and admission. |
rqgames admissions game:arena [page] |
Ten recent receipts per page, newest first. |
rqgames inspect game:arena admission-uuid [page] |
Twenty participants per page; arrival, failure or unconfirmed; coherent revision for action. |
rqgames pause game:arena revision |
Stop new joins, reservations and dispatch. In-flight transport may still finish. |
rqgames resume game:arena revision |
Resume after owner reconciliation; this does not clear held capacity. |
rqgames capacity game:arena count revision |
Change capacity without reducing below occupied/configured limits. |
rqgames priority game:arena ticket-uuid weight revision |
Change a waiting party's priority, retaining FIFO sequence. |
rqgames departed game:arena ticket-uuid player-uuid revision confirm-departed |
Confirmed departure: remove waiting party, release active player, or hold uncertain transfer. |
rqgames cancel game:arena admission-uuid REQUEUE\|REMOVE revision |
Cancel an OFFERED batch that has never started dispatch. |
rqgames recover game:arena admission-uuid requeue\|remove revision confirm-evacuated |
Paused HELD batch only, after verified whole-batch evacuation and fencing late transport. |
rqgames complete game:arena admission-uuid revision confirm-arrivals |
Paused HELD batch with all arrivals already verified by its owner and no failed members. |
rqgames save game:arena |
Explicit checkpoint and acknowledgement. |
rqgames language reload |
Reload the shared Core language catalog, including when ordinary bridge commands are disabled. |
Use the revision printed by status/inspect. Rejections after a concurrent change require fresh inspection. Successful mutations are logged with the actor, operation and result, then checkpointed if persistent. A failed save does not undo a mutation; inspect before retrying. A RECOVERY_REQUIRED departure can itself record a failure/hold, and that is checkpointed too.
Messages live under messages.games in languages/en.yml, with the normal Core fallback and locale settings. Existing translations are retained. Headings stay short. UUIDs are explicit to avoid resolving player names on the wrong thread.
recover ... confirm-evacuated.A restart discards stale arrival evidence and restores occupied work as HELD. It cannot infer that a player arrived or disconnected safely. The console cannot invent an arrival record or override a failed participant. Do not delete a state file to bypass recovery.
RiddlesQueueApi api = RiddlesQueueApi.find(getServer()).orElseThrow();
QueueScheduler tasks = api.scheduling().orElseThrow().forPlugin(this);
QueueTask handle = tasks.entity(player, () -> player.sendMessage(message), () -> {
// Entity retired: lightweight bookkeeping only. No world/entity access here.
});
Import scheduling types from com.riddleslabs.queue.api.schedule.
| Context | Methods | Use |
|---|---|---|
| Entity | entity, entityDelayed, entityRepeating |
Players/entities; follows region ownership; includes retired callback. |
| Region | region, regionDelayed, regionRepeating |
A world and chunk X/Z; block/chunk work in that region. |
| Global | global, globalDelayed, globalRepeating |
Global server state. Not a universal main thread on Folia. |
| Async | async, asyncDelayed, asyncRepeating |
Non-world background work. Do not use for unbounded/blocking workloads. |
Tick delays/periods must be at least one; async delays use positive Duration. QueueTask exposes state, cancellation and isDone. Close cancels future invocations; running code may finish. Tasks are cancelled automatically when the owning plugin disables or Queue stops. Up to 64 owner scopes and 256 outstanding tasks per owner; Core's module-wide limit also applies. Rejection throws explicitly. Core records callback failures through its scheduler diagnostics.
A scope is shared for that plugin. Close it only when all of that plugin's components are finished. Never close Core's scheduler. Registration and scope lookup belong in a valid plugin lifecycle context. Futures, subscriptions and retired callbacks do not grant world ownership. Use a captured entity reference or separately schedule the appropriate world/region context; do not resolve and mutate Bukkit players from a file callback.
Existing register(owner, options) remains session-only. Opt in explicitly:
api.games().orElseThrow().registerPersistent(this, options)
.whenComplete((queue, failure) -> {
if (failure != null) {
// Keep this game unavailable; report the cause. Existing files are preserved.
return;
}
// Publish the handle safely. This callback may run on a Core file worker.
// Restored queues are paused: inspect/reconcile before resuming.
});
Do not call join()/get() on this future during enable or on a tick/region thread. An initial empty snapshot is saved before a new persistent handle is returned. Owner name and full original QueueOptions must match on restore. Runtime capacity/priority changes are saved separately and survive. A session registration refuses an existing saved queue, preventing accidental loss by switching off persistence.
State is stored below the backend data directory in game-queues/<namespace>~<name>.bin. It contains queue options, ticket IDs, original join requests, current members, FIFO order, priority, capacity, receipts and retired ticket IDs. This binary state is not a configuration file. It is versioned, size-bounded and checksummed; Core confines its paths, forces the replacement file and atomically replaces it. Atomic replacement support is required. This is local filesystem recovery, not a cross-server transaction or a guarantee against every storage/power failure.
Queue inventories saved memberships during startup before consumers can join other game queues. Missing owners keep those memberships reserved. Invalid/corrupt inventories quarantine developer game queue registration and appear in Core's game-queues health; the existing bridge/standalone runtime remains separate. A rejected registration never overwrites that queue's original file. Save and restore failures are visible in health/logs.
QueueResult<AdmissionSnapshot> reserved = queue.reserve(requestId, 4, 8);
if (reserved.successful()) {
queue.beginDurable(reserved.requireValue().id()).thenAccept(started -> {
if (started.code() != QueueResult.Code.SUCCESS) return;
// Only now ask your transport adapter to schedule/verify player movement.
// Do not directly touch Bukkit world/player state in this file-worker callback.
});
}
Ordinary begin() returns DURABILITY_REQUIRED for a persistent queue. beginDurable() records DISPATCHING, checkpoints, then authorizes only the first caller with SUCCESS, provided the queue/admission remains open, unpaused and unexpired. Retries return ALREADY_APPLIED, which never authorizes redispatch. A save failure holds capacity and blocks new admissions until saving recovers. Future cancellation does not cancel the reservation or prove that a write/transfer failed.
Normal mutations auto-save within roughly five seconds while workers are available. They are not acknowledged durable until checkpoint() completes. Use checkpoints for acknowledged joins, departure/recovery changes or shutdown. A failed checkpoint can leave an in-memory change applied. Never retry transport merely because a future failed.
Restored queues always start paused. Saved WAITING tickets retain order and priority. Saved OFFERED, DISPATCHING, HELD and remaining ACTIVE participants become HELD with RESTART_RECOVERY; none are silently freed or automatically dispatched. Previous arrival/failure observations are cleared so the owner must establish current facts. Terminal unreferenced receipts and bounded deduplication history are retained. After verified recovery, checkpoint before acknowledging it.
Stop your matchmaker, fence pending transports and clean up or explicitly hold matches before owner shutdown. closeAsync() captures a final snapshot and completes after that save; close() initiates the same process without waiting. The backend's Core shutdown hook submits saves before workers close. A forced stop can lose recent uncheckpointed changes. Owner disable is not an automatic evacuation.
Closed persistent queues retain participant reservations until restored. Re-registering the same ID waits for its final save; a failed final save refuses re-registration in that session. Handles from the old lifetime stay closed. Existing proxy/standalone persistence is unchanged.
Bounds: 64 registered queues, 16 per owner; 64 durable queue IDs; 50,000 active plus unclaimed saved participants. Snapshot maximum is 4 MiB per queue, also constrained by Core's files.max-bytes (default 2 MiB). Aggregate snapshot budget is 32 MiB, accounted conservatively by per-queue high-water size until restart. Do not increase capacities blindly; keep state within those limits. Existing receipt and party limits still apply.
Persistence is optional, local and owned by one backend. It does not replicate queues, resume game worlds, charge/refund economy or manage your game's match database. Do not share these files between running backends or edit them externally.
ArenaQueueIntegration: session queues and transport contract.PersistentArenaIntegration: persistent registration, checkpointed joins, durable dispatch, recovery, shutdown and entity scheduling.Both are source components compiled with the production reactor; neither is an installable example plugin or a test.
These are backend-to-proxy operations from api.network(). They do not expose network queue join, leave, teleport, or matchmaking commands. Local GameQueue.join() is a different operation.
| Method | Result and handling |
|---|---|
isRuntimeAvailable() |
Local runtime availability check only. The transport can fail immediately afterward. |
proxyStatus() |
CompletableFuture<ProxyStatus>: success, proxy type/version, message and error code. |
queueStatus(UUID player, String targetHint) |
Future of QueueStatusView. Player is required; null target hint becomes an empty hint. Check available() before displaying counts. |
queueTop(String target, int limit) |
Future of QueueTopView. Target must not be blank; limit is clamped to 1–500. |
pointsGet(UUID player) |
Future of PointsResult. Check both future failure and success(). |
pointsAdd, pointsTake, pointsSet |
Future of PointsResult; legacy overloads take player UUID, long amount/value, reason. Retryable overloads additionally take operation UUID first. |
pointsOperation(UUID operationId) |
Future of PointsOperation: operation ID, status, before/after points, commit time. Reconcile uncertain outcomes with the original operation ID. |
effectiveWeight(UUID player) |
Future of Long. Proxy errors complete exceptionally. |
PointsResult contains success, nullable points, message, and errorCode. Do not unbox points without checking for null. An operation can return an ordinary error DTO or fail its future, so handle both. Blank/null point reasons are replaced with paper-bridge by the backend adapter. Use trusted server-side values; this API does not decide whether a player is allowed to receive points.
Persist a unique operation UUID with your business action before submitting a retryable point change. Reuse it for retries of that same intent, never for a different payment/reward. Receipt-capable proxy storage is required. Legacy overloads do not supply a durable business identity. A missing receipt or lost reply is not permission to invent a new operation UUID and apply the change again.
// In a method that receives a previously persisted operationId and playerId:
network.pointsAdd(operationId, playerId, 25L, "EVENT_REWARD")
.whenComplete((result, error) -> {
if (error != null) {
// Outcome uncertain: retain the same operation ID and reconcile.
return;
}
if (!result.success()) {
// Inspect errorCode/message; do not blindly submit a new operation.
return;
}
// Acknowledge the business action in your own durable store.
});
QueueStatusView exposes availability, in-queue state, target, position, size, ETA milliseconds, effective weight, points, state, fetched-at time, workflow, position scope, ticket state, targets and party size. Position units depend on positionScope; do not label every workflow as an individual-player rank. fresh(ttlMillis) requires availability and a nonnegative age within the supplied TTL; it does not refresh anything.
QueueTopView contains availability, target, entries and fetched-at time. safeEntries() normalizes a null list; entryAt(index) returns null outside the list. Each entry has UUID, name, position, ETA, weight and workflow/party fields.
1.15.0 implementation limitation: the backend mapQueueTop adapter copies only UUID, name, position, ETA and weight from each protocol row. The other fields therefore take constructor defaults (ordinary, local-players, party size 1, QUEUED), even when the protocol row contains richer metadata. Do not use those queue-top fields as authoritative subscription/party information. This is a source-confirmed limitation, not a corrected implementation in this documentation update.
Queue-status and queue-top proxy error responses become available=false snapshots; those adapters do not retain the detailed proxy error code. Unexpected response types fail the future. Do not treat an unavailable snapshot as an empty healthy queue.
api.readiness() is present in network mode. ApplicationReadiness remains in com.riddleslabs.queue.bridge.api.readiness. Registration names and reason codes form a finite contract between your game and server configuration.
| Field or rule | Contract |
|---|---|
| Provider ID | Lowercase namespaced ID, each side 1–32 characters: letters, digits, underscore, dot or hyphen. Example mygame:arena. |
| Owner | Enabled Bukkit plugin; its disable withdraws the registration. |
| Limits | 32 registrations, up to 32 declared reason codes each, 16 subscriptions. |
| Reason | Declared uppercase code starting with a letter, followed by uppercase letters, digits or underscores; at most 48 characters. |
| Sequence | Positive and strictly increasing for that registration. |
| Observation time | Positive epoch milliseconds; cannot be in the future or already expired. |
| Lease | Duration of 1–30 seconds. Renew before expiration; rejected updates do not renew it. |
| Publishable states | STARTING, READY, BLOCKED, DRAINING. |
| Derived states | MISSING for an absent required provider; STALE for an expired observation. These are not producer-published states. |
Registration alone does not gate entry. Add the exact ID to backend admission-report.required-providers and configure the relevant network admission/reporting integration. Aggregate readiness requires all required providers to be READY; an optional blocked provider does not block it. This is backend admission readiness, not a separate readiness flag for each game queue.
Publish STARTING while loading/resetting, READY only while accepting, BLOCKED when unavailable and DRAINING when winding down. Renew through a lifecycle-owned task. Read your game state on its proper scheduler, then publish immutable observations. Do not infer readiness just because the plugin enabled.
snapshot() gives generation, aggregate ready and provider diagnostics (ID, required, state, reason, age). subscribe(owner, listener) delivers Update(revision, snapshot, gap) on background workers. Coalescing means this is not an event journal. Close registrations and subscriptions during cleanup; a running callback may finish afterward.
A successful bridge reload advances generation() and invalidates existing registrations. Detect a changed generation or closed handle, register again, restart your per-registration sequence and publish current facts. Do not continue renewing a superseded handle. Service openness, network connectivity and application readiness are three separate checks.
Reviewed against local Queue 1.15.0 source on 26 October 2026, API contract 3. The naming migration, current public types, example components, unchanged queue-top mapping limitation and built-in-waiting boundaries were checked. This checkout has no Git metadata; the review does not establish a pushed commit or public artifact.
The API and both supplied integration components passed the Maven production compile phase with JDK 25 and Java 21 target bytecode (mvn -pl RiddlesQueueApi,examples/game-api -am -Dmaven.test.skip=true -DskipITs=true compile). Tests/test compilation and live server/proxy runs were not performed. Compilation does not validate transport, rendering, crash recovery or performance.
Persistent registration, scheduler capabilities and the queue-top metadata limitation remain as documented. Pre-1.14 package and loader names are no longer current compatibility identifiers: update imports/descriptors and rebuild. The 1.15 waiting engine adds no new backend API contract.
For support, provide Queue/Core/server versions, operation and result code, queue/admission/ticket IDs, snapshot revision, persistence health and a minimal reproduction. Remove secrets and personal data from logs. See the Core documentation for its runtime services.
The production compile check passed for the two 1.15.0 components below. They are integration building blocks, not installable plugins. Implement the game-specific transport adapter, ownership scheduling, arrival verification and cancellation/fencing. The persistent component uses the session component’s Transport interface.
package com.riddleslabs.examples.queue;
import com.riddleslabs.queue.api.RiddlesQueueApi;
import com.riddleslabs.queue.api.game.*;
import org.bukkit.plugin.Plugin;
import java.util.*;
import java.util.concurrent.CompletionStage;
/**
* A compilable integration component, not a server plugin or a test.
* Your game owns eligibility, party consent, arenas, teleports, match lifecycle and UI.
* Construct during onEnable after Queue. Stop/evacuate games and cancel outstanding
* transports BEFORE closing this component or disabling your plugin.
*/
public final class ArenaQueueIntegration implements AutoCloseable {
@FunctionalInterface public interface Transport {
/**
* Schedule on the player's owner thread and verify actual arrival there.
* Complete true only after arrival, false on failure. Never block a tick thread.
* Your implementation must support cancelling/fencing late arrivals before recovery.
*/
CompletionStage<Boolean> admit(UUID player);
}
private final GameQueue queue;
private final Transport transport;
public ArenaQueueIntegration(Plugin owner, Transport transport) {
this.transport = Objects.requireNonNull(transport);
var api = RiddlesQueueApi.find(owner.getServer()).orElseThrow(
() -> new IllegalStateException("Riddles Queue must be enabled first"));
queue = api.games().orElseThrow(() -> new IllegalStateException("Upgrade Queue to 1.14.0+"))
.register(owner, QueueOptions.builder("example:arena")
.capacity(8).minimumAdmissionPlayers(4).maxPartySize(4).maxWaitingPlayers(100).build());
}
/** Call after checking online status, permission, eligibility and consent for every party member. */
public QueueResult<TicketSnapshot> join(UUID stableTicketId, Set<UUID> party, int trustedPriority) {
return queue.join(new JoinRequest(stableTicketId, party, trustedPriority));
}
/** Call when your arena is ready. A stable request ID prevents a retried call from creating a second batch. */
public QueueResult<AdmissionSnapshot> tryStart(UUID requestId) {
var offered = queue.reserve(requestId, 4, 8);
if (!offered.successful()) return offered;
var admission = offered.requireValue();
// A retried request can refer to a completed/cancelled/held admission. Never redispatch it.
if (admission.state() != AdmissionSnapshot.State.OFFERED) return offered;
var started = queue.begin(admission.id());
if (started.code() != QueueResult.Code.SUCCESS) return started;
for (UUID player : started.requireValue().players()) {
if (queue.admission(admission.id()).map(a -> a.state() != AdmissionSnapshot.State.DISPATCHING).orElse(true)) break;
try {
transport.admit(player).whenComplete((arrived, failure) -> {
// Queue calls are thread-safe; this callback intentionally does no Bukkit player/world work.
if (failure == null && Boolean.TRUE.equals(arrived)) queue.arrived(admission.id(), player);
else queue.failed(admission.id(), player, "TRANSFER_FAILED");
});
} catch (RuntimeException failure) { queue.failed(admission.id(), player, "TRANSFER_FAILED"); }
}
return started;
}
/** Use the ticket ID captured for this connection/game session, not a later lookup for the same UUID. */
public QueueResult<Boolean> departed(UUID ticketId, UUID player) {
// Safe even if begin/completion raced the departure: the queue applies the exact current state atomically.
return queue.departed(ticketId, player);
}
/** Invoke only after every batch member is evacuated and all pending/late transport callbacks are fenced. */
public QueueResult<AdmissionSnapshot> requeueAfterVerifiedEvacuation(UUID admissionId) {
return queue.recover(admissionId, GameQueue.Recovery.REQUEUE_AFTER_EVACUATION);
}
public GameQueue queue() { return queue; }
@Override public void close() { queue.close(); }
}
package com.riddleslabs.examples.queue;
import com.riddleslabs.queue.api.RiddlesQueueApi;
import com.riddleslabs.queue.api.game.*;
import com.riddleslabs.queue.api.schedule.QueueScheduler;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import net.kyori.adventure.text.Component;
import java.util.*;
import java.util.concurrent.*;
/** Compilable production integration component, not an installable example plugin. */
public final class PersistentArenaIntegration {
private final GameQueue queue;
private final QueueScheduler scheduler;
private final ArenaQueueIntegration.Transport transport;
private PersistentArenaIntegration(GameQueue queue,QueueScheduler scheduler,ArenaQueueIntegration.Transport transport) {
this.queue=queue;this.scheduler=scheduler;this.transport=transport;
}
/** Call during owner enable; do not join/get this stage on a server thread. */
public static CompletionStage<PersistentArenaIntegration> open(Plugin owner,ArenaQueueIntegration.Transport transport) {
Objects.requireNonNull(transport);
var api=RiddlesQueueApi.find(owner.getServer()).orElseThrow();
var scheduler=api.scheduling().orElseThrow().forPlugin(owner);
return api.games().orElseThrow().registerPersistent(owner,QueueOptions.builder("example:persistent-arena")
.capacity(8).minimumAdmissionPlayers(4).maxPartySize(4).maxWaitingPlayers(100).build())
.thenApply(queue->new PersistentArenaIntegration(queue,scheduler,transport));
}
/** Eligibility and party consent must already have been checked. A failed save does not undo an accepted join. */
public CompletionStage<QueueResult<TicketSnapshot>> joinDurable(JoinRequest request) {
var result=queue.join(request);
return result.successful()?queue.checkpoint().thenApply(v->result):CompletableFuture.completedFuture(result);
}
/** Restored queues stay paused. Reconcile held games and validate waiting players before explicitly resuming. */
public QueueResult<Boolean> resumeAfterReconciliation(){return queue.pause(false);}
public CompletionStage<QueueResult<AdmissionSnapshot>> tryStart(UUID requestId) {
var offered=queue.reserve(requestId,4,8);
if(!offered.successful())return CompletableFuture.completedFuture(offered);
return queue.beginDurable(offered.requireValue().id()).thenApply(started->{
if(started.code()!=QueueResult.Code.SUCCESS)return started;
UUID admission=started.requireValue().id();
for(UUID player:started.requireValue().players()) {
if(!queue.isOpen() || queue.admission(admission).map(a->a.state()!=AdmissionSnapshot.State.DISPATCHING).orElse(true))break;
try {
transport.admit(player).whenComplete((arrived,error)->{
if(error==null && Boolean.TRUE.equals(arrived))queue.arrived(admission,player);
else queue.failed(admission,player,"TRANSFER_FAILED");
});
}catch(RuntimeException error){queue.failed(admission,player,"TRANSFER_FAILED");}
}
return started;
});
}
/** Captured player reference; scheduling follows the entity through region changes and handles retirement. */
public void show(Player player,Component message){scheduler.entity(player,()->player.sendMessage(message),()->{});}
/** Fence/evacuate the entire admission first. Await the checkpoint before acknowledging durable recovery. */
public CompletionStage<QueueResult<AdmissionSnapshot>> recoverAfterEvacuation(UUID id) {
var result=queue.recover(id,GameQueue.Recovery.REQUEUE_AFTER_EVACUATION);
return result.successful()?queue.checkpoint().thenApply(v->result):CompletableFuture.completedFuture(result);
}
public GameQueue queue(){return queue;}
/** First stop your matchmaker and transport. The shared owner scheduler closes automatically on plugin disable. */
public CompletionStage<Void> closeAfterTransportStopped(){return queue.closeAsync();}
}
Expand a type to inspect its package, imports, full method signatures, enum values and constructor contracts from the audited 1.15.0 API source. Pair these declarations with the workflows above. ApiProvider registration/clear methods belong to the provider lifecycle; consumer plugins should use RiddlesQueueApi.find instead.
package com.riddleslabs.queue.bridge.api;
import java.util.Objects;
public final class ApiProvider {
private static volatile RiddlesQueueBridgeApi api;
private ApiProvider() {}
public static void register(RiddlesQueueBridgeApi api) {
ApiProvider.api = Objects.requireNonNull(api, "api");
}
public static void clear() {
api = null;
}
public static RiddlesQueueBridgeApi get() {
return api;
}
}
package com.riddleslabs.queue.bridge.api;
import com.riddleslabs.queue.bridge.service.model.PointsResult;
import com.riddleslabs.queue.bridge.service.model.ProxyStatus;
import com.riddleslabs.queue.bridge.service.queueview.model.QueueStatusView;
import com.riddleslabs.queue.bridge.service.queueview.model.QueueTopView;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public interface RiddlesQueueBridgeApi {
boolean isRuntimeAvailable();
CompletableFuture<ProxyStatus> proxyStatus();
CompletableFuture<QueueStatusView> queueStatus(UUID playerId, String targetHint);
CompletableFuture<QueueTopView> queueTop(String target, int limit);
CompletableFuture<PointsResult> pointsGet(UUID playerId);
CompletableFuture<PointsResult> pointsAdd(UUID playerId, long delta, String reason);
CompletableFuture<PointsResult> pointsTake(UUID playerId, long delta, String reason);
CompletableFuture<PointsResult> pointsSet(UUID playerId, long value, String reason);
CompletableFuture<Long> effectiveWeight(UUID playerId);
/** Stable IDs enable durable retry on receipt-capable stores. Legacy stores remain explicitly volatile. */
default CompletableFuture<PointsResult> pointsAdd(UUID operationId, UUID playerId, long amount, String reason) {
return CompletableFuture.failedFuture(new UnsupportedOperationException("Operation IDs are unavailable"));
}
default CompletableFuture<PointsResult> pointsTake(UUID operationId, UUID playerId, long amount, String reason) {
return CompletableFuture.failedFuture(new UnsupportedOperationException("Operation IDs are unavailable"));
}
default CompletableFuture<PointsResult> pointsSet(UUID operationId, UUID playerId, long amount, String reason) {
return CompletableFuture.failedFuture(new UnsupportedOperationException("Operation IDs are unavailable"));
}
default CompletableFuture<com.riddleslabs.queue.bridge.service.model.PointsOperation> pointsOperation(UUID operationId) {
return CompletableFuture.failedFuture(new UnsupportedOperationException("Operation lookup is unavailable"));
}
}
package com.riddleslabs.queue.bridge.api.readiness;
import org.bukkit.plugin.Plugin;
import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
/** Application-owned readiness. Publishing never runs application callbacks or performs network I/O. */
public interface ApplicationReadiness {
enum State { STARTING, READY, BLOCKED, DRAINING, MISSING, STALE }
record Observation(long sequence, long observedAtMillis, State state, String reason, Duration validFor) {}
record Provider(String id, boolean required, State state, String reason, long ageMillis) {}
record Snapshot(long generation, boolean ready, List<Provider> providers) {
public Snapshot { providers = List.copyOf(providers); }
}
record Update(long revision, Snapshot snapshot, boolean gap) {}
interface Subscription extends AutoCloseable {
boolean isOpen();
/** A currently executing callback may finish; subsequent delivery is stopped. */
@Override void close();
}
/** At most 16 subscribers. Callbacks run on Core workers; updates coalesce and indicate gaps. */
Subscription subscribe(Plugin owner, Consumer<Update> listener);
interface Registration extends AutoCloseable {
/** False means closed, superseded, expired, invalid, or out-of-order; rejected data never renews a lease. */
boolean publish(Observation observation);
boolean isOpen();
@Override void close();
}
/** IDs are lowercase namespaced identifiers; at most 32 registrations and 32 finite reason codes each. */
Registration register(Plugin owner, String providerId, Set<String> reasonCodes);
/** Immutable local diagnostics; expired leases are evaluated at the instant of this call. */
Snapshot snapshot();
/** Successful bridge reload fences previous registrations; re-register when this generation changes. */
long generation();
}
package com.riddleslabs.queue.bridge.api;
import java.util.UUID;
/** Read-only standalone observations. Registered only in standalone mode; safe on any thread. */
public interface StandaloneQueueApi {
record Status(String mode,String state,int position,int waiting,int active,int capacity,boolean draining) {}
/** UUID null returns aggregate counts. Active includes slots reserved for login/teleport. */
Status status(UUID player);
}
package com.riddleslabs.queue.bridge.service.model;
import java.util.UUID;
/** Operation lookup. NOT_FOUND does not establish failure; reconcile/retry using the same ID. */
public record PointsOperation(UUID operationId, String status, long beforePoints, long afterPoints, long committedAtMillis) {}
package com.riddleslabs.queue.bridge.service.model;
public record PointsResult(
boolean success,
Long points,
String message,
String errorCode
) {
public static PointsResult ok(Long points, String message) {
return new PointsResult(true, points, message, null);
}
public static PointsResult error(String errorCode, String message) {
return new PointsResult(false, null, message, errorCode);
}
}
package com.riddleslabs.queue.bridge.service.model;
public record ProxyStatus(
boolean success,
String proxyType,
String proxyVersion,
String message,
String errorCode
) {
public static ProxyStatus ok(String proxyType, String proxyVersion) {
return new ProxyStatus(true, proxyType, proxyVersion, null, null);
}
public static ProxyStatus error(String errorCode, String message) {
return new ProxyStatus(false, null, null, message, errorCode);
}
}
package com.riddleslabs.queue.bridge.service.queueview.model;
public record QueueStatusView(
boolean available,
boolean inQueue,
String target,
int position,
int size,
long etaMillis,
long effectiveWeight,
long points,
String state,
long fetchedAtMillis,
String workflow,String positionScope,String ticketState,java.util.List<String> targets,int partySize
) {
public QueueStatusView(boolean available,boolean inQueue,String target,int position,int size,long etaMillis,long effectiveWeight,long points,String state,long fetchedAtMillis) {
this(available,inQueue,target,position,size,etaMillis,effectiveWeight,points,state,fetchedAtMillis,"ordinary","local-players",state,target==null||target.isBlank()?java.util.List.of():java.util.List.of(target),1);
}
public QueueStatusView { targets=java.util.List.copyOf(targets); }
public boolean fresh(long ttlMs) {
if (!available) return false;
long age = System.currentTimeMillis() - fetchedAtMillis;
return age >= 0 && age <= ttlMs;
}
}
package com.riddleslabs.queue.bridge.service.queueview.model;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
public record QueueTopView(
boolean available,
String target,
List<Entry> entries,
long fetchedAtMillis
) {
public record Entry(UUID playerId,String name,int position,long etaMillis,long effectiveWeight,String workflow,String positionScope,int partySize,String ticketState) {
public Entry(UUID playerId,String name,int position,long etaMillis,long effectiveWeight){this(playerId,name,position,etaMillis,effectiveWeight,"ordinary","local-players",1,"QUEUED");}
}
public boolean fresh(long ttlMs) {
if (!available) return false;
long age = System.currentTimeMillis() - fetchedAtMillis;
return age >= 0 && age <= ttlMs;
}
public List<Entry> safeEntries() {
return entries == null ? Collections.emptyList() : entries;
}
public Entry entryAt(int index) {
List<Entry> list = safeEntries();
if (index < 0 || index >= list.size()) return null;
return list.get(index);
}
}
package com.riddleslabs.queue.api.game;
import java.util.Set;
import java.util.UUID;
/** Progress, not proof of a teleport. The owning game records arrival only after verifying it. */
public record AdmissionSnapshot(UUID id, Set<UUID> ticketIds, Set<UUID> players, Set<UUID> arrived, Set<UUID> failed,
State state, long deadlineEpochMillis, String reason) {
public enum State { OFFERED, DISPATCHING, HELD, COMPLETED, CANCELLED, RECOVERED }
public AdmissionSnapshot { ticketIds = Set.copyOf(ticketIds); players = Set.copyOf(players); arrived = Set.copyOf(arrived); failed = Set.copyOf(failed); }
public Set<UUID> pending() {
var pending = new java.util.HashSet<>(players); pending.removeAll(arrived); pending.removeAll(failed); return Set.copyOf(pending);
}
}
package com.riddleslabs.queue.api.game;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
/**
* Owner's handle to one local game queue. Calls are synchronized in memory and safe from any thread.
* Players may belong to only one developer game queue on this backend, including active/held slots.
* The plugin must enforce online status, permissions, party consent and game eligibility before joining.
* Queue never teleports players or assumes that a timeout proves a failed transfer.
* State is session-only unless registered with registerPersistent(). The game owns player cleanup.
*/
public interface GameQueue extends AutoCloseable {
enum CancelAction { REQUEUE, REMOVE }
/** Caller must first verify every participant has left the destination and cannot arrive later. */
enum Recovery { REQUEUE_AFTER_EVACUATION, REMOVE_AFTER_EVACUATION }
interface Subscription extends AutoCloseable {
boolean isOpen();
@Override void close();
}
/** Persistence observations. False for older implementations and ordinary register(). */
default boolean persistent() { return false; }
default boolean storageHealthy() { return true; }
/**
* Save a complete snapshot through Core. Completes after this or a newer snapshot is stored.
* Normal mutations auto-save within five seconds; await this for acknowledged waiting/recovery state.
* Session queues complete immediately. Never block a server thread awaiting this stage.
*/
default java.util.concurrent.CompletionStage<Void> checkpoint() { return java.util.concurrent.CompletableFuture.completedFuture(null); }
/**
* Required dispatch boundary for persistent queues. Persists DISPATCHING before SUCCESS.
* Only SUCCESS authorizes dispatch. ALREADY_APPLIED never authorizes repeating transport.
* Callback has no world ownership; use scheduling(). Failure retains/holds capacity for recovery.
*/
default java.util.concurrent.CompletionStage<QueueResult<AdmissionSnapshot>> beginDurable(UUID admissionId) {
return java.util.concurrent.CompletableFuture.completedFuture(begin(admissionId));
}
/** Stop new work and persist before withdrawing. The owning game must already have fenced its transport. */
default java.util.concurrent.CompletionStage<Void> closeAsync() { close(); return java.util.concurrent.CompletableFuture.completedFuture(null); }
String id();
boolean isOpen();
QueueSnapshot snapshot();
Optional<TicketSnapshot> player(UUID player);
Optional<TicketSnapshot> ticket(UUID ticketId);
/** Waiting tickets ordered by priority then FIFO; offset >= 0, limit 1-100. */
List<TicketSnapshot> waiting(int offset, int limit);
Optional<AdmissionSnapshot> admission(UUID admissionId);
/** At most 100 recent admissions, newest first; includes pending/held and retained terminal receipts. */
List<AdmissionSnapshot> admissions(int limit);
/** Page through all current tickets in original join order, including reserved/active tickets. */
default List<TicketSnapshot> tickets(int offset, int limit) { throw new UnsupportedOperationException("Queue 1.13+ required"); }
/** Recent admissions, newest first, with offset >= 0 and limit 1-100. */
default List<AdmissionSnapshot> admissions(int offset, int limit) {
if(offset!=0)throw new UnsupportedOperationException("Queue 1.13+ required");
return admissions(limit);
}
default QueueResult<TicketSnapshot> join(UUID player) { return join(JoinRequest.player(player)); }
QueueResult<TicketSnapshot> join(JoinRequest request);
/** Waiting: removes the entire party. Active: releases just this player's slot. Reserved/held: refuses. */
QueueResult<Boolean> leave(UUID player);
/** Fenced leave for asynchronous work: refuses if this player now belongs to a different ticket. */
QueueResult<Boolean> leave(UUID ticketId, UUID player);
/**
* Confirmed departure for an exact ticket. Atomically cancels an undispatched offer,
* removes a waiting party or releases an active slot. Dispatched/held participants
* are marked failed and capacity stays charged; returns RECOVERY_REQUIRED in that case.
*/
QueueResult<Boolean> departed(UUID ticketId, UUID player);
QueueResult<TicketSnapshot> priority(UUID ticketId, int priority);
QueueResult<Boolean> pause(boolean paused);
/** Refuses to reduce below occupied slots, minimum batch or maximum configured party size. */
QueueResult<Integer> capacity(int capacity);
/** Uses configured minimum and current available capacity. No transfer begins automatically. */
QueueResult<AdmissionSnapshot> reserve();
/** Stable request ID makes retries idempotent while its receipt is retained. Strict FIFO within priority; parties never split. */
QueueResult<AdmissionSnapshot> reserve(UUID requestId, int minimumPlayers, int maximumPlayers);
/** Custom matchmaking: reserve these whole waiting tickets atomically. Owner explicitly overrides priority order. */
QueueResult<AdmissionSnapshot> reserveTickets(UUID requestId, java.util.Set<UUID> ticketIds);
/** Session queues only: must succeed BEFORE dispatch. Persistent queues require beginDurable(). */
QueueResult<AdmissionSnapshot> begin(UUID admissionId);
/** Record a verified arrival. A dispatching batch completes on all arrivals; a held batch requires complete(). */
QueueResult<AdmissionSnapshot> arrived(UUID admissionId, UUID player);
/** Mark a failed/disconnected participant, clear its arrival and hold the batch. It then requires evacuation recovery. */
QueueResult<AdmissionSnapshot> failed(UUID admissionId, UUID player, String reason);
/** Complete a held batch only after all arrivals are verified and no participant is marked failed. */
QueueResult<AdmissionSnapshot> complete(UUID admissionId);
/** Preserve all reserved capacity after an uncertain/partial transfer; reason is a finite uppercase code. */
QueueResult<AdmissionSnapshot> hold(UUID admissionId, String reason);
/** Safe only before begin(). Requeue preserves original priority/FIFO order. */
QueueResult<AdmissionSnapshot> cancel(UUID admissionId, CancelAction action);
/** Explicit whole-batch recovery after evacuation; elapsed time alone is never sufficient. */
QueueResult<AdmissionSnapshot> recover(UUID admissionId, Recovery recovery);
/** At most 8 subscribers. Background callbacks coalesce; no Bukkit world/player calls in callbacks. */
Subscription subscribe(Consumer<QueueUpdate> listener);
/** Withdraw the queue after the game has cleaned up its players. Also called automatically on owner disable. */
@Override void close();
}
package com.riddleslabs.queue.api.game;
import org.bukkit.plugin.Plugin;
import java.util.List;
import java.util.Optional;
/** Local game queues, available in both backend modes. No world access, SQL or network I/O on calls. */
public interface GameQueues {
/** Register during owner enable. Duplicate IDs, stopped owners or exhausted registry limits throw. */
GameQueue register(Plugin owner, QueueOptions options);
/**
* Opt-in local persistence. Loads asynchronously; never block enable/tick threads waiting for it.
* Restored queues start paused, with interrupted/active admissions HELD for owner reconciliation.
* Exact owner name and QueueOptions must match the saved file; corrupt/incompatible files are preserved.
* Session register() refuses an existing durable file so persistence cannot be accidentally disabled.
*/
default java.util.concurrent.CompletionStage<GameQueue> registerPersistent(Plugin owner, QueueOptions options) {
return java.util.concurrent.CompletableFuture.failedFuture(new UnsupportedOperationException("Queue 1.13+ required"));
}
/** Read-only discovery; mutation handles are returned only to the registering plugin. */
Optional<QueueSnapshot> find(String id);
List<QueueSnapshot> snapshots();
boolean isOpen();
}
package com.riddleslabs.queue.api.game;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
/** One ticket for one player or an indivisible party. Priority is trusted plugin input, not player input. */
public record JoinRequest(UUID ticketId, Set<UUID> players, int priority) {
public JoinRequest {
Objects.requireNonNull(ticketId); players = Set.copyOf(players);
if (players.isEmpty() || players.size() > 64 || priority < 0 || priority > 1000000)
throw new IllegalArgumentException("Use 1-64 players and priority 0-1000000");
}
public static JoinRequest player(UUID player) { return new JoinRequest(UUID.randomUUID(), Set.of(player), 0); }
public static JoinRequest party(Set<UUID> players) { return new JoinRequest(UUID.randomUUID(), players, 0); }
}
package com.riddleslabs.queue.api.game;
import java.time.Duration;
import java.util.Objects;
/** Limits for one local game queue. Use builder(id) for readable defaults. */
public record QueueOptions(String id, int capacity, int maxWaitingPlayers, int maxPartySize,
int minimumAdmissionPlayers, Duration offerTimeout, Duration transferTimeout) {
public QueueOptions {
Objects.requireNonNull(id); Objects.requireNonNull(offerTimeout); Objects.requireNonNull(transferTimeout);
if (!id.matches("[a-z0-9_.-]{1,32}:[a-z0-9_.-]{1,32}")) throw new IllegalArgumentException("Use a namespaced queue ID, e.g. mygame:duos");
if (capacity < 1 || capacity > 4096 || maxWaitingPlayers < 1 || maxWaitingPlayers > 10000
|| maxPartySize < 1 || maxPartySize > 64 || maxPartySize > capacity
|| minimumAdmissionPlayers < 1 || minimumAdmissionPlayers > capacity)
throw new IllegalArgumentException("Invalid game queue limits");
validateTimeout(offerTimeout); validateTimeout(transferTimeout);
}
private static void validateTimeout(Duration timeout) {
if (timeout.compareTo(Duration.ofSeconds(1)) < 0 || timeout.compareTo(Duration.ofMinutes(5)) > 0)
throw new IllegalArgumentException("Timeout must be between 1 second and 5 minutes");
}
public static Builder builder(String id) { return new Builder(id); }
public static final class Builder {
private final String id;
private int capacity = 16, maxWaiting = 1000, maxParty = 1, minimum = 1;
private Duration offer = Duration.ofSeconds(15), transfer = Duration.ofSeconds(30);
private Builder(String id) { this.id = id; }
public Builder capacity(int value) { capacity = value; return this; }
public Builder maxWaitingPlayers(int value) { maxWaiting = value; return this; }
public Builder maxPartySize(int value) { maxParty = value; return this; }
public Builder minimumAdmissionPlayers(int value) { minimum = value; return this; }
public Builder offerTimeout(Duration value) { offer = value; return this; }
public Builder transferTimeout(Duration value) { transfer = value; return this; }
public QueueOptions build() { return new QueueOptions(id, capacity, maxWaiting, maxParty, minimum, offer, transfer); }
}
}
package com.riddleslabs.queue.api.game;
import java.util.Objects;
/** Expected operational failures are codes; invalid arguments throw IllegalArgumentException. */
public record QueueResult<T>(Code code, T value) {
public enum Code {
SUCCESS, ALREADY_APPLIED, CLOSED, PAUSED, FULL, PLAYER_ALREADY_QUEUED,
ID_CONFLICT, NOT_FOUND, INVALID_STATE, NOT_ENOUGH_PLAYERS, NO_CAPACITY,
LIMIT_REACHED, RECOVERY_REQUIRED, DURABILITY_REQUIRED, STORAGE_UNAVAILABLE
}
public QueueResult { Objects.requireNonNull(code); }
public boolean successful() { return code == Code.SUCCESS || code == Code.ALREADY_APPLIED; }
/** Useful for setup/examples; normal gameplay should handle code() explicitly. */
public T requireValue() {
if (!successful()) throw new IllegalStateException("Queue operation failed: " + code);
return Objects.requireNonNull(value, "Operation returned no value");
}
public static <T> QueueResult<T> ok(T value) { return new QueueResult<>(Code.SUCCESS, value); }
public static <T> QueueResult<T> failure(Code code) { return new QueueResult<>(code, null); }
}
package com.riddleslabs.queue.api.game;
/** Immutable counts. Occupied includes offered, transferring, held and active players. */
public record QueueSnapshot(String id, long revision, boolean open, boolean paused, int capacity,
int waitingPlayers, int waitingTickets, int occupiedPlayers,
int activePlayers, int heldPlayers) {
public int availableSlots() { return Math.max(0, capacity - occupiedPlayers); }
}
package com.riddleslabs.queue.api.game;
import java.util.UUID;
/** Coalescing notification. If gap is true, query current tickets/admissions instead of replaying changes. */
public record QueueUpdate(QueueSnapshot snapshot, Change change, UUID ticketId, UUID admissionId, boolean gap) {
public enum Change { SNAPSHOT, JOINED, LEFT, PRIORITY_CHANGED, PAUSED, CAPACITY_CHANGED,
RESERVED, DISPATCHING, ARRIVAL, COMPLETED, HELD, CANCELLED, RECOVERED }
}
package com.riddleslabs.queue.api.game;
import java.util.Set;
import java.util.UUID;
/** Rank is among waiting parties/tickets; playersAhead counts people ahead. Both are zero outside waiting. */
public record TicketSnapshot(UUID id, Set<UUID> players, int priority, State state,
int ticketPosition, int playersAhead, UUID admissionId) {
public enum State { WAITING, OFFERED, DISPATCHING, HELD, ACTIVE }
public TicketSnapshot { players = Set.copyOf(players); }
}
package com.riddleslabs.queue.api;
import com.riddleslabs.queue.bridge.api.RiddlesQueueBridgeApi;
import com.riddleslabs.queue.bridge.api.StandaloneQueueApi;
import com.riddleslabs.queue.bridge.api.readiness.ApplicationReadiness;
import java.util.Optional;
import java.util.Set;
/**
* The public entry point for Paper/Folia backend integrations.
* Obtain it from the server ServicesManager using RiddlesQueueApi.class, after
* RiddlesQueueBridge enables. All grouped contracts are in the same API artifact.
* Do not shade the API or depend directly on Core to use this service.
*
* <p>Capabilities describe supported interfaces, not financial, network or game
* readiness. Network operations can fail while disconnected. games() manages
* local developer queues and reservations; the owning game verifies eligibility
* and performs actual teleports or connections.
*
* <p>Accessors and standalone observations are safe from any thread. Network
* futures and readiness callbacks may complete off the server thread: schedule
* world/player work through the appropriate Paper/Folia scheduler. Never block
* a tick/region thread waiting for a future.
*/
public interface RiddlesQueueApi {
int API_VERSION = 3;
enum Mode { NETWORK, STANDALONE_RECONNECT, STANDALONE_WAITING_WORLD }
enum Capability { STANDALONE_STATUS, NETWORK_OPERATIONS, APPLICATION_READINESS, GAME_QUEUES, OWNER_SCHEDULING, PERSISTENT_GAME_QUEUES }
/** Call during plugin enable or from an appropriate server lifecycle context. */
static Optional<RiddlesQueueApi> find(org.bukkit.Server server) {
return Optional.ofNullable(java.util.Objects.requireNonNull(server).getServicesManager().load(RiddlesQueueApi.class))
.filter(RiddlesQueueApi::isOpen);
}
default int apiVersion() { return API_VERSION; }
/** Configured mode; remains meaningful after shutdown. */
Mode mode();
/** Service lifecycle only. Does not imply connected transport or ready games. */
boolean isOpen();
/** Immutable supported interfaces; empty after service shutdown. */
Set<Capability> capabilities();
/** Local read-only admission observations; empty in network mode or after shutdown. */
Optional<StandaloneQueueApi> standalone();
/** Proxy observations and points operations; empty in standalone mode or after shutdown. */
Optional<RiddlesQueueBridgeApi> network();
/** Existing backend readiness registry; empty in standalone mode or after shutdown. */
Optional<ApplicationReadiness> readiness();
/** Paper/Folia execution ownership helpers; empty on older implementations or shutdown. */
default Optional<com.riddleslabs.queue.api.schedule.QueueSchedulers> scheduling() { return Optional.empty(); }
/** Owner-managed local game queues in both modes. Empty for older implementations or after shutdown. */
default Optional<com.riddleslabs.queue.api.game.GameQueues> games() { return Optional.empty(); }
}
package com.riddleslabs.queue.api.schedule;
import java.time.Duration;
import org.bukkit.World;
import org.bukkit.entity.Entity;
/**
* Tasks owned by your plugin, automatically cancelled on its disable. No direct Core dependency.
* Global is NOT a universal main thread on Folia. Use entity for players/entities, region for blocks.
* Async tasks must not access live world/entity state. Never join a future on a tick/region thread.
* Retired callbacks run lightweight non-world cleanup only, possibly immediately on the caller.
* Delays/periods are positive. Rejected scheduling throws; callbacks must handle their own business failures.
*/
public interface QueueScheduler extends AutoCloseable {
boolean isOpen();
int activeTasks();
QueueTask global(Runnable action);
QueueTask globalDelayed(long ticks, Runnable action);
QueueTask globalRepeating(long initialTicks, long periodTicks, Runnable action);
QueueTask region(World world, int chunkX, int chunkZ, Runnable action);
QueueTask regionDelayed(World world, int chunkX, int chunkZ, long ticks, Runnable action);
QueueTask regionRepeating(World world, int chunkX, int chunkZ, long initialTicks, long periodTicks, Runnable action);
QueueTask entity(Entity target, Runnable action, Runnable retired);
QueueTask entityDelayed(Entity target, long ticks, Runnable action, Runnable retired);
QueueTask entityRepeating(Entity target, long initialTicks, long periodTicks, Runnable action, Runnable retired);
QueueTask async(Runnable action);
QueueTask asyncDelayed(Duration delay, Runnable action);
QueueTask asyncRepeating(Duration initialDelay, Duration period, Runnable action);
/** Cancels only this owner's tasks, never Core's shared scheduler. Running actions may finish. */
@Override void close();
}
package com.riddleslabs.queue.api.schedule;
import org.bukkit.plugin.Plugin;
/** Owner-scoped access, up to 64 owners and 256 outstanding tasks per owner (Core also applies its limit). */
public interface QueueSchedulers {
/** Call during enable or another appropriate plugin lifecycle context. Reuses an open scope for this owner. */
QueueScheduler forPlugin(Plugin owner);
}
package com.riddleslabs.queue.api.schedule;
/** A Core-backed task. Cancellation prevents later invocations; an already-running action may finish. */
public interface QueueTask extends AutoCloseable {
enum State { SCHEDULED, RUNNING, COMPLETED, CANCELLED, RETIRED, FAILED }
State state();
boolean cancel();
default boolean isDone() { State observed=state(); return observed != State.SCHEDULED && observed != State.RUNNING; }
@Override default void close() { cancel(); }
}