-
Notifications
You must be signed in to change notification settings - Fork 1
Send server heartbeats so idle realtime connections stay alive #32
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
src/main/java/gg/modl/backend/realtime/schedule/RealtimeServerHeartbeatEmitter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| package gg.modl.backend.realtime.schedule; | ||
|
|
||
| import gg.modl.backend.realtime.config.RealtimeProperties; | ||
| import gg.modl.backend.realtime.state.RealtimeConnectionRegistry; | ||
| import gg.modl.backend.realtime.state.RealtimeConnectionState; | ||
| import gg.modl.backend.realtime.transport.RealtimeCodec; | ||
| import gg.modl.backend.realtime.transport.RealtimeSessionOperations; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.scheduling.annotation.Scheduled; | ||
| import org.springframework.stereotype.Component; | ||
| import org.springframework.web.socket.WebSocketSession; | ||
|
|
||
| /** | ||
| * Emits unsolicited heartbeats to authenticated connections so idle sessions keep seeing inbound | ||
| * traffic. | ||
| * | ||
| * <p>Clients treat prolonged inbound silence as a dead connection. Without this, a connection that | ||
| * is healthy and fully subscribed but simply has no domain events to carry looks dead to the | ||
| * client: the Minecraft plugin tears it down and reconnects roughly every 100 seconds, re-running a | ||
| * full baseline fetch each cycle. {@link RealtimeHeartbeatSweeper} is the inbound counterpart — it | ||
| * closes connections whose <em>client</em> heartbeats have stopped.</p> | ||
| */ | ||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class RealtimeServerHeartbeatEmitter { | ||
| private final RealtimeProperties properties; | ||
| private final RealtimeConnectionRegistry connectionRegistry; | ||
| private final RealtimeCodec codec; | ||
| private final RealtimeSessionOperations sessionOperations; | ||
|
|
||
| @Scheduled(fixedDelayString = "${modl.realtime.ws.server-heartbeat-interval-ms:25000}") | ||
| public void emitHeartbeats() { | ||
| if (!properties.isEnabled()) { | ||
| return; | ||
| } | ||
|
|
||
| for (RealtimeConnectionRegistry.RealtimeConnectionSnapshot snapshot : connectionRegistry.snapshot()) { | ||
| RealtimeConnectionState state = snapshot.state(); | ||
| // Unauthenticated sessions are the handshake sweeper's business; sending to a closing or | ||
| // terminal session would only race its close frame. | ||
| if (!state.isAuthenticated() || state.isClosing() || state.getTerminalSince() != null) { | ||
| continue; | ||
| } | ||
| WebSocketSession session = snapshot.session(); | ||
| if (!session.isOpen()) { | ||
| continue; | ||
| } | ||
| // Best effort: a failed keepalive is not itself grounds for tearing down the connection. | ||
| // A genuinely dead peer stops sending client heartbeats and the sweeper closes it. | ||
| sessionOperations.trySend(session, state, codec.heartbeat(state.nextOutboundHeartbeatSequence())); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
167 changes: 167 additions & 0 deletions
167
src/test/java/gg/modl/backend/realtime/schedule/RealtimeServerHeartbeatEmitterTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,167 @@ | ||
| package gg.modl.backend.realtime.schedule; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertTrue; | ||
| import static org.mockito.ArgumentMatchers.any; | ||
| import static org.mockito.Mockito.mock; | ||
| import static org.mockito.Mockito.never; | ||
| import static org.mockito.Mockito.verify; | ||
| import static org.mockito.Mockito.when; | ||
|
|
||
| import gg.modl.backend.realtime.auth.RealtimePrincipal; | ||
| import gg.modl.backend.realtime.config.RealtimeProperties; | ||
| import gg.modl.backend.realtime.lifecycle.RealtimeConnectionCleanup; | ||
| import gg.modl.backend.realtime.metrics.RealtimeMetrics; | ||
| import gg.modl.backend.realtime.rate.RealtimeMessageRateLimiter; | ||
| import gg.modl.backend.realtime.state.RealtimeConnectionRegistry; | ||
| import gg.modl.backend.realtime.state.RealtimeConnectionState; | ||
| import gg.modl.backend.realtime.transport.RealtimeCodec; | ||
| import gg.modl.backend.realtime.transport.RealtimeSessionOperations; | ||
| import gg.modl.backend.server.data.Server; | ||
| import gg.modl.backend.server.data.ServerPlan; | ||
| import gg.modl.proto.modl.v1.RealtimeEnvelope; | ||
| import io.micrometer.core.instrument.simple.SimpleMeterRegistry; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.mockito.ArgumentCaptor; | ||
| import org.springframework.web.socket.BinaryMessage; | ||
| import org.springframework.web.socket.WebSocketSession; | ||
|
|
||
| /** | ||
| * Guards the server -> client liveness contract. The Minecraft plugin force-reconnects when it sees | ||
| * no inbound frame for 75s, so the backend must emit unsolicited heartbeats on idle connections; | ||
| * without them a healthy, fully subscribed connection is torn down roughly every 100 seconds. | ||
| */ | ||
| class RealtimeServerHeartbeatEmitterTest { | ||
|
|
||
| @Test | ||
| void sendsHeartbeatToAuthenticatedSession() throws Exception { | ||
| Fixture fixture = new Fixture(); | ||
| WebSocketSession session = fixture.openSession("authenticated"); | ||
| RealtimeConnectionState state = fixture.registry.register(session); | ||
| state.authenticate(RealtimePrincipal.minecraft(server()), 1); | ||
|
|
||
| fixture.emitter.emitHeartbeats(); | ||
|
|
||
| ArgumentCaptor<BinaryMessage> captor = ArgumentCaptor.forClass(BinaryMessage.class); | ||
| verify(session).sendMessage(captor.capture()); | ||
| RealtimeEnvelope envelope = RealtimeEnvelope.parseFrom(payload(captor.getValue())); | ||
| assertEquals(RealtimeEnvelope.PayloadCase.HEARTBEAT, envelope.getPayloadCase()); | ||
| } | ||
|
|
||
| /** | ||
| * Both the plugin and the panel transport-ACK any frame carrying a non-empty event_id. An | ||
| * event_id on a heartbeat would therefore double every keepalive into a request/response pair. | ||
| */ | ||
| @Test | ||
| void heartbeatCarriesNoEventIdSoClientsDoNotAckIt() throws Exception { | ||
| Fixture fixture = new Fixture(); | ||
| WebSocketSession session = fixture.openSession("no-ack"); | ||
| RealtimeConnectionState state = fixture.registry.register(session); | ||
| state.authenticate(RealtimePrincipal.minecraft(server()), 1); | ||
|
|
||
| fixture.emitter.emitHeartbeats(); | ||
|
|
||
| ArgumentCaptor<BinaryMessage> captor = ArgumentCaptor.forClass(BinaryMessage.class); | ||
| verify(session).sendMessage(captor.capture()); | ||
| RealtimeEnvelope envelope = RealtimeEnvelope.parseFrom(payload(captor.getValue())); | ||
| assertTrue(envelope.getEventId().isEmpty(), "heartbeat must not carry an event_id"); | ||
| assertEquals(1, envelope.getProtocolVersion()); | ||
| } | ||
|
|
||
| @Test | ||
| void heartbeatSequenceAdvancesPerConnection() throws Exception { | ||
| Fixture fixture = new Fixture(); | ||
| WebSocketSession session = fixture.openSession("sequenced"); | ||
| RealtimeConnectionState state = fixture.registry.register(session); | ||
| state.authenticate(RealtimePrincipal.minecraft(server()), 1); | ||
|
|
||
| fixture.emitter.emitHeartbeats(); | ||
| fixture.emitter.emitHeartbeats(); | ||
|
|
||
| ArgumentCaptor<BinaryMessage> captor = ArgumentCaptor.forClass(BinaryMessage.class); | ||
| verify(session, org.mockito.Mockito.times(2)).sendMessage(captor.capture()); | ||
| long first = RealtimeEnvelope.parseFrom(payload(captor.getAllValues().get(0))).getHeartbeat().getSequence(); | ||
| long second = RealtimeEnvelope.parseFrom(payload(captor.getAllValues().get(1))).getHeartbeat().getSequence(); | ||
| assertEquals(1L, first); | ||
| assertEquals(2L, second); | ||
| } | ||
|
|
||
| @Test | ||
| void doesNotHeartbeatUnauthenticatedSession() throws Exception { | ||
| Fixture fixture = new Fixture(); | ||
| WebSocketSession session = fixture.openSession("unauthenticated"); | ||
| fixture.registry.register(session); | ||
|
|
||
| fixture.emitter.emitHeartbeats(); | ||
|
|
||
| verify(session, never()).sendMessage(any(BinaryMessage.class)); | ||
| } | ||
|
|
||
| @Test | ||
| void doesNotHeartbeatTerminalSession() throws Exception { | ||
| Fixture fixture = new Fixture(); | ||
| WebSocketSession session = fixture.openSession("terminal"); | ||
| RealtimeConnectionState state = fixture.registry.register(session); | ||
| state.authenticate(RealtimePrincipal.minecraft(server()), 1); | ||
| state.markClosing(); | ||
| state.markTerminal(); | ||
|
|
||
| fixture.emitter.emitHeartbeats(); | ||
|
|
||
| verify(session, never()).sendMessage(any(BinaryMessage.class)); | ||
| } | ||
|
|
||
| @Test | ||
| void doesNothingWhenRealtimeDisabled() throws Exception { | ||
| Fixture fixture = new Fixture(); | ||
| fixture.properties.setEnabled(false); | ||
| WebSocketSession session = fixture.openSession("disabled"); | ||
| RealtimeConnectionState state = fixture.registry.register(session); | ||
| state.authenticate(RealtimePrincipal.minecraft(server()), 1); | ||
|
|
||
| fixture.emitter.emitHeartbeats(); | ||
|
|
||
| verify(session, never()).sendMessage(any(BinaryMessage.class)); | ||
| } | ||
|
|
||
| private static final class Fixture { | ||
| private final RealtimeProperties properties = new RealtimeProperties(); | ||
| private final RealtimeConnectionRegistry registry; | ||
| private final RealtimeServerHeartbeatEmitter emitter; | ||
|
|
||
| private Fixture() { | ||
| properties.setEnabled(true); | ||
| registry = new RealtimeConnectionRegistry(properties); | ||
| RealtimeMetrics metrics = new RealtimeMetrics(new SimpleMeterRegistry()); | ||
| RealtimeConnectionCleanup cleanup = | ||
| new RealtimeConnectionCleanup(registry, new RealtimeMessageRateLimiter(properties), metrics); | ||
| emitter = new RealtimeServerHeartbeatEmitter( | ||
| properties, | ||
| registry, | ||
| new RealtimeCodec(properties), | ||
| new RealtimeSessionOperations(registry, cleanup, metrics) | ||
| ); | ||
| } | ||
|
|
||
| private WebSocketSession openSession(String id) { | ||
| WebSocketSession session = mock(WebSocketSession.class); | ||
| when(session.getId()).thenReturn(id); | ||
| when(session.isOpen()).thenReturn(true); | ||
| when(session.getAttributes()).thenReturn(new ConcurrentHashMap<>()); | ||
| return session; | ||
| } | ||
| } | ||
|
|
||
| private static byte[] payload(BinaryMessage message) { | ||
| byte[] payload = new byte[message.getPayloadLength()]; | ||
| message.getPayload().get(payload); | ||
| return payload; | ||
| } | ||
|
|
||
| private static Server server() { | ||
| Server server = new Server("server", "server", "server_db", "admin@example.com", true, ServerPlan.FREE); | ||
| server.setId("server-id"); | ||
| return server; | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.