refactor: migrate WebSocket proxy to v1-ws-proxy module
- Updated import paths to use the new v1-ws-proxy module. - Removed the old ws-proxy module and its associated files. - Implemented new WebSocket proxy logic in the v1-ws-proxy module. - Adjusted UserV1Proxy to utilize the new WebSocket proxy manager and methods.
This commit is contained in:
58
src/modules/v1-ws-proxy/index.ts
Normal file
58
src/modules/v1-ws-proxy/index.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { WsProxyManager } from './manager.ts';
|
||||
import { getLoginUserByToken } from '@/modules/auth.ts';
|
||||
import { logger } from '../logger.ts';
|
||||
export const wsProxyManager = new WsProxyManager();
|
||||
import { WebSocketListenerFun } from '@kevisual/router/src/server/server-type.ts'
|
||||
export const wssFun: WebSocketListenerFun = async (req, res) => {
|
||||
// do nothing, just to enable ws upgrade event
|
||||
const { id, ws, token, data, emitter } = req;
|
||||
logger.debug('ws proxy connected, id=', id, ' token=', token, ' data=', data);
|
||||
// console.log('req', req)
|
||||
const { type } = data || {};
|
||||
if (type === 'registryClient') {
|
||||
const loginUser = await getLoginUserByToken(token);
|
||||
if (!loginUser?.tokenUser) {
|
||||
logger.debug('未登录,断开连接');
|
||||
ws.send(JSON.stringify({ code: 401, message: '未登录' }));
|
||||
setTimeout(() => {
|
||||
ws.close(401, 'Unauthorized');
|
||||
}, 1000);
|
||||
return;
|
||||
}
|
||||
const user = loginUser?.tokenUser?.username;
|
||||
const userApp = user + '--' + id;
|
||||
logger.debug('注册 ws 连接', userApp);
|
||||
const wsMessage = wsProxyManager.get(userApp);
|
||||
if (wsMessage) {
|
||||
logger.debug('ws 连接已存在,关闭旧连接', userApp);
|
||||
wsMessage.ws.close();
|
||||
wsProxyManager.unregister(userApp);
|
||||
}
|
||||
// @ts-ignore
|
||||
wsProxyManager.register(userApp, { user, ws });
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: 'connected',
|
||||
user: user,
|
||||
id,
|
||||
}),
|
||||
);
|
||||
emitter.once('close--' + id, () => {
|
||||
logger.debug('ws emitter closed');
|
||||
wsProxyManager.unregister(userApp);
|
||||
});
|
||||
// @ts-ignore
|
||||
ws.data.userApp = userApp;
|
||||
return;
|
||||
}
|
||||
// @ts-ignore
|
||||
const userApp = ws.data.userApp;
|
||||
logger.debug('message', data, ' userApp=', userApp);
|
||||
const wsMessage = wsProxyManager.get(userApp);
|
||||
if (wsMessage) {
|
||||
wsMessage.sendResponse(data);
|
||||
} else {
|
||||
// @ts-ignore
|
||||
logger.debug('账号应用未注册,无法处理消息。未授权?', ws.data);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user