Skip to content

Commit dc70ab4

Browse files
authored
ws reconnection bug + clean up logging (#1058)
1 parent 123b627 commit dc70ab4

File tree

7 files changed

+42
-31
lines changed

7 files changed

+42
-31
lines changed

emain/docsite.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@ export async function initDocsite() {
1717
console.log("Embedded docsite is running, using embedded version for help view");
1818
docsiteUrl = docsiteEmbeddedUrl;
1919
} else {
20-
console.log("Embedded docsite is not running, using web version for help view", response);
20+
console.log(
21+
"Embedded docsite is not running, using web version for help view",
22+
"status: " + response?.status
23+
);
2124
docsiteUrl = docsiteWebUrl;
2225
}
2326
} catch (error) {

emain/emain.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1075,7 +1075,7 @@ async function relaunchBrowserWindows(): Promise<void> {
10751075
}
10761076
for (const win of wins) {
10771077
await win.readyPromise;
1078-
console.log("show", win.waveWindowId);
1078+
console.log("show window", win.waveWindowId);
10791079
win.show();
10801080
}
10811081
}

frontend/app/store/ws.ts

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const dlog = debug("wave:ws");
1212
const WarnWebSocketSendSize = 1024 * 1024; // 1MB
1313
const MaxWebSocketSendSize = 5 * 1024 * 1024; // 5MB
1414
const reconnectHandlers: (() => void)[] = [];
15+
const StableConnTime = 2000;
1516

1617
function addWSReconnectHandler(handler: () => void) {
1718
reconnectHandlers.push(handler);
@@ -45,6 +46,7 @@ class WSControl {
4546
lastReconnectTime: number = 0;
4647
eoOpts: ElectronOverrideOpts;
4748
noReconnect: boolean = false;
49+
onOpenTimeoutId: NodeJS.Timeout = null;
4850

4951
constructor(
5052
baseHostPort: string,
@@ -80,9 +82,15 @@ class WSControl {
8082
}
8183
: null
8284
);
83-
this.wsConn.onopen = this.onopen.bind(this);
84-
this.wsConn.onmessage = this.onmessage.bind(this);
85-
this.wsConn.onclose = this.onclose.bind(this);
85+
this.wsConn.onopen = (e: Event) => {
86+
this.onopen(e);
87+
};
88+
this.wsConn.onmessage = (e: MessageEvent) => {
89+
this.onmessage(e);
90+
};
91+
this.wsConn.onclose = (e: CloseEvent) => {
92+
this.onclose(e);
93+
};
8694
// turns out onerror is not necessary (onclose always follows onerror)
8795
// this.wsConn.onerror = this.onerror;
8896
}
@@ -118,8 +126,11 @@ class WSControl {
118126
}, timeout * 1000);
119127
}
120128

121-
onclose(event: any) {
129+
onclose(event: CloseEvent) {
122130
// console.log("close", event);
131+
if (this.onOpenTimeoutId) {
132+
clearTimeout(this.onOpenTimeoutId);
133+
}
123134
if (event.wasClean) {
124135
dlog("connection closed");
125136
} else {
@@ -132,15 +143,18 @@ class WSControl {
132143
}
133144
}
134145

135-
onopen() {
146+
onopen(e: Event) {
136147
dlog("connection open");
137148
this.open = true;
138149
this.opening = false;
150+
this.onOpenTimeoutId = setTimeout(() => {
151+
this.reconnectTimes = 0;
152+
dlog("clear reconnect times");
153+
}, StableConnTime);
139154
for (let handler of reconnectHandlers) {
140155
handler();
141156
}
142157
this.runMsgQueue();
143-
// reconnectTimes is reset in onmessage:hello
144158
}
145159

146160
runMsgQueue() {
@@ -157,7 +171,7 @@ class WSControl {
157171
}, 100);
158172
}
159173

160-
onmessage(event: any) {
174+
onmessage(event: MessageEvent) {
161175
let eventData = null;
162176
if (event.data != null) {
163177
eventData = JSON.parse(event.data);
@@ -173,10 +187,6 @@ class WSControl {
173187
// nothing
174188
return;
175189
}
176-
if (eventData.type == "hello") {
177-
this.reconnectTimes = 0;
178-
return;
179-
}
180190
if (this.messageCallback) {
181191
try {
182192
this.messageCallback(eventData);

frontend/app/view/webview/webview.tsx

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ export class WebViewModel implements ViewModel {
6060
this.homepageUrl = atom((get) => {
6161
const defaultUrl = get(defaultUrlAtom);
6262
const pinnedUrl = get(this.blockAtom).meta.pinnedurl;
63-
console.log("homepageUrl", pinnedUrl, defaultUrl);
6463
return pinnedUrl ?? defaultUrl;
6564
});
6665
this.urlWrapperClassName = atom("");

pkg/blockcontroller/blockcontroller.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,6 @@ func (bc *BlockController) DoRunShellCommand(rc *RunShellOpts, blockMeta waveobj
369369
bc.ShellProc.Cmd.Write(ic.InputData)
370370
}
371371
if ic.TermSize != nil {
372-
log.Printf("SETTERMSIZE: %dx%d\n", ic.TermSize.Rows, ic.TermSize.Cols)
373372
err = setTermSize(ctx, bc.BlockId, *ic.TermSize)
374373
if err != nil {
375374
log.Printf("error setting pty size: %v\n", err)

pkg/web/ws.go

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ func RunWebSocketServer(listener net.Listener) {
4040
Handler: gr,
4141
}
4242
server.SetKeepAlivesEnabled(false)
43-
log.Printf("Running websocket server on %s\n", listener.Addr())
43+
log.Printf("[websocket] running websocket server on %s\n", listener.Addr())
4444
err := server.Serve(listener)
4545
if err != nil {
46-
log.Printf("[error] trying to run websocket server: %v\n", err)
46+
log.Printf("[websocket] error trying to run websocket server: %v\n", err)
4747
}
4848
}
4949

@@ -81,7 +81,7 @@ func processWSCommand(jmsg map[string]any, outputCh chan any, rpcInputCh chan []
8181
r := recover()
8282
if r != nil {
8383
rtnErr = fmt.Errorf("panic: %v", r)
84-
log.Printf("panic in processMessage: %v\n", r)
84+
log.Printf("[websocket] panic in processMessage: %v\n", r)
8585
debug.PrintStack()
8686
}
8787
if rtnErr == nil {
@@ -108,7 +108,7 @@ func processWSCommand(jmsg map[string]any, outputCh chan any, rpcInputCh chan []
108108
msgBytes, err := json.Marshal(rpcMsg)
109109
if err != nil {
110110
// this really should never fail since we just unmarshalled this value
111-
log.Printf("error marshalling rpc message: %v\n", err)
111+
log.Printf("[websocket] error marshalling rpc message: %v\n", err)
112112
return
113113
}
114114
rpcInputCh <- msgBytes
@@ -125,7 +125,7 @@ func processWSCommand(jmsg map[string]any, outputCh chan any, rpcInputCh chan []
125125
msgBytes, err := json.Marshal(rpcMsg)
126126
if err != nil {
127127
// this really should never fail since we just unmarshalled this value
128-
log.Printf("error marshalling rpc message: %v\n", err)
128+
log.Printf("[websocket] error marshalling rpc message: %v\n", err)
129129
return
130130
}
131131
rpcInputCh <- msgBytes
@@ -152,21 +152,21 @@ func processMessage(jmsg map[string]any, outputCh chan any, rpcInputCh chan []by
152152
processWSCommand(jmsg, outputCh, rpcInputCh)
153153
}
154154

155-
func ReadLoop(conn *websocket.Conn, outputCh chan any, closeCh chan any, rpcInputCh chan []byte) {
155+
func ReadLoop(conn *websocket.Conn, outputCh chan any, closeCh chan any, rpcInputCh chan []byte, routeId string) {
156156
readWait := wsReadWaitTimeout
157157
conn.SetReadLimit(64 * 1024)
158158
conn.SetReadDeadline(time.Now().Add(readWait))
159159
defer close(closeCh)
160160
for {
161161
_, message, err := conn.ReadMessage()
162162
if err != nil {
163-
log.Printf("ReadPump error: %v\n", err)
163+
log.Printf("[websocket] ReadPump error (%s): %v\n", routeId, err)
164164
break
165165
}
166166
jmsg := map[string]any{}
167167
err = json.Unmarshal(message, &jmsg)
168168
if err != nil {
169-
log.Printf("Error unmarshalling json: %v\n", err)
169+
log.Printf("[websocket] error unmarshalling json: %v\n", err)
170170
break
171171
}
172172
conn.SetReadDeadline(time.Now().Add(readWait))
@@ -197,7 +197,7 @@ func WritePing(conn *websocket.Conn) error {
197197
return nil
198198
}
199199

200-
func WriteLoop(conn *websocket.Conn, outputCh chan any, closeCh chan any) {
200+
func WriteLoop(conn *websocket.Conn, outputCh chan any, closeCh chan any, routeId string) {
201201
ticker := time.NewTicker(wsInitialPingTime)
202202
defer ticker.Stop()
203203
initialPing := true
@@ -211,22 +211,22 @@ func WriteLoop(conn *websocket.Conn, outputCh chan any, closeCh chan any) {
211211
} else {
212212
barr, err = json.Marshal(msg)
213213
if err != nil {
214-
log.Printf("cannot marshal websocket message: %v\n", err)
214+
log.Printf("[websocket] cannot marshal websocket message: %v\n", err)
215215
// just loop again
216216
break
217217
}
218218
}
219219
err = conn.WriteMessage(websocket.TextMessage, barr)
220220
if err != nil {
221221
conn.Close()
222-
log.Printf("WritePump error: %v\n", err)
222+
log.Printf("[websocket] WritePump error (%s): %v\n", routeId, err)
223223
return
224224
}
225225

226226
case <-ticker.C:
227227
err := WritePing(conn)
228228
if err != nil {
229-
log.Printf("WritePump error: %v\n", err)
229+
log.Printf("[websocket] WritePump error (%s): %v\n", routeId, err)
230230
return
231231
}
232232
if initialPing {
@@ -250,6 +250,7 @@ func HandleWsInternal(w http.ResponseWriter, r *http.Request) error {
250250
if err != nil {
251251
w.WriteHeader(http.StatusUnauthorized)
252252
w.Write([]byte(fmt.Sprintf("error validating authkey: %v", err)))
253+
log.Printf("[websocket] error validating authkey: %v\n", err)
253254
return err
254255
}
255256
conn, err := WebSocketUpgrader.Upgrade(w, r, nil)
@@ -258,7 +259,6 @@ func HandleWsInternal(w http.ResponseWriter, r *http.Request) error {
258259
}
259260
defer conn.Close()
260261
wsConnId := uuid.New().String()
261-
log.Printf("New websocket connection: windowid:%s connid:%s\n", windowId, wsConnId)
262262
outputCh := make(chan any, 100)
263263
closeCh := make(chan any)
264264
eventbus.RegisterWSChannel(wsConnId, windowId, outputCh)
@@ -269,6 +269,7 @@ func HandleWsInternal(w http.ResponseWriter, r *http.Request) error {
269269
routeId = wshutil.MakeWindowRouteId(windowId)
270270
}
271271
defer eventbus.UnregisterWSChannel(wsConnId)
272+
log.Printf("[websocket] new connection: windowid:%s connid:%s routeid:%s\n", windowId, wsConnId, routeId)
272273
// we create a wshproxy to handle rpc messages to/from the window
273274
wproxy := wshutil.MakeRpcProxy()
274275
wshutil.DefaultRouter.RegisterRoute(routeId, wproxy)
@@ -293,12 +294,12 @@ func HandleWsInternal(w http.ResponseWriter, r *http.Request) error {
293294
go func() {
294295
// read loop
295296
defer wg.Done()
296-
ReadLoop(conn, outputCh, closeCh, wproxy.FromRemoteCh)
297+
ReadLoop(conn, outputCh, closeCh, wproxy.FromRemoteCh, routeId)
297298
}()
298299
go func() {
299300
// write loop
300301
defer wg.Done()
301-
WriteLoop(conn, outputCh, closeCh)
302+
WriteLoop(conn, outputCh, closeCh, routeId)
302303
}()
303304
wg.Wait()
304305
close(wproxy.FromRemoteCh)

pkg/wshrpc/wshserver/wshserver.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,6 @@ func (ws *WshServer) EventPublishCommand(ctx context.Context, data wps.WaveEvent
422422
}
423423

424424
func (ws *WshServer) EventSubCommand(ctx context.Context, data wps.SubscriptionRequest) error {
425-
log.Printf("EventSubCommand: %v\n", data)
426425
rpcSource := wshutil.GetRpcSourceFromContext(ctx)
427426
if rpcSource == "" {
428427
return fmt.Errorf("no rpc source set")

0 commit comments

Comments
 (0)