Amal Jose commited on
Commit ·
446bc13
1
Parent(s): 46f60fe
added new redis emitter
Browse filesFiles changed (13)
- ecosystem.config.cjs+1-1
- src/app.ts+3-1
- src/config/env.config.ts+1
- src/config/redis.config.ts+2
- src/controllers/serverDataOnlyController.ts+5-6
- src/events/deploymentEmitter.ts+65-8
- src/events/handlers/deployment.handler.ts-1
- src/events/types/Emitters.tsAdded+18
- src/routes/base.route.ts-2
- src/server.ts+3-3
- src/services/deployment.service.ts+17-3
- src/services/logs.service.ts+1-1
- src/services/project.service.ts+9-2
3 unmodified lines456789103 unmodified linesscript: "./dist/server.js",instances: 1,exec_mode: "cluster",max_memory_restart: "4G",3 unmodified lines456789103 unmodified linesscript: "./dist/server.js",instances: 3,exec_mode: "cluster",max_memory_restart: "4G",
26 unmodified lines2728293031323326 unmodified linesapp.use(cookieParser());app.use(helmet());app.use(passport.initialize());app.use(morgan("tiny"));app.set("trust proxy", 1);26 unmodified lines27282930313233343526 unmodified linesapp.use(cookieParser());app.use(helmet());app.use(passport.initialize());morgan.token("app-id", () => String(process.pid));app.use(morgan(":app-id :method :url :status :response-time ms"));app.set("trust proxy", 1);
55 unmodified lines56575859606155 unmodified linesEMAIL_SENDER_EMAIL: z.email(),NOTIFY_EVENTS_API_KEY: z.string(),});function validateEnv() {try {55 unmodified lines5657585960616255 unmodified linesEMAIL_SENDER_EMAIL: z.email(),NOTIFY_EVENTS_API_KEY: z.string(),USE_REDIS_EMITTER: z.stringbool("Please provide 'true' or 'false' for ENV :- USE_REDIS_EMITTER").optional().default(false),});function validateEnv() {try {
123import { ENVS } from "@/config/env.config.js";import { Redis } from "ioredis";export const redisClient = new Redis((ENVS.REDIS_URL as string) || "");12345import { ENVS } from "@/config/env.config.js";import { Redis } from "ioredis";export const redisClient = new Redis((ENVS.REDIS_URL as string) || "");export const redisEmitterPublisher = new Redis((ENVS.REDIS_URL as string) || "");export const redisEmitterSubscriber = redisClient;
4 unmodified lines56789101112131415161718194 unmodified linesimport { NextFunction, Request, Response } from "express";export const getServerNotifications = async (req: Request, res: Response, next: NextFunction) => {try {const data = await redisCacheService.get<string>("server-notifications")if (!data) {res.status(200).json({ fromServer: null })return}res.status(200).json({ fromServer: data })} catch (error: any) {console.log(error.message, error)next(new AppError(COMMON_ERRORS.SOMETHING_WENT_WRONG, STATUS_CODES.INTERNAL_SERVER_ERROR, error));}};4 unmodified lines567891011121314151617184 unmodified linesimport { NextFunction, Request, Response } from "express";export const getServerNotifications = async (req: Request, res: Response, next: NextFunction) => {try {const data = await redisCacheService.get<string>("server-notifications");if (!data) {res.status(200).json({ fromServer: null });return;}res.status(200).json({ fromServer: data });} catch (error: any) {console.log(error.message, error);next(new AppError(COMMON_ERRORS.SOMETHING_WENT_WRONG, STATUS_CODES.INTERNAL_SERVER_ERROR, error));}};
12345679 unmodified lines1718192021222324252627282930313233import { EventEmitter } from "events";import { Response, Request } from "express";class DeploymentEmitter extends EventEmitter {onEvent(eventString: string, callback: (log: any) => void) {this.on(eventString, callback);}9 unmodified linesthis.removeAllListeners(eventString);}}export const deploymentEmitter = new DeploymentEmitter();interface SSEClient {deploymentId: string;res: Response;listener: (data: any) => void;errors: number;}class SSEManager {private emitter: DeploymentEmitter;private clients: Map<string, SSEClient>;private interval: NodeJS.Timeout;12345678910119 unmodified lines21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import { redisEmitterPublisher, redisEmitterSubscriber } from "@/config/redis.config.js";import { EventEmitter } from "events";import { Response, Request } from "express";import { Redis } from "ioredis";import { IDeploymentEmitter, SSEClient } from "./types/Emitters.js";import { ENVS } from "@/config/env.config.js";class DeploymentEmitter extends EventEmitter implements IDeploymentEmitter {onEvent(eventString: string, callback: (log: any) => void) {this.on(eventString, callback);}9 unmodified linesthis.removeAllListeners(eventString);}}class RedisDeploymentEmitter implements IDeploymentEmitter {private sub: Redis;private pub: Redis;private localInternalEmitter: EventEmitter;constructor(publisher: Redis, subscriber: Redis) {this.pub = publisher;this.sub = subscriber;this.localInternalEmitter = new EventEmitter();this.start();}private start() {this.sub.on("message", (channel, message) => {try {const parsed = JSON.parse(message);this.localInternalEmitter.emit(channel, parsed);} catch (error) {console.log("Error on Redis message parsing...", channel);}});console.log("Started sub on------------------------");}async onEvent(eventString: string, callback: (log: any) => void) {if (this.localInternalEmitter.listenerCount(eventString) === 0) {await this.sub.subscribe(eventString);}this.localInternalEmitter.on(eventString, callback);}async offEvent(eventString: string, callback: (log: any) => void) {this.localInternalEmitter.off(eventString, callback);if (this.localInternalEmitter.listenerCount(eventString) === 0) {await this.sub.unsubscribe(eventString);}}async emitEvents(eventString: string, log: any, type: string) {const emitData = { type, data: log };const str = JSON.stringify(emitData);await this.pub.publish(eventString, str);}async offAllEvents(eventString: string) {await this.sub.unsubscribe(eventString);this.localInternalEmitter.removeAllListeners(eventString);}setMaxListeners(n: number) {this.localInternalEmitter.setMaxListeners(n);}eventNames() {return this.localInternalEmitter.eventNames();}listeners(name: string | symbol) {return this.localInternalEmitter.listeners(name);}}console.log("Using redis emiter = ", ENVS.USE_REDIS_EMITTER);export const deploymentEmitter = ENVS.USE_REDIS_EMITTER? new RedisDeploymentEmitter(redisEmitterPublisher, redisEmitterSubscriber): new DeploymentEmitter();class SSEManager {private emitter: DeploymentEmitter | RedisDeploymentEmitter;private clients: Map<string, SSEClient>;private interval: NodeJS.Timeout;
105 unmodified lines106107108109110111112105 unmodified linesbreak;}case UpdateTypes.CUSTOM: {updates;await Promise.all([deploymentService.__updateDeployment(projectId, deploymentId, {status: updates.status,105 unmodified lines106107108109110111105 unmodified linesbreak;}case UpdateTypes.CUSTOM: {await Promise.all([deploymentService.__updateDeployment(projectId, deploymentId, {status: updates.status,
123456789101112131415161718import { Response } from "express";
export interface IDeploymentEmitter { onEvent(e: string, cb: (log: any) => void): void | Promise<void>; offEvent(e: string, cb: (log: any) => void): void | Promise<void>; emitEvents(e: string, log: any, type: string): void | Promise<void>; offAllEvents(e: string): void | Promise<void>; setMaxListeners(n: number): void; eventNames(): (string | symbol)[]; listeners(name: string | symbol): Function[];}
export interface SSEClient { deploymentId: string; res: Response; listener: (data: any) => void; errors: number;}6 unmodified lines789101112136 unmodified lines202122232425266 unmodified linesstatus: "ok",service: "lynfera-backend",ip: { reqIp: _req.ip },});return;});6 unmodified lines});});baseRouter.get("/server-notifications", getServerNotifications);export default baseRouter;6 unmodified lines7891011126 unmodified lines1920212223246 unmodified linesstatus: "ok",service: "lynfera-backend",ip: { reqIp: _req.ip },});return;});6 unmodified lines});});baseRouter.get("/server-notifications", getServerNotifications);export default baseRouter;
6 unmodified lines789101112131415166 unmodified linesconst PORT = ENVS.PORT || 8000;const startServer = async () => {console.log("starting.....");if (ENVS.NODE_ENV === "production") {const totalMem = totalmem() / (1024 ** 3);const freeMem = freemem() / (1024 ** 3);const cpuCores = cpus().length;const load = loadavg(); // [1m, 5m, 15m]6 unmodified lines789101112131415166 unmodified linesconst PORT = ENVS.PORT || 8000;const startServer = async () => {console.log("starting.....app id " + process.pid);if (ENVS.NODE_ENV === "production") {const totalMem = totalmem() / 1024 ** 3;const freeMem = freemem() / 1024 ** 3;const cpuCores = cpus().length;const load = loadavg(); // [1m, 5m, 15m]
56 unmodified lines575859606162636465666764 unmodified lines13213313413513613713813914056 unmodified linesthis.githubSvcs = githubSvcs;}async newDeployment(deploymentData: Partial<IDeployment>, userId: string, projectId: string, isRedeploy: boolean): Promise<IDeployment | null> {const canDeploy = await this.userService.userCanDeploy(userId);if (!canDeploy.user) {throw new AppError(USER_ERRORS.NOT_FOUND, STATUS_CODES.NOT_FOUND);}if (!canDeploy.allowed) {throw new AppError(DEPLOYMENT_ERRORS.DAILY_DEPLOYMENT_LIMIT, STATUS_CODES.TOO_MANY_REQUESTS);}64 unmodified linesproject: IProject,installationId?: number,): Promise<{ status: string; reason: string }> {const canDeploy = await this.userService.userCanDeploy(project.user.toString());const correspondindProject = project;if (installationId && canDeploy.user.githubInstallationId && canDeploy.user.githubInstallationId !== installationId) {return { status: "ignored", reason: "installation mismatch" };}56 unmodified lines57585960616263646566676869707172737464 unmodified lines13914014114214314414514614714814915015115215315456 unmodified linesthis.githubSvcs = githubSvcs;}async newDeployment(deploymentData: Partial<IDeployment>, userId: string, projectId: string, isRedeploy: boolean): Promise<IDeployment | null> {const [canDeploy, problems] = await Promise.all([this.userService.userCanDeploy(userId),this.redisCache.get<{ affectedModules: string[] }>("server-notifications"),]);if (problems?.affectedModules?.includes("deployments")) {throw new AppError(DEPLOYMENT_ERRORS.DEPLOY_FAILED + "; Deployments are currently disabled", STATUS_CODES.BAD_REQUEST);}if (!canDeploy.user) {throw new AppError(USER_ERRORS.NOT_FOUND, STATUS_CODES.NOT_FOUND);}if (canDeploy.allowed) {throw new AppError(DEPLOYMENT_ERRORS.DAILY_DEPLOYMENT_LIMIT, STATUS_CODES.TOO_MANY_REQUESTS);}64 unmodified linesproject: IProject,installationId?: number,): Promise<{ status: string; reason: string }> {const [canDeploy, problems] = await Promise.all([this.userService.userCanDeploy(project.user.toString()),this.redisCache.get<{ affectedModules: string[] }>("server-notifications"),]);const correspondindProject = project;if (problems?.affectedModules?.includes("github")) {await this.createNewFailedDeployment(deploymentData, project, DEPLOYMENT_ERRORS.DEPLOY_FAILED + "; Deployments are currently disabled");}if (installationId && canDeploy.user.githubInstallationId && canDeploy.user.githubInstallationId !== installationId) {return { status: "ignored", reason: "installation mismatch" };}
143 unmodified lines144145146147148149150143 unmodified linesasync __saveLogAsBatch(logs: ILogs[]): Promise<void> {// await new Promise((res) => setTimeout(res, 2000))console.log(logs[0].event_id)await this.logsRepository.__insertLogsAsBatch(logs);}143 unmodified lines144145146147148149150143 unmodified linesasync __saveLogAsBatch(logs: ILogs[]): Promise<void> {// await new Promise((res) => setTimeout(res, 2000))console.log(logs[0].event_id);await this.logsRepository.__insertLogsAsBatch(logs);}
67 unmodified lines686970717273747576777867 unmodified linessubdomain: `${generateSlug(2)}-${nanoid(6)}`,};const user = await this.userRepository.findByUserId(userId);if (!user) {throw new AppError(USER_ERRORS.NOT_FOUND, STATUS_CODES.NOT_FOUND);}if (user?.projects > PLANS[user.plan].maxProjects) {throw new AppError(PROJECT_ERRORS.LIMIT_REACHED, STATUS_CODES.FORBIDDEN);}const newProject = await this.projectRepository.createProject(projectData);67 unmodified lines68697071727374757677787980818283848567 unmodified linessubdomain: `${generateSlug(2)}-${nanoid(6)}`,};const [user, problems] = await Promise.all([this.userRepository.findByUserId(userId),this.cacheInvalidator.get<{ affectedModules: string[] }>("server-notifications"),]);if (!user) {throw new AppError(USER_ERRORS.NOT_FOUND, STATUS_CODES.NOT_FOUND);}if (problems?.affectedModules?.includes("projects")) {throw new AppError(PROJECT_ERRORS.CREATE_FAILED + "; Projects creation currently disabled", STATUS_CODES.BAD_REQUEST);}if (user?.projects < PLANS[user.plan].maxProjects) {throw new AppError(PROJECT_ERRORS.LIMIT_REACHED, STATUS_CODES.FORBIDDEN);}const newProject = await this.projectRepository.createProject(projectData);
ecosystem.config.cjs+1-1
src/app.ts+3-1
src/config/env.config.ts+1
src/config/redis.config.ts+2
src/controllers/serverDataOnlyController.ts+5-6
src/events/deploymentEmitter.ts+65-8
src/events/handlers/deployment.handler.ts-1
src/events/types/Emitters.tsAdded+18
src/routes/base.route.ts-2
src/server.ts+3-3
src/services/deployment.service.ts+17-3
src/services/logs.service.ts+1-1
src/services/project.service.ts+9-2