Skip to content

Commit ecb2940

Browse files
committed
fix: beef up socket retry logic
1 parent 4364a3d commit ecb2940

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

site/src/modules/resources/AgentMetadata.tsx

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -64,35 +64,38 @@ export const AgentMetadata: FC<AgentMetadataProps> = ({
6464
}
6565

6666
let timeoutId: number | undefined = undefined;
67-
let latestSocket: OneWayWebSocket | undefined = undefined;
67+
let activeSocket: OneWayWebSocket | undefined = undefined;
6868
let retries = 0;
6969

7070
const createNewConnection = () => {
7171
const socket = watchAgentMetadata(agent.id);
72-
latestSocket = socket;
72+
activeSocket = socket;
7373

7474
socket.addEventListener("error", () => {
7575
setActiveMetadata(undefined);
7676
window.clearTimeout(timeoutId);
7777

78+
// The error event is supposed to fire when an error happens
79+
// with the connection itself, which implies that the connection
80+
// would auto-close. Couldn't find a definitive answer on MDN,
81+
// though, so closing it manually just to be safe
82+
socket.close();
83+
activeSocket = undefined;
84+
7885
retries++;
79-
if (retries < maxSocketErrorRetryCount) {
86+
if (retries >= maxSocketErrorRetryCount) {
8087
displayError(
81-
"Unexpected disconnect while watching Metadata changes. Creating new connection...",
88+
"Unexpected disconnect while watching Metadata changes. Please try refreshing the page.",
8289
);
83-
timeoutId = window.setTimeout(() => {
84-
createNewConnection();
85-
}, 3_000);
8690
return;
8791
}
8892

8993
displayError(
90-
"Unexpected disconnect while watching Metadata changes. Cannot connect to server",
94+
"Unexpected disconnect while watching Metadata changes. Creating new connection...",
9195
);
92-
// The socket should already be closed by this point, but doing
93-
// this just to be thorough
94-
socket.close();
95-
latestSocket = undefined;
96+
timeoutId = window.setTimeout(() => {
97+
createNewConnection();
98+
}, 3_000);
9699
});
97100

98101
socket.addEventListener("message", (e) => {
@@ -112,7 +115,7 @@ export const AgentMetadata: FC<AgentMetadataProps> = ({
112115
createNewConnection();
113116
return () => {
114117
window.clearTimeout(timeoutId);
115-
latestSocket?.close();
118+
activeSocket?.close();
116119
};
117120
}, [agent.id, storybookMetadata]);
118121

0 commit comments

Comments
 (0)