Skip to content

Commit

Permalink
Fix starter clear and improve logging (#612)
Browse files Browse the repository at this point in the history
* Fix starter clear and improve logging
  • Loading branch information
twonirwana authored Nov 5, 2024
1 parent 111c44f commit f8279b5
Show file tree
Hide file tree
Showing 16 changed files with 402 additions and 385 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@
import java.util.UUID;
import java.util.function.Supplier;

import static de.janno.discord.connector.api.BottomCustomIdUtils.CUSTOM_ID_DELIMITER;

@Slf4j
public abstract class ComponentCommandImpl<C extends RollConfig, S extends StateData> implements ComponentCommand {

Expand All @@ -44,7 +42,7 @@ protected ComponentCommandImpl(PersistenceManager persistenceManager, Supplier<U

@Override
public final Mono<Void> handleComponentInteractEvent(@NonNull ButtonEventAdaptor event) {
final Timer timer = new Timer(getCommandId());
final ComponentInteractionContext componentInteractionContext = new ComponentInteractionContext(getCommandId());
final long eventMessageId = event.getMessageId();
final long channelId = event.getChannelId();
final long userId = event.getUserId();
Expand Down Expand Up @@ -98,9 +96,9 @@ public final Mono<Void> handleComponentInteractEvent(@NonNull ButtonEventAdaptor
//update state bevor editing the event message
updateCurrentMessageStateData(configUUID, guildId, channelId, eventMessageId, config, state);
//reply/edit/acknowledge to the event message, no defer but directly call
return replyToEvent(event, config, state, configUUID, channelId, userId, answerTargetChannelId, timer)
return replyToEvent(event, config, state, configUUID, channelId, userId, answerTargetChannelId, componentInteractionContext)
//send answer messages
.then(Mono.defer(() -> sendAnswerMessage(event, config, state, guildId, channelId, userId, answerTargetChannelId, timer))
.then(Mono.defer(() -> sendAnswerMessage(event, config, state, guildId, channelId, userId, answerTargetChannelId, componentInteractionContext))
//create an optional new button message
.then(Mono.defer(() -> createNewButtonMessage(configUUID, config, state, guildId, channelId, userId).map(Mono::just).orElse(Mono.empty())
//update the new button message if a starter uuid is set
Expand All @@ -111,21 +109,19 @@ public final Mono<Void> handleComponentInteractEvent(@NonNull ButtonEventAdaptor
return Mono.just(bm);
})
//send the new button message, flatMap because we do it only if a new buttonMessage should be created
.flatMap(nbm -> Mono.defer(() -> sendNewButtonMessage(event, nbm, configUUID, guildId, channelId, answerTargetChannelId, timer))
.flatMap(nbm -> Mono.defer(() -> sendNewButtonMessage(event, nbm, configUUID, guildId, channelId, answerTargetChannelId, componentInteractionContext))
//delete the event message and event data if a new buttonMessage was created, flatMap because we do it only if a new buttonMessage is created
.flatMap(newButtonMessageId -> Mono.defer(() -> deleteEventMessageAndData(event, configUUID, eventMessageId, channelId, answerTargetChannelId, newButtonMessageId))))

)))
//do further actions last
.then(Mono.defer(() -> furtherAction(event, config, state, timer)))
.doAfterTerminate(() -> {
//only logging if there is an answer or new button message, and not if the event message was only edited
if (timer.getAnswerFinished() != null || timer.getNewButtonFinished() != null || timer.getFurtherActionFinished() != null) {
log.info("{}: '{}'={} in {}",
if (componentInteractionContext.getAnswerFinished() != null || componentInteractionContext.getNewButtonFinished() != null) {
log.info("{}: {}-{} = {}",
event.getRequester().toLogString(),
event.getCustomId().replace(CUSTOM_ID_DELIMITER, ":"),
getCommandId(),
state.toShortString(),
timer.toLog()
componentInteractionContext.toLog()
);
}
});
Expand All @@ -141,20 +137,20 @@ public final Mono<Void> handleComponentInteractEvent(@NonNull ButtonEventAdaptor
final long channelId,
final long userId,
final Long answerTargetChannelId,
@NonNull final Timer timer) {
@NonNull final ComponentInteractionContext componentInteractionContext) {
final boolean keepExistingButtonMessage = shouldKeepExistingButtonMessage(event) || answerTargetChannelId != null;

//edit the current message if the command changes it or mark it as processing
final Optional<String> editMessage = getCurrentMessageContentChange(config, state, keepExistingButtonMessage);
final Optional<List<ComponentRowDefinition>> editMessageComponents = getCurrentMessageComponentChange(configUUID, config, state, channelId, userId, keepExistingButtonMessage);

timer.stopStartAcknowledge();
componentInteractionContext.stopStartAcknowledge();
if (editMessage.isPresent() || editMessageComponents.isPresent()) {
return event.editMessage(editMessage.orElse(null), editMessageComponents.orElse(null))
.doOnSuccess(v -> timer.stopReplyFinished());
.doOnSuccess(v -> componentInteractionContext.stopReplyFinished());
} else {
return event.acknowledge()
.doOnSuccess(v -> timer.stopAcknowledgeFinished());
.doOnSuccess(v -> componentInteractionContext.stopAcknowledgeFinished());
}
}

Expand All @@ -165,10 +161,11 @@ public final Mono<Void> handleComponentInteractEvent(@NonNull ButtonEventAdaptor
final long channelId,
final long userId,
final Long answerTargetChannelId,
@NonNull final Timer timer) {
@NonNull final ComponentInteractionContext componentInteractionContext) {
final Optional<RollAnswer> answer = getAnswer(config, state, channelId, userId);
if (answer.isPresent()) {
BotMetrics.incrementAnswerFormatCounter(config.getAnswerFormatType(), getCommandId());
componentInteractionContext.setAnswerText(answer.get().toShortString());
EmbedOrMessageDefinition baseAnswer = RollAnswerConverter.toEmbedOrMessageDefinition(answer.get());
final EmbedOrMessageDefinition answerMessage;
if (config.getAnswerInteractionType() == AnswerInteractionType.reroll &&
Expand All @@ -179,7 +176,7 @@ public final Mono<Void> handleComponentInteractEvent(@NonNull ButtonEventAdaptor
answerMessage = baseAnswer;
}
return event.sendMessage(answerMessage.toBuilder().sendToOtherChannelId(answerTargetChannelId).build()).then()
.doOnSuccess(v -> timer.stopAnswer());
.doOnSuccess(v -> componentInteractionContext.stopAnswer());

}
return Mono.empty();
Expand All @@ -194,13 +191,13 @@ public final Mono<Void> handleComponentInteractEvent(@NonNull ButtonEventAdaptor
final Long guildId,
final long channelId,
final Long answerTargetChannelId,
@NonNull final Timer timer) {
@NonNull final ComponentInteractionContext componentInteractionContext) {


if (answerTargetChannelId == null) {
return Mono.defer(() -> event.sendMessage(newButtonMessage)
.doOnNext(newMessageId -> createEmptyMessageData(configUUID, guildId, channelId, newMessageId))
.doOnNext(newMessageId -> timer.stopNewButton())
.doOnNext(newMessageId -> componentInteractionContext.stopNewButton())
.delaySubscription(calculateDelay(event)));
}
return Mono.empty();
Expand Down Expand Up @@ -317,8 +314,4 @@ private Duration calculateDelay(ButtonEventAdaptor event) {
BotMetrics.incrementDelayCounter(getCommandId(), false);
return Duration.ZERO;
}

protected Mono<Void> furtherAction(ButtonEventAdaptor event, C config, State<S> state, Timer timer) {
return Mono.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,23 @@
import java.time.Duration;

@Data
public class Timer {
public class ComponentInteractionContext {
private final String commandId;
private Stopwatch stopwatch = Stopwatch.createStarted();
private Duration startAcknowledge;
private Duration replyFinished;
private Duration acknowledgeFinished;
private Duration answerFinished;
private Duration newButtonFinished;
private Duration furtherActionFinished;
private String answerText;

public String toLog() {
String out = null;
if(answerText != null){
out = answerText;
}
if(startAcknowledge != null) {
out = "start=%dms".formatted(startAcknowledge.toMillis());
out = Joiner.on(" ").skipNulls().join(out, "start=%dms".formatted(startAcknowledge.toMillis()));
}
if (replyFinished != null) {
out = Joiner.on(" ").skipNulls().join(out, "reply=%dms".formatted(replyFinished.toMillis()));
Expand All @@ -35,9 +38,6 @@ public String toLog() {
if (newButtonFinished != null) {
out = Joiner.on(" ").skipNulls().join(out, "newButton=%dms".formatted(newButtonFinished.toMillis()));
}
if (furtherActionFinished != null) {
out = Joiner.on(" ").skipNulls().join(out, "furtherAction=%dms".formatted(furtherActionFinished.toMillis()));
}
return Joiner.on(" ").skipNulls().join(out, "total=%dms".formatted(stopwatch.elapsed().toMillis()));
}

Expand All @@ -62,10 +62,6 @@ public void stopAnswer() {
BotMetrics.timerAnswerMetricCounter(commandId, answerFinished);
}

public void stopFurtherAction() {
furtherActionFinished = stopwatch.elapsed();
}

public void stopNewButton() {
newButtonFinished = stopwatch.elapsed();
BotMetrics.timerNewButtonMessageMetricCounter(commandId, newButtonFinished);
Expand Down
12 changes: 1 addition & 11 deletions bot/src/main/java/de/janno/discord/bot/command/RollAnswer.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@
import lombok.NonNull;
import lombok.Singular;
import lombok.Value;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nullable;
import java.io.InputStream;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

@Value
Expand Down Expand Up @@ -42,15 +40,7 @@ public class RollAnswer {
List<DieIdTypeAndValue> dieIdTypeAndValues;

public String toShortString() {
String fieldStringList = Optional.ofNullable(multiRollResults)
.map(f -> f.stream()
.map(RollResults::toShortString)
.toList().toString())
.orElse(null);

return String.format("%s=%s", expression,
Joiner.on(",").skipNulls().join(result, StringUtils.abbreviate(rollDetails, 100), errorMessage, warning, fieldStringList))
.replace("\n", " ");
return Joiner.on(",").skipNulls().join(expression, errorMessage).replace("\n", " ");
}

@Value
Expand Down
3 changes: 2 additions & 1 deletion bot/src/main/java/de/janno/discord/bot/command/State.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import lombok.NonNull;
import lombok.Value;

import javax.annotation.Nullable;

import java.util.Optional;
Expand All @@ -19,6 +20,6 @@ public String toShortString() {
String persistedStateValues = Optional.ofNullable(data)
.map(d -> data.getShortStringValues())
.orElse("");
return String.format("[%s]", persistedStateValues).replace("\n", " ");
return String.format("%s [%s]", buttonValue, persistedStateValues).replace("\n", " ");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -182,10 +182,9 @@ protected EmbedOrMessageDefinition getHelpMessage(Locale userLocale) {
return event.replyWithEmbedOrMessageDefinition(createAnswerWithOptionalWarning(answer), false)
.doAfterTerminate(() -> {
BotMetrics.timerAcknowledgeFinishedMetricCounter(getCommandId(), stopwatch.elapsed());
log.info("{}: '{}'={} -> {} in start={}ms reply={}ms",
log.info("{}: {} = {} in start={}ms reply={}ms",
event.getRequester().toLogString(),
commandString.replace("`", ""),
diceExpression,
getCommandId(),
answer.toShortString(),
untilAck.toMillis(),
stopwatch.elapsed(TimeUnit.MILLISECONDS)
Expand Down
Loading

0 comments on commit f8279b5

Please sign in to comment.