Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
import dev.cyr1en.promptpaper.util.PluginLogger;
import dev.cyr1en.promptpaper.util.Scheduler;
import dev.cyr1en.promptui.api.CommandPrompterAPI;
import io.papermc.paper.event.player.AsyncChatEvent;
import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
import java.util.Map;
import org.bstats.bukkit.Metrics;
Expand Down Expand Up @@ -66,6 +65,7 @@ public class CommandPrompter extends JavaPlugin implements Listener {
private ScreenManager screenManager;
private HeadCache headCache;
private HookContainer hookContainer;
private ChatPromptListener fallbackChatListener;
private GeyserStandaloneSupport geyserStandaloneSupport;
private PresetRegistry presetRegistry;
private ItemCatalogRegistry itemCatalogRegistry;
Expand Down Expand Up @@ -313,19 +313,16 @@ private void resolveChatListener() {
return;
}
}
var listener = new ChatPromptListener(this, screenManager);
getServer()
.getPluginManager()
.registerEvent(
AsyncChatEvent.class,
listener,
listener.resolvePriority(),
(registeredListener, event) -> listener.onPlayerChat((AsyncChatEvent) event),
this,
false);
fallbackChatListener = new ChatPromptListener(this, screenManager);
refreshChatListenerPriority();
pluginLogger.info("Using default Bukkit chat listener");
}

/** Applies the chat event priority when Bukkit is handling chat responses. */
public void refreshChatListenerPriority() {
if (fallbackChatListener != null) fallbackChatListener.refreshRegistration();
}

/** Cancels all active screens and sessions for a disconnecting player. */
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Expand Down Expand Up @@ -358,6 +355,7 @@ public void onPlayerQuit(PlayerQuitEvent event) {
@Override
public void onDisable() {
activeLifecycle = false;
fallbackChatListener = null;
var registry = getCustomScreenRegistry();
if (registry != null) {
registry.freeze();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -493,11 +493,8 @@ private void bindCandidateGatesChain(
}
}

// Establish provisional exact interaction claim
Duration ttl = Duration.ofSeconds(Math.max(60, candidate.definition().timeout() * 2L));
Optional<PlayerInteractionLease> leaseOpt =
leaseRegistry.acquire(targetUuid, executionId, ttl);
if (leaseOpt.isEmpty()) {
// Hold the claim through this target's last gate, or until execution cleanup.
if (leaseRegistry.acquire(targetUuid, executionId, null).isEmpty()) {
rollbackProvisionalClaims(provisionalClaimsSoFar, executionId);
callback.onResult(
PreDispatchGateResult.error(
Expand Down Expand Up @@ -681,14 +678,14 @@ private void executeBoundGate(
}
String renderedMsg = msgResult.renderedText();

Duration ttl = Duration.ofSeconds(gate.timeout());
Optional<PlayerInteractionLease> leaseOpt =
leaseRegistry.acquire(targetUuid, executionId, ttl);
if (leaseOpt.isEmpty()) {
if (leaseRegistry
.getLease(targetUuid)
.filter(lease -> executionId.equals(lease.executionId()))
.isEmpty()) {
Comment thread
CyR1en marked this conversation as resolved.
Resolved
cleanupExecution(executionId, plan);
callback.onResult(
PreDispatchGateResult.error(
"Failed to acquire interaction lease for approver " + targetPlayer.getName()));
"Missing interaction lease for approver " + targetPlayer.getName()));
return;
}

Expand All @@ -699,7 +696,7 @@ private void executeBoundGate(
initiatorUuid,
instance.getIncarnation(),
targetUuid,
ttl);
Duration.ofSeconds(gate.timeout()));
if (capOpt.isEmpty()) {
cleanupExecution(executionId, plan);
callback.onResult(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public static PlayerInteractionLease forApproval(
null,
ClaimType.APPROVAL,
acquiredAt,
Objects.requireNonNull(expiresAt, "expiresAt must not be null"));
expiresAt);
}

public static PlayerInteractionLease forPrompt(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,14 @@ public PlayerInteractionLeaseRegistry(Clock clock) {
*
* @param player the player UUID to lease
* @param executionId the execution acquiring the lease
* @param ttl lease duration
* @param ttl optional lease duration, or null to hold until explicitly released
* @return optional containing the lease if acquired, or empty if rejected due to collision
*/
public synchronized Optional<PlayerInteractionLease> acquire(
UUID player, ExecutionId executionId, Duration ttl) {
Objects.requireNonNull(player, "player must not be null");
Objects.requireNonNull(executionId, "executionId must not be null");
Objects.requireNonNull(ttl, "ttl must not be null");
if (ttl.isNegative() || ttl.isZero()) {
if (ttl != null && (ttl.isNegative() || ttl.isZero())) {
throw new IllegalArgumentException("ttl must be positive");
}

Expand All @@ -60,8 +59,9 @@ public synchronized Optional<PlayerInteractionLease> acquire(
}
}

Instant expiresAt = ttl != null ? now.plus(ttl) : null;
PlayerInteractionLease lease =
PlayerInteractionLease.forApproval(player, executionId, now, now.plus(ttl));
PlayerInteractionLease.forApproval(player, executionId, now, expiresAt);
leases.put(player, lease);
return Optional.of(lease);
}
Expand Down Expand Up @@ -157,19 +157,6 @@ public synchronized boolean releasePromptIfExact(UUID player, long incarnation)
return false;
}

/**
* Releases any lease or claim held for the player.
*
* @param player player UUID
* @return true if a lease was removed
*/
public synchronized boolean releaseAllForPlayer(UUID player) {
if (player == null) {
return false;
}
return leases.remove(player) != null;
}

/**
* Gets the active lease for a player, if any. Expired leases are pruned on lookup.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,8 @@ private void reloadAfterTeardown(
if (engine != null) engine.publishParser(preparedParser);
});

plugin.refreshChatListenerPriority();

try {
plugin.getPluginLogger().reload(preparedConfig.config());
if (previousConfig != null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,12 +378,8 @@ public InterceptResult interceptResult(Player player, String commandLine) {
new InterceptResult.RejectedFailClosed("Structural command parse failed: " + safeMsg));
}

var presetSnapshot =
plugin != null
&& plugin.getPresetRegistry() != null
&& plugin.getPresetRegistry().getSnapshot() != null
? plugin.getPresetRegistry().getSnapshot()
: PresetSnapshot.empty();
var presetRegistry = plugin != null ? plugin.getPresetRegistry() : null;
var presetSnapshot = presetRegistry != null ? presetRegistry.getSnapshot() : null;

// Fail-fast: any unresolved preset ID or validator alias aborts the command flow.
var missingPrompts = findMissingPromptPresets(parsed, presetSnapshot);
Expand Down Expand Up @@ -488,7 +484,7 @@ public InterceptResult interceptResult(Player player, String commandLine) {
candidateIncarnation,
0L,
planDefinition,
presetSnapshot,
presetSnapshot != null ? presetSnapshot : PresetSnapshot.empty(),
List.copyOf(effectiveParsed.postCmds())));
return PromptSession.start(uuid.toString(), effectiveParsed, candidateIncarnation);
});
Expand Down Expand Up @@ -573,15 +569,18 @@ ParsedCommand applyPresetSanitize(ParsedCommand parsed, PresetSnapshot snapshot)
: registry != null
? registry.getPrompt(tag.displayText()).orElse(null)
: null;
var timeout = definition != null ? definition.timeout() : null;
return definition != null && definition.behavior() != null
? definition.behavior().apply(tag, sanitize)
: withSanitize(tag, sanitize);
? definition.behavior().apply(tag, sanitize, timeout)
: withSanitizeAndTimeout(
tag, sanitize, timeout != null ? timeout : tag.timeout());
})
.toList();
return withPromptTags(parsed, adjustedTags);
}

private static PromptTag withSanitize(PromptTag tag, boolean sanitize) {
private static PromptTag withSanitizeAndTimeout(
PromptTag tag, boolean sanitize, Integer timeout) {
return new PromptTag(
tag.rawTag(),
tag.key(),
Expand All @@ -593,7 +592,7 @@ private static PromptTag withSanitize(PromptTag tag, boolean sanitize) {
tag.subTags(),
tag.preset(),
tag.title(),
tag.timeout(),
timeout,
tag.flags(),
tag.breakIf());
}
Expand Down Expand Up @@ -826,8 +825,6 @@ public void cancel(
lastInterceptResults.remove(uuid);
if (cancelledIncarnation.get() >= 0) {
getEffectiveLeaseRegistry().releasePromptIfExact(uuid, cancelledIncarnation.get());
} else {
getEffectiveLeaseRegistry().releaseAllForPlayer(uuid);
}
var coordinator = getExecutionCoordinator();
if (coordinator != null) {
Expand Down Expand Up @@ -946,8 +943,6 @@ public void discard(UUID uuid) {
lastInterceptResults.remove(uuid);
if (s != null) {
getEffectiveLeaseRegistry().releasePromptIfExact(uuid, s.incarnation());
} else {
getEffectiveLeaseRegistry().releaseAllForPlayer(uuid);
}
}
}
Expand Down Expand Up @@ -1127,25 +1122,17 @@ private List<String> findMissingPromptPresets(ParsedCommand parsed, PresetSnapsh
private List<String> findMissingPostCommandPresets(
ParsedCommand parsed, PresetSnapshot snapshot) {
var registry = plugin != null ? plugin.getPresetRegistry() : null;
if (registry == null && snapshot == null) {
return parsed.postCmds().stream()
.filter(PostCommandMeta::isPreset)
.map(PostCommandMeta::command)
.toList();
}
return parsed.postCmds().stream()
.filter(PostCommandMeta::isPreset)
.map(PostCommandMeta::command)
.filter(
id -> {
if (snapshot != null && snapshot.getPostCommand(id).isPresent()) {
return false;
}
if (registry != null && registry.getPostCommand(id).isPresent()) {
return false;
}
return true;
})
id ->
snapshot != null
? snapshot.getPostCommand(id).isEmpty()
&& snapshot.getConditionalPostCommand(id).isEmpty()
: registry == null
|| (registry.getPostCommand(id).isEmpty()
&& registry.getConditionalPostCommand(id).isEmpty()))
.toList();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -724,7 +724,15 @@ private void dispatchOnDenyAction(

ImmediateActionRequest req =
new ImmediateActionRequest(
player, renderedCommand, executeAs, provenance, initiatorExecutor, sourceId);
player,
renderedCommand,
executeAs,
provenance,
initiatorExecutor,
sourceId,
() ->
registry.getByExecutionId(executionId).orElse(null) == instance
&& instance.getStage() == ExecutionStage.PRE_DISPATCH_GATES);

try {
immediateActionDispatcher.dispatch(
Expand Down Expand Up @@ -895,7 +903,15 @@ private void dispatchPrimaryOrPostActions(

PrimaryDispatchRequest request =
new PrimaryDispatchRequest(
player, command, mode, attachmentContext, initiatorExecutor, null);
player,
command,
mode,
attachmentContext,
initiatorExecutor,
null,
() ->
registry.getByExecutionId(executionId).orElse(null) == instance
&& instance.getStage() == ExecutionStage.PRIMARY_DISPATCH);

long expectedIncarnation = completion.incarnation();

Expand Down Expand Up @@ -997,6 +1013,7 @@ private void runPostActions(
postActionScheduler,
papiResolver,
templateSyntax,
() -> registry.getByExecutionId(executionId).orElse(null) == instance,
result -> {
try {
initiatorExecutor.execute(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ public enum DispatchErrorKind {
/** Target or initiator player entity scheduler was retired or unavailable. */
SCHEDULER_RETIRED,
/** A command event listener cancelled the finished command, so it never ran. */
CANCELLED_BY_LISTENER
CANCELLED_BY_LISTENER,
/** The execution ended before the scheduled command could be dispatched. */
EXECUTION_CANCELLED
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import dev.cyr1en.promptpaper.custom.PlayerExecutor;
import dev.cyr1en.promptpaper.preset.ExecuteAs;
import java.util.Objects;
import java.util.function.BooleanSupplier;
import org.bukkit.entity.Player;

/** Immutable request parameters for executing an immediate action. */
Expand All @@ -12,10 +13,22 @@ public record ImmediateActionRequest(
ExecuteAs executeAs,
ActionProvenance provenance,
PlayerExecutor initiatorExecutor,
String sourceId) {
String sourceId,
BooleanSupplier canDispatch) {
public ImmediateActionRequest(
Player player,
String command,
ExecuteAs executeAs,
ActionProvenance provenance,
PlayerExecutor initiatorExecutor,
String sourceId) {
this(player, command, executeAs, provenance, initiatorExecutor, sourceId, () -> true);
}

public ImmediateActionRequest {
Objects.requireNonNull(player, "player must not be null");
Objects.requireNonNull(command, "command must not be null");
Objects.requireNonNull(canDispatch, "canDispatch must not be null");
if (executeAs == null) {
executeAs = ExecuteAs.PLAYER;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import dev.cyr1en.promptpaper.util.Scheduler;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BooleanSupplier;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
Expand Down Expand Up @@ -81,7 +82,7 @@ public void dispatch(ImmediateActionRequest request, ActionDispatchCallback call
return;
}

dispatchConsole(initiator, commandToExecute, safeCallback);
dispatchConsole(initiator, commandToExecute, request.canDispatch(), safeCallback);
} else {
dispatchPlayer(initiator, player, commandToExecute, safeCallback);
}
Expand Down Expand Up @@ -111,15 +112,22 @@ private void dispatchPlayer(
}

private void dispatchConsole(
PlayerExecutor initiator, String command, ActionDispatchCallback callback) {
PlayerExecutor initiator,
String command,
BooleanSupplier canDispatch,
ActionDispatchCallback callback) {
try {
scheduler.runSync(
() -> {
DispatchOutcome outcome;
try {
var consoleSender = Bukkit.getConsoleSender();
boolean ok = Bukkit.dispatchCommand(consoleSender, command);
if (ok) {
if (!canDispatch.getAsBoolean()) {
outcome =
DispatchOutcome.failure(
DispatchErrorKind.EXECUTION_CANCELLED,
"execution cancelled before dispatch");
} else if (Bukkit.dispatchCommand(consoleSender, command)) {
outcome = DispatchOutcome.success();
} else {
outcome =
Expand Down
Loading
Loading