Skip to content

Commit

Permalink
Merge pull request #69 from 100-hours-a-week/dev
Browse files Browse the repository at this point in the history
v0.1.1 release
  • Loading branch information
jjikky authored Oct 7, 2024
2 parents 581d923 + 79ff997 commit c1b6d11
Show file tree
Hide file tree
Showing 10 changed files with 290 additions and 227 deletions.
11 changes: 5 additions & 6 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
const express = require('express');
const fs = require('fs');
const https = require('https');
const express = require('express');
const socketio = require('socket.io');
const config = require('./src/common/config');
const expressLoader = require('./src/common/modules/express');
const socketIoLoader = require('./src/socket.loader');
const logger = require('./src/common/modules/logger');
const expressLoader = require('./src/common/modules/express');
const socketIoLoader = require('./src/handlers/socket.handler');
const { START_MESSAGE } = require('./src/common/constants/express');

const app = express();

const socketio = require('socket.io');
const { START_MESSAGE } = require('./src/common/constants/express');

const initLocalServer = async () => {
await expressLoader(app);

Expand Down
14 changes: 14 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
services:
dao-signaling-server:
build: .
container_name: dao-signaling-server
env_file:
- .env
networks:
- backend-network
ports:
- '8083:8083'

networks:
backend-network:
external: true
1 change: 0 additions & 1 deletion src/common/constants/error-message.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const ErrorMessage = Object.freeze({
// 환경변수
ENV_FILE_NOT_FOUND: '환경변수 파일을 찾을 수 없습니다.',
NODE_ENV_WRONG:
'NODE_ENV가 올바르게 설정되지 않았습니다. [ production / development / local 중 하나로 설정되어야 합니다.\n 명시되지 않음으로 인해 development로 설정 됩니다.',
Expand Down
3 changes: 1 addition & 2 deletions src/common/modules/express/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ module.exports = expressLoader = (app) => {
cors({
credentials: true,
origin: (origin, callback) => {
// TODO : SSL 연결 후 !origin 삭제
if (config.corsWhiteList.indexOf(origin) !== -1 || !origin) {
return callback(null, true);
}
Expand All @@ -19,7 +18,7 @@ module.exports = expressLoader = (app) => {
})(req, res, next);
});

app.use('/', (req, res) => {
app.use('/', (_, res) => {
res.status(200).send('DAO SIGNALING SERVER');
});
};
132 changes: 0 additions & 132 deletions src/handler/socket.handler.js

This file was deleted.

107 changes: 107 additions & 0 deletions src/handlers/socket.handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
const axios = require('axios');
const https = require('https');
const config = require('../common/config');
const logger = require('../common/modules/logger');
const { getResponseTimeMs } = require('../common/utils/time.util');
const handshakeMiddleware = require('../middlewares/handshake');
const {
handleObjetJoin,
handleOffer,
handleAnswer,
handleCandidate,
handleDisconnect,
} = require('../services/socket.service');

module.exports = socketIoLoader = (io) => {
io.use(handshakeMiddleware);

io.on('connection', async (socket) => {
const socket_id = socket.id;
const { token, lounge_id } = socket.handshake.query;
const startTime = process.hrtime();

validateHandShake(token, lounge_id);

try {
await validateRequest(token, lounge_id, socket);
logSuccess(socket, lounge_id, socket_id, startTime);
} catch (err) {
handleError(err, socket, lounge_id, socket_id, startTime);
return;
}

setupSocketEvents(socket, io, socket_id);
});
};

const validateRequest = async (token, lounge_id, socket) => {
return axios.post(
`${config.springServerUrl}/lounges/validate`,
{ lounge_id },
{
headers: {
Authorization: `Bearer ${token}`,
'x-request-id': socket.xRequestId,
},
httpsAgent: new https.Agent({
rejectUnauthorized: false,
}),
}
);
};

const logSuccess = (socket, lounge_id, socket_id, startTime) => {
const responseTime = getResponseTimeMs(startTime);
logger.info(
`[연결 성공] - 라운지 ID: ${lounge_id}, 소켓 ID: ${socket_id}, x-request-id: ${socket.xRequestId}, 응답 시간: ${responseTime}ms`
);
};

const handleError = (err, socket, lounge_id, socket_id, startTime) => {
const responseTime = getResponseTimeMs(startTime);
logger.error(
`[연결 오류] - 라운지 ID: ${lounge_id}, 소켓 ID: ${socket_id}, 오류 내용: ${
JSON.stringify(err.response?.data) || err.message
}, x-request-id: ${socket.xRequestId}, 응답 시간: ${responseTime}ms`
);
socket.emit('error_message', {
error: err.response?.data || '알 수 없는 오류',
});
socket.disconnect(true);
};

const setupSocketEvents = (socket, io, socket_id) => {
socket.on('join_objet', async (data) => {
await handleObjetJoin(io, socket, data, socket_id);
});

socket.on('offer', (data) => {
handleOffer(socket, data);
});

socket.on('answer', (data) => {
handleAnswer(socket, data);
});

socket.on('candidate', (data) => {
handleCandidate(socket, data);
});

socket.on('disconnect', async () => {
await handleDisconnect(socket, socket_id);
});
};

const validateHandShake = (token, lounge_id) => {
if (!token || !lounge_id) {
return handleMissingParams(socket, socket_id);
}
};

const handleMissingParams = (socket, socket_id) => {
logger.warn(`[연결 실패] - 토큰 또는 라운지 ID가 없습니다. 소켓 ID: ${socket_id}`);
socket.emit('error_message', {
error: '토큰 또는 라운지 ID가 없습니다',
});
socket.disconnect(true);
};
File renamed without changes.
36 changes: 36 additions & 0 deletions src/repositories/objet.repository.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const redisCli = require('../common/modules/redis');

class ObjetRepository {
async getUsersInObjet(objetKey) {
return await redisCli.lRange(objetKey, 0, -1);
}

async addUserToObjet(objetKey, user) {
return await redisCli.rPush(objetKey, JSON.stringify(user));
}

async setSocketToObjet(socketKey, objet_id) {
return await redisCli.set(socketKey, String(objet_id));
}

async getObjetBySocket(socketKey) {
return await redisCli.get(socketKey);
}

async deleteSocket(socketKey) {
return await redisCli.del(socketKey);
}

async deleteObjet(objetKey) {
return await redisCli.del(objetKey);
}

async updateUsersInObjet(objetKey, usersInObjet) {
await redisCli.del(objetKey);
for (const user of usersInObjet) {
await redisCli.rPush(objetKey, user);
}
}
}

module.exports = new ObjetRepository();
Loading

0 comments on commit c1b6d11

Please sign in to comment.