From c72949a228a8f6954c19219bb1ebda0f993a7b51 Mon Sep 17 00:00:00 2001 From: Ganesh Raikhelkar Date: Thu, 14 Nov 2024 16:43:27 -0700 Subject: [PATCH] fix: browser data when cira channel is closed (#1707) --- src/utils/wsRedirect.test.ts | 29 ++++++++++++++++++++++++++++- src/utils/wsRedirect.ts | 8 +++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/utils/wsRedirect.test.ts b/src/utils/wsRedirect.test.ts index 23a56a1dc..34e501e5c 100644 --- a/src/utils/wsRedirect.test.ts +++ b/src/utils/wsRedirect.test.ts @@ -66,7 +66,11 @@ describe('WsRedirect tests', () => { const message: any = { data: 'hello' } wsRedirect.websocketFromDevice = { - writeData: jest.fn() + writeData: jest.fn(), + state: 1 + } as any + wsRedirect.websocketFromWeb = { + close: jest.fn() } as any wsRedirect.interceptor = { processBrowserData: jest.fn() @@ -74,11 +78,34 @@ describe('WsRedirect tests', () => { const interceptorSpy = spyOn(wsRedirect.interceptor, 'processBrowserData').mockReturnValue('binaryData') const writeSpy = spyOn(wsRedirect.websocketFromDevice, 'writeData') void wsRedirect.handleMessage(message) + const closeSpy = spyOn(wsRedirect.websocketFromWeb, 'close') expect(interceptorSpy).toBeCalledWith(message.data) expect(writeSpy).toBeCalledWith('binaryData') }) + it('should close websocket conn to browser if cira channel is closed', () => { + const message: any = { data: 'hello' } + + wsRedirect.websocketFromDevice = { + writeData: jest.fn(), + state: 0 + } as any + wsRedirect.websocketFromWeb = { + close: jest.fn() + } as any + wsRedirect.interceptor = { + processBrowserData: jest.fn() + } as any + const interceptorSpy = spyOn(wsRedirect.interceptor, 'processBrowserData').mockReturnValue('binaryData') + const writeSpy = spyOn(wsRedirect.websocketFromDevice, 'writeData') + void wsRedirect.handleMessage(message) + const closeSpy = spyOn(wsRedirect.websocketFromWeb, 'close') + + expect(interceptorSpy).toBeCalledWith(message.data) + expect(closeSpy).toBeCalled() + }) + describe('handleClose tests', () => { let params: queryParams let publishEventSpy diff --git a/src/utils/wsRedirect.ts b/src/utils/wsRedirect.ts index 6ceb178af..0de7b7d3b 100644 --- a/src/utils/wsRedirect.ts +++ b/src/utils/wsRedirect.ts @@ -70,7 +70,13 @@ export class WsRedirect { if (this.interceptor) { msgStr = this.interceptor.processBrowserData(msgStr) } // Run data thru interceptor - await this.websocketFromDevice.writeData(msgStr) // Forward data to the associated TCP connection. + + if (this.websocketFromDevice && this.websocketFromDevice.state > 0) { + await this.websocketFromDevice.writeData(msgStr) // Forward data to the associated TCP connection. + } else { + logger.error('Attempted to write to a closed CIRA Channel.') + this.websocketFromWeb.close() + } } handleClose(params: queryParams, CloseEvent: WebSocket.CloseEvent): void {