<commit_before>package com.github.msemys.esjc.tcp.handler;

import com.github.msemys.esjc.tcp.TcpCommand;
import com.github.msemys.esjc.tcp.TcpPackage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class HeartbeatHandler extends SimpleChannelInboundHandler<TcpPackage> {
    private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);

    private final long timeoutMillis;
    private volatile ScheduledFuture<?> timeoutTask;

    public HeartbeatHandler(Duration timeout) {
        timeoutMillis = timeout.toMillis();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TcpPackage msg) throws Exception {
        switch (msg.command) {
            case HeartbeatRequestCommand:
                ctx.writeAndFlush(TcpPackage.newBuilder()
                    .command(TcpCommand.HeartbeatResponseCommand)
                    .correlationId(msg.correlationId)
                    .build());
                break;
            case HeartbeatResponseCommand:
                if (timeoutTask != null) {
                    timeoutTask.cancel(true);
                    timeoutTask = null;
                }
                break;
            default:
                ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            ctx.writeAndFlush(TcpPackage.newBuilder()
                .command(TcpCommand.HeartbeatRequestCommand)
                .correlationId(UUID.randomUUID())
                .build());
            timeoutTask = ctx.executor().schedule(() -> {
                logger.info("Closing TCP connection [{}, L{}] due to HEARTBEAT TIMEOUT.", ctx.channel().remoteAddress(), ctx.channel().localAddress());
                ctx.close();
            }, timeoutMillis, MILLISECONDS);
        }
    }

}<commit_msg>fix: cancel running timeout-task when handler is removed<commit_after>package com.github.msemys.esjc.tcp.handler;

import com.github.msemys.esjc.tcp.TcpCommand;
import com.github.msemys.esjc.tcp.TcpPackage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Duration;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class HeartbeatHandler extends SimpleChannelInboundHandler<TcpPackage> {
    private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);

    private final long timeoutMillis;
    private volatile ScheduledFuture<?> timeoutTask;

    public HeartbeatHandler(Duration timeout) {
        timeoutMillis = timeout.toMillis();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TcpPackage msg) throws Exception {
        switch (msg.command) {
            case HeartbeatRequestCommand:
                ctx.writeAndFlush(TcpPackage.newBuilder()
                    .command(TcpCommand.HeartbeatResponseCommand)
                    .correlationId(msg.correlationId)
                    .build());
                break;
            case HeartbeatResponseCommand:
                cancelTimeoutTask();
                break;
            default:
                ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        cancelTimeoutTask();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            ctx.writeAndFlush(TcpPackage.newBuilder()
                .command(TcpCommand.HeartbeatRequestCommand)
                .correlationId(UUID.randomUUID())
                .build());
            timeoutTask = ctx.executor().schedule(() -> {
                logger.info("Closing TCP connection [{}, L{}] due to HEARTBEAT TIMEOUT.", ctx.channel().remoteAddress(), ctx.channel().localAddress());
                ctx.close();
            }, timeoutMillis, MILLISECONDS);
        }
    }

    private void cancelTimeoutTask() {
        if (timeoutTask != null) {
            timeoutTask.cancel(true);
            timeoutTask = null;
        }
    }

}
{'fraction_non_alphanumeric': 0.09172164290274526, 'fraction_numerical': 0.001276867418599702, 'mean_word_length': 2.547169811320755, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6817580', 'n_tokens_mistral': 1267, 'n_tokens_neox': 1230, 'n_words': 239}