Skip to content

Commit 4fe60ab

Browse files
committed
Change logic when two clients are using the same key
This is because sending keepalive with sendComment/sendEvent does not actually recognize the client as terminated immediately.
1 parent 4df97ce commit 4fe60ab

1 file changed

Lines changed: 9 additions & 27 deletions

File tree

src/main/java/net/earthmc/emcapi/sse/SSEManager.java

Lines changed: 9 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -59,28 +59,6 @@ public void loadSSE() {
5959
return;
6060
}
6161

62-
final ClientData existingClient = CLIENTS.get(key);
63-
if (existingClient != null) {
64-
// check if the other client is still active
65-
// prevent sending more than one keepalive per second
66-
final long now = System.currentTimeMillis();
67-
final long lastKeepAlive = existingClient.lastManualKeepAlive.getAndUpdate(prev ->
68-
(prev == 0 || now - prev > 1000) ? now : prev
69-
);
70-
71-
final boolean sendKeepAlive = lastKeepAlive == 0 || now - lastKeepAlive > 1000;
72-
73-
if (sendKeepAlive) {
74-
existingClient.client.sendComment("keepalive");
75-
}
76-
77-
if (!sendKeepAlive || !existingClient.client.terminated()) {
78-
client.sendEvent("error", msg("This API key is already in use."));
79-
client.close();
80-
return;
81-
}
82-
}
83-
8462
Set<String> events = new HashSet<>();
8563
Set<String> invalid = new HashSet<>();
8664

@@ -107,6 +85,14 @@ public void loadSSE() {
10785
return;
10886
}
10987

88+
ClientData existingClient = CLIENTS.get(key);
89+
if (existingClient != null) {
90+
if (!existingClient.client.terminated()) {
91+
existingClient.client.sendEvent("close", msg("Another client has connected with this API Key. If this was not you, revoke your API key."));
92+
}
93+
existingClient.client.close();
94+
}
95+
11096
ClientData data = new ClientData(client, Set.copyOf(events), owner);
11197
client.keepAlive();
11298
client.sendEvent("open", msg("Connected to the EarthMC API."));
@@ -199,11 +185,7 @@ private static String msg(final String message) {
199185
return object.toString();
200186
}
201187

202-
public record ClientData(SseClient client, @Unmodifiable Set<String> events, UUID playerID, AtomicLong lastManualKeepAlive) {
203-
public ClientData(final SseClient client, final Set<String> events, final UUID playerID) {
204-
this(client, events, playerID, new AtomicLong());
205-
}
206-
188+
public record ClientData(SseClient client, @Unmodifiable Set<String> events, UUID playerID) {
207189
public ClientData {
208190
events = Set.copyOf(events);
209191
}

0 commit comments

Comments
 (0)