Skip to content

Commit e5f8ea2

Browse files
committed
Code rework v2
1 parent 1e810d6 commit e5f8ea2

3 files changed

Lines changed: 24 additions & 32 deletions

File tree

ice-adapter/src/main/java/com/faforever/iceadapter/debug/TelemetryDebugger.java

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
@Slf4j
3131
@EqualsAndHashCode
3232
public class TelemetryDebugger implements Debugger, AutoCloseable {
33-
private static final int MAX_RECONNECT_ATTEMPTS = 2;
33+
private static final int MAX_RECONNECT_ATTEMPTS = 5;
3434
private static final Duration RECONNECT_BASE_DELAY = Duration.ofSeconds(1);
3535
private static final Duration MAX_RECONNECT_DELAY = Duration.ofSeconds(30);
3636

@@ -40,7 +40,7 @@ public class TelemetryDebugger implements Debugger, AutoCloseable {
4040
private final ObjectMapper objectMapper;
4141

4242
private final Map<Integer, RateLimiter> peerRateLimiter = new ConcurrentHashMap<>();
43-
private final BlockingQueue<OutgoingMessageV1> messageQueue = new LinkedBlockingQueue<>(1000); // Ограничение очереди
43+
private final BlockingQueue<OutgoingMessageV1> messageQueue = new LinkedBlockingQueue<>(1000);
4444

4545
private final Thread sendingLoopThread;
4646

@@ -56,7 +56,6 @@ public TelemetryDebugger(GPGNetServer gpgNetServer, String telemetryServer, int
5656
gameId,
5757
playerId);
5858

59-
// Создаём первый клиент
6059
createNewWebSocketClient();
6160

6261
objectMapper = new ObjectMapper();
@@ -69,8 +68,7 @@ private void createNewWebSocketClient() {
6968
this.websocketClient = new WebSocketClient(websocketUri) {
7069
@Override
7170
public void onOpen(ServerHandshake handshakedata) {
72-
log.info("Telemetry websocket opened");
73-
reconnectAttempt = 0; // Сброс счётчика при успехе
71+
log.trace("Telemetry websocket opened");
7472
}
7573

7674
@Override
@@ -81,7 +79,6 @@ public void onMessage(String message) {
8179
@Override
8280
public void onClose(int code, String reason, boolean remote) {
8381
log.info("Telemetry websocket closed (code: {}, reason: {})", code, reason);
84-
// Клиент закрыт — следующая попытка должна создать новый
8582
}
8683

8784
@Override
@@ -105,8 +102,7 @@ private void sendMessage(OutgoingMessageV1 message) {
105102
private void sendingLoop() {
106103
try {
107104
while (shouldRun) {
108-
OutgoingMessageV1 message = messageQueue.poll(1, TimeUnit.SECONDS);
109-
if (message == null) continue;
105+
OutgoingMessageV1 message = messageQueue.take();
110106

111107
if (!ensureConnected()) {
112108
log.warn("Failed to send telemetry message (no connection): {}", message.getType());
@@ -137,7 +133,9 @@ private void sendingLoop() {
137133

138134
private boolean ensureConnected() throws InterruptedException {
139135
while (shouldRun && !websocketClient.isOpen()) {
140-
if (!shouldRun) return false;
136+
if (!shouldRun) {
137+
return false;
138+
}
141139

142140
// Exponential latency with jitter
143141
Duration delay = RECONNECT_BASE_DELAY.multipliedBy((long) Math.pow(2, Math.min(reconnectAttempt, 5)));
@@ -149,8 +147,9 @@ private boolean ensureConnected() throws InterruptedException {
149147
Thread.sleep(delay.toMillis());
150148

151149
try {
152-
createNewWebSocketClient(); // Создаём новый клиент
150+
createNewWebSocketClient();
153151
if (websocketClient.connectBlocking()) {
152+
reconnectAttempt = 0;
154153
return true;
155154
} else {
156155
log.warn("Failed to connect to telemetry websocket (attempt {}/{})", reconnectAttempt + 1, MAX_RECONNECT_ATTEMPTS);

ice-adapter/src/main/java/com/faforever/iceadapter/gpgnet/FaDataInputStream.java

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.faforever.iceadapter.gpgnet;
22

33
import com.google.common.io.LittleEndianDataInputStream;
4+
45
import java.io.BufferedInputStream;
56
import java.io.IOException;
67
import java.io.InputStream;
@@ -16,13 +17,12 @@ public class FaDataInputStream extends InputStream {
1617

1718
private static final int MAX_CHUNK_SIZE = 10;
1819
private static final int FIELD_TYPE_INT = 0;
19-
private static final int FIELD_TYPE_STRING = 1; // Добавлено: явное определение типа строки
20+
private static final int FIELD_TYPE_STRING = 1;
2021

2122
private final LittleEndianDataInputStream inputStream;
2223
private final Charset charset = StandardCharsets.UTF_8;
2324

2425
public FaDataInputStream(InputStream inputStream) {
25-
// Улучшено: проверка на null
2626
if (inputStream == null) {
2727
throw new IllegalArgumentException("Input stream cannot be null");
2828
}
@@ -55,15 +55,14 @@ public List<Object> readChunks() throws IOException {
5555
chunks.add(readInt());
5656
break;
5757

58-
case FIELD_TYPE_STRING: // Явная обработка строки
58+
case FIELD_TYPE_STRING:
5959
String str = readString();
60-
// Исправлено: замена экранированных последовательностей
61-
str = str.replace("\\t", "\t").replace("\\n", "\n"); // Исправлено: /t → \t
60+
str = str.replace("\\t", "\t").replace("\\n", "\n");
6261
chunks.add(str);
6362
break;
6463

6564
default:
66-
throw new IOException("Unknown field type: " + fieldType); // Лучше чем молчание
65+
throw new IOException("Unknown field type: " + fieldType);
6766
}
6867
}
6968

@@ -90,7 +89,7 @@ public String readString() throws IOException {
9089
}
9190

9291
if (size == 0) {
93-
return ""; // Оптимизация: пустая строка
92+
return "";
9493
}
9594

9695
byte[] buffer = new byte[size];
@@ -100,9 +99,6 @@ public String readString() throws IOException {
10099

101100
@Override
102101
public void close() throws IOException {
103-
// Добавлен null-check (на всякий случай)
104-
if (inputStream != null) {
105-
inputStream.close();
106-
}
102+
inputStream.close();
107103
}
108104
}

ice-adapter/src/main/java/com/faforever/iceadapter/gpgnet/FaDataOutputStream.java

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public class FaDataOutputStream extends OutputStream {
2727
private final LittleEndianDataOutputStream outputStream;
2828
private final Charset charset = StandardCharsets.UTF_8;
2929
private final Lock writer = new ReentrantLock();
30-
private volatile boolean closed = false; // Для отслеживания состояния
30+
private volatile boolean closed = false;
3131

3232
public FaDataOutputStream(OutputStream outputStream) {
3333
if (outputStream == null) {
@@ -50,8 +50,9 @@ public void write(int b) throws IOException {
5050
/**
5151
* Writes a message with header and arguments.
5252
* Supports Integer, Double (as int), and String.
53+
*
5354
* @param header the message header (must not be null)
54-
* @param args the arguments (null values are skipped)
55+
* @param args the arguments (null values are skipped)
5556
* @throws IOException if an I/O error occurs
5657
*/
5758
public void writeMessage(String header, Object... args) throws IOException {
@@ -73,7 +74,9 @@ public void writeMessage(String header, Object... args) throws IOException {
7374

7475
@Override
7576
public void flush() throws IOException {
76-
if (closed) return; // flush после close — допустим, но ничего не делает
77+
if (closed) {
78+
return;
79+
}
7780
writer.lock();
7881
try {
7982
outputStream.flush();
@@ -88,11 +91,7 @@ public void close() throws IOException {
8891
try {
8992
if (closed) return;
9093
closed = true;
91-
try {
92-
outputStream.close();
93-
} finally {
94-
// Даже если close выбросил исключение, всё равно освобождаем ресурсы
95-
}
94+
outputStream.close();
9695
} finally {
9796
writer.unlock();
9897
}
@@ -104,11 +103,9 @@ private void writeArgs(List<Object> args) throws IOException {
104103
return;
105104
}
106105

107-
// Фильтрация null-значений и подсчёт валидных аргументов
108106
List<Object> validArgs = args.stream()
109107
.filter(arg -> {
110108
if (arg == null) {
111-
// Можно включить логирование при необходимости
112109
return false;
113110
}
114111
return true;
@@ -128,7 +125,7 @@ private void writeArgs(List<Object> args) throws IOException {
128125
writeByte(FIELD_TYPE_STRING);
129126
writeString(str);
130127
} else {
131-
log.error("Unsupported argument type: {} {}",arg.getClass().getSimpleName(), arg);
128+
log.error("Unsupported argument type: {} {}", arg.getClass().getSimpleName(), arg);
132129
}
133130
}
134131
}

0 commit comments

Comments
 (0)