replace ws with socketio

This commit is contained in:
Andras Bacsai
2022-11-02 09:49:21 +01:00
parent bdc62a007e
commit eb92d39d40
12 changed files with 247 additions and 141 deletions

View File

@@ -6,9 +6,10 @@ import cookie from '@fastify/cookie';
import multipart from '@fastify/multipart';
import path, { join } from 'path';
import autoLoad from '@fastify/autoload';
import websocket from '@fastify/websocket';
import socketIO from 'fastify-socket.io'
import socketIOServer from './realtime'
import { asyncExecShell, cleanupDockerStorage, createRemoteEngineConfiguration, decrypt, encrypt, executeDockerCmd, executeSSHCmd, generateDatabaseConfiguration, getDomain, isDev, listSettings, prisma, startTraefikProxy, startTraefikTCPProxy, version } from './lib/common';
import { asyncExecShell, cleanupDockerStorage, createRemoteEngineConfiguration, decrypt, encrypt, executeDockerCmd, executeSSHCmd, generateDatabaseConfiguration, isDev, listSettings, prisma, startTraefikProxy, startTraefikTCPProxy, version } from './lib/common';
import { scheduler } from './lib/scheduler';
import { compareVersions } from 'compare-versions';
import Graceful from '@ladjs/graceful'
@@ -18,8 +19,7 @@ import { verifyRemoteDockerEngineFn } from './routes/api/v1/destinations/handler
import { checkContainer } from './lib/docker';
import { migrateServicesToNewTemplate } from './lib';
import { refreshTags, refreshTemplates } from './routes/api/v1/handlers';
import { realtime } from './routes/realtime';
import cuid from 'cuid';
declare module 'fastify' {
interface FastifyInstance {
config: {
@@ -109,23 +109,12 @@ const host = '0.0.0.0';
});
fastify.register(cookie)
fastify.register(cors);
fastify.register(websocket, {
options: {
clientTracking: true,
verifyClient: async (info, next) => {
try {
const token = info.req.headers?.cookie.split('; ').find((cookie) => cookie.startsWith('token')).split('=')[1];
if (!token) {
return next(false)
}
fastify.jwt.verify(token)
} catch (error) {
return next(false)
}
next(true)
}
fastify.register(socketIO, {
cors: {
origin: "http://localhost:3000"
}
})
// To detect allowed origins
// fastify.addHook('onRequest', async (request, reply) => {
// let allowedList = ['coolify:3000'];
@@ -148,20 +137,8 @@ const host = '0.0.0.0';
try {
fastify.decorate('wssend', function (data: any) {
fastify.websocketServer.clients.forEach((client) => {
client.send(JSON.stringify(data));
})
})
fastify.register(async function (fastify) {
fastify.get('/realtime', { websocket: true }, (connection) => {
// connection.socket.on('message', message => {
// realtime(fastify, connection, message)
// })
})
})
await fastify.listen({ port, host })
await socketIOServer(fastify)
console.log(`Coolify's API is listening on ${host}:${port}`);
await migrateServicesToNewTemplate()

View File

@@ -146,18 +146,18 @@ export async function startService(request: FastifyRequest<ServiceStartStop>, fa
}
async function startServiceContainers(fastify, id, teamId, dockerId, composeFileDestination) {
try {
fastify.wssend({ teamId, type: 'service', id, message: 'Pulling images...' })
fastify.io.to(teamId).emit(`start-service`, { serviceId: id, state: 'Pulling images...' })
await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} pull` })
} catch (error) { }
fastify.wssend({ teamId, type: 'service', id, message: 'Building...' })
fastify.io.to(teamId).emit(`start-service`, { serviceId: id, state: 'Building images...' })
await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} build --no-cache` })
fastify.wssend({ teamId, type: 'service', id, message: 'Creating containers...' })
fastify.io.to(teamId).emit(`start-service`, { serviceId: id, state: 'Creating containers...' })
await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} create` })
fastify.wssend({ teamId, type: 'service', id, message: 'Starting containers...' })
fastify.io.to(teamId).emit(`start-service`, { serviceId: id, state: 'Starting containers...' })
await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} start` })
await asyncSleep(1000);
await executeDockerCmd({ dockerId, command: `docker compose -f ${composeFileDestination} up -d` })
fastify.wssend({ teamId, type: 'service', id, message: 'ending' })
fastify.io.to(teamId).emit(`start-service`, { serviceId: id, state: 0 })
}
export async function migrateAppwriteDB(request: FastifyRequest<OnlyId>, reply: FastifyReply) {
try {

View File

@@ -0,0 +1,29 @@
export default async (fastify) => {
fastify.io.use((socket, next) => {
const { token } = socket.handshake.auth;
if (token && fastify.jwt.verify(token)) {
next();
} else {
return next(new Error("unauthorized event"));
}
});
fastify.io.on('connection', (socket: any) => {
const { token } = socket.handshake.auth;
const { teamId } = fastify.jwt.decode(token);
socket.join(teamId);
console.info('Socket connected!', socket.id)
console.info('Socket joined team!', teamId)
socket.on('message', (message) => {
console.log(message)
})
socket.on('error', (err) => {
console.log(err)
})
})
// fastify.io.on("error", (err) => {
// if (err && err.message === "unauthorized event") {
// fastify.io.disconnect();
// }
// });
}

View File

@@ -1,7 +0,0 @@
export function realtime(fastify, connection, message) {
const { socket } = connection
const data = JSON.parse(message);
if (data.type === 'subscribe') {
socket.send(JSON.stringify({ type: 'subscribe', message: 'pong' }))
}
}