@@ -142,6 +142,47 @@ function detect_auth_error(requestToken, client_origin, server_origin, host) {
142142 }
143143}
144144
145+ // Combines duplicated lines into a single message (log message + number of skipped messages)
146+ function createLogger ( ) {
147+ // Combine logs for logInterval ms duration
148+ const logInterval = 5000 ;
149+ const messages = [ ] ;
150+ let lastLog = 0 ;
151+ let timer ;
152+
153+ const logQueuedMessages = ( immediate = false ) => {
154+ const now = Date . now ( ) ;
155+ clearTimeout ( timer ) ;
156+ // Nothing logged since logInterval, log immediately
157+ if ( now - lastLog > logInterval || immediate ) {
158+ for ( const { message, count } of messages ) {
159+ console . log ( message ) ;
160+ if ( count > 1 ) {
161+ console . log ( `Skipped ${ count - 1 } previous duplicated messages` ) ;
162+ }
163+ }
164+ messages . length = 0 ;
165+ lastLog = now ;
166+ } else if ( messages . length > 0 ) {
167+ // Log at most logInterval duration since current queue started
168+ timer = setTimeout ( logQueuedMessages , ( lastLog + logInterval - now ) ) ;
169+ }
170+ }
171+
172+ return {
173+ log : ( msg ) => {
174+ const lastMessage = messages . at ( - 1 ) ;
175+ if ( lastMessage && lastMessage . message == msg ) {
176+ lastMessage . count ++ ;
177+ } else {
178+ messages . push ( { "message" : msg , count : 1 } ) ;
179+ }
180+ logQueuedMessages ( ) ;
181+ } ,
182+ flush : ( ) => logQueuedMessages ( true ) ,
183+ } ;
184+ } ;
185+
145186wss . on ( 'connection' , function connection ( ws , req ) {
146187 var dir ,
147188 term ,
@@ -152,7 +193,8 @@ wss.on('connection', function connection (ws, req) {
152193 ws . isAlive = true ;
153194 ws . startedAt = Date . now ( ) ;
154195 ws . lastActivity = Date . now ( ) ;
155-
196+ ws . logger = createLogger ( ) ;
197+
156198 console . log ( 'Connection established' ) ;
157199
158200 [ host , dir ] = host_and_dir_from_url ( req . url ) ;
@@ -179,7 +221,12 @@ wss.on('connection', function connection (ws, req) {
179221
180222 term . onData ( function ( data ) {
181223 ws . send ( data , function ( error ) {
182- if ( error ) console . log ( 'Send error: ' + error . message ) ;
224+ if ( ws . readyState === WebSocket . CLOSED || ws . readyState === WebSocket . CLOSING ) {
225+ ws . logger . log ( 'The websocket will not receive any more messages. Killing the terminal connection' ) ;
226+ term . kill ( ) ;
227+ } else if ( error ) {
228+ ws . logger . log ( 'Send error: ' + error . message ) ;
229+ }
183230 } ) ;
184231 ws . lastActivity = Date . now ( ) ;
185232 } ) ;
@@ -201,6 +248,7 @@ wss.on('connection', function connection (ws, req) {
201248 term . end ( ) ;
202249 this . isAlive = false ;
203250 console . log ( 'Closed terminal: ' + term . pid ) ;
251+ ws . logger . flush ( ) ;
204252 } ) ;
205253
206254 ws . on ( 'pong' , function ( ) {
0 commit comments