Skip to content

Commit 44c568b

Browse files
[Fix] WebSocket close bug (#238)
1 parent 4760f81 commit 44c568b

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

.changeset/pretty-zebras-brush.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@powersync/common': patch
3+
---
4+
5+
Fix issue where WebSockets might not close under some error conditions.

packages/common/src/client/sync/stream/AbstractRemote.ts

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -253,9 +253,18 @@ export abstract class AbstractRemote {
253253
socketIsClosed = true;
254254
rsocket.close();
255255
};
256+
// Helps to prevent double close scenarios
257+
rsocket.onClose(() => (socketIsClosed = true));
256258
// We initially request this amount and expect these to arrive eventually
257259
let pendingEventsCount = SYNC_QUEUE_REQUEST_N;
258260

261+
const disposeClosedListener = stream.registerListener({
262+
closed: () => {
263+
closeSocket();
264+
disposeClosedListener();
265+
}
266+
});
267+
259268
const socket = await new Promise<Requestable>((resolve, reject) => {
260269
let connectionEstablished = false;
261270

@@ -275,9 +284,8 @@ export abstract class AbstractRemote {
275284
if (e.message !== 'Closed. ') {
276285
this.logger.error(e);
277286
}
278-
// RSocket will close this automatically
279-
// Attempting to close multiple times causes a console warning
280-
socketIsClosed = true;
287+
// RSocket will close the RSocket stream automatically
288+
// Close the downstream stream as well - this will close the RSocket connection and WebSocket
281289
stream.close();
282290
// Handles cases where the connection failed e.g. auth error or connection error
283291
if (!connectionEstablished) {
@@ -318,8 +326,7 @@ export abstract class AbstractRemote {
318326
}
319327
},
320328
closed: () => {
321-
closeSocket();
322-
l?.();
329+
l();
323330
}
324331
});
325332

0 commit comments

Comments
 (0)