Skip to content

Commit

Permalink
feat: track chat socket latency (#545)
Browse files Browse the repository at this point in the history
  • Loading branch information
iProdigy committed Mar 6, 2022
1 parent 055195c commit e2fde52
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
5 changes: 5 additions & 0 deletions chat/src/main/java/com/github/twitch4j/chat/ITwitchChat.java
Expand Up @@ -79,6 +79,11 @@ default boolean sendMessage(String channel, String message, @Unofficial String n
@Override
void close();

/**
* @return the most recently measured round-trip latency for the socket(s) in milliseconds, or -1 if unknown
*/
long getLatency();

/**
* @return cached mappings of channel ids to names
*/
Expand Down
26 changes: 26 additions & 0 deletions chat/src/main/java/com/github/twitch4j/chat/TwitchChat.java
Expand Up @@ -53,6 +53,7 @@
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;

Expand Down Expand Up @@ -237,6 +238,14 @@ public class TwitchChat implements ITwitchChat {
*/
private final int wsPingPeriod;

/**
* Tracks the timestamp of the last outbound ping
*/
protected final AtomicLong lastPing = new AtomicLong();

@Getter
protected volatile long latency = -1L;

/**
* Cache of recent number of join attempts for each channel
*/
Expand Down Expand Up @@ -625,6 +634,23 @@ public void onDisconnected(WebSocket websocket,
log.info("Disconnected from Twitch IRC (WebSocket)!");
}
}

@Override
public void onFrameSent(WebSocket websocket, WebSocketFrame frame) {
if (frame != null && frame.isPingFrame()) {
lastPing.compareAndSet(0L, System.currentTimeMillis());
}
}

@Override
public void onPongFrame(WebSocket websocket, WebSocketFrame frame) {
final long last = lastPing.getAndSet(0L);
if (last > 0) {
latency = System.currentTimeMillis() - last;
log.trace("TwitchChat: Round-trip socket latency recorded at {} ms.", latency);
}
}

});

} catch (Exception ex) {
Expand Down
Expand Up @@ -278,6 +278,20 @@ protected void disposeConnection(TwitchChat connection) {
connection.close();
}

@Override
public long getLatency() {
long sum = 0;
int count = 0;
for (TwitchChat connection : getConnections()) {
final long latency = connection.getLatency();
if (latency > 0) {
sum += latency;
count++;
}
}
return count > 0 ? sum / count : -1L;
}

/**
* Note: this map does not dynamically update unlike {@link TwitchChat#getChannelIdToChannelName()}
* <p>
Expand Down

0 comments on commit e2fde52

Please sign in to comment.