Skip to content

Commit

Permalink
ajuste de compatibilidade com o worker - #130
Browse files Browse the repository at this point in the history
  • Loading branch information
jrCleber committed Jun 5, 2024
1 parent 6e130ab commit 9e6ffd2
Show file tree
Hide file tree
Showing 9 changed files with 66 additions and 123 deletions.
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"dayjs": "^1.11.11",
"dotenv": "^16.3.1",
"eventemitter2": "^6.4.9",
"express": "^4.18.2",
"express": "^4.19.2",
"express-async-errors": "^3.1.1",
"express-session": "^1.17.3",
"hbs": "^4.2.0",
Expand All @@ -69,7 +69,6 @@
"pino-pretty": "^11.0.0",
"qrcode": "^1.5.1",
"qrcode-terminal": "^0.12.0",
"redis": "^4.6.14",
"uuid": "^9.0.0",
"yamljs": "^0.3.0"
},
Expand All @@ -96,6 +95,6 @@
"prettier": "^3.1.0",
"prisma": "^5.14.0",
"ts-node-dev": "^2.0.0",
"typescript": "^5.3.2"
"typescript": "^5.4.5"
}
}
21 changes: 11 additions & 10 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ import express, {
import { Logger } from './config/logger.config';
import { S3Service } from './integrations/minio/s3.service';
import { Repository } from './repository/repository.service';
import { RedisCache } from './cache/redis';
import { ConfigService } from './config/env.config';
import { TypebotService } from './integrations/typebot/typebot.service';
import { eventEmitter } from './config/event.config';
Expand Down Expand Up @@ -73,6 +72,7 @@ import { JwtGuard } from './guards/auth.guard';
import { ErrorMiddle } from './middle/error.middle';
import 'express-async-errors';
import { docsRouter } from './config/scala.config';
import { ProviderFiles } from './provider/sessions';

export function describeRoutes(
rootPath: string,
Expand All @@ -95,6 +95,7 @@ export function describeRoutes(
export enum HttpStatus {
OK = 200,
CREATED = 201,
NO_CONTENT = 202,
NOT_FOUND = 404,
FORBIDDEN = 403,
BAD_REQUEST = 400,
Expand All @@ -109,19 +110,19 @@ export async function AppModule(context: Map<string, any>) {

const logger = new Logger(configService, 'APP MODULE');

const redisCache = new RedisCache(configService);
logger.info('Cache:Redis - ON');
await redisCache.onModuleInit();
const providerFiles = new ProviderFiles(configService);
await providerFiles.onModuleInit();
logger.info('Provider:Files - ON');

const repository = new Repository(configService);
logger.info('Repository - ON');
await repository.onModuleInit();
logger.info('Repository - ON');

const waMonitor = new WAMonitoringService(
eventEmitter,
configService,
repository,
redisCache,
providerFiles,
);

logger.info('WAMonitoringService - ON');
Expand All @@ -134,7 +135,7 @@ export async function AppModule(context: Map<string, any>) {
async (req: Request, res: Response, next: NextFunction) =>
await new JwtGuard(configService).canActivate(req, res, next),
async (req: Request, res: Response, next: NextFunction) =>
await new InstanceGuard(waMonitor, redisCache).canActivate(req, res, next),
await new InstanceGuard(waMonitor, providerFiles).canActivate(req, res, next),
];
logger.info('Middlewares - ON');

Expand All @@ -149,7 +150,7 @@ export async function AppModule(context: Map<string, any>) {
repository,
eventEmitter,
instanceService,
redisCache,
providerFiles,
);
logger.info('InstanceController - ON');

Expand Down Expand Up @@ -221,12 +222,12 @@ export async function AppModule(context: Map<string, any>) {

app['close'] = async () => {
await repository.onModuleDestroy();
await redisCache.onModuleDestroy();
await providerFiles.onModuleDestroy();
};

context.set('app', app);
context.set('module:logger', logger);
context.set('module:repository', repository);
context.set('module:redisCache', redisCache);
context.set('module:redisCache', providerFiles);
context.set('module:config', configService);
}
52 changes: 0 additions & 52 deletions src/cache/redis.ts

This file was deleted.

16 changes: 8 additions & 8 deletions src/config/env.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,10 @@ export type Database = {
DB_OPTIONS: DBOptions;
};

export type Redis = {
export type ProviderSession = {
ENABLED: boolean;
URI: string;
PREFIX_KEY: string;
HOST: string;
PORT: string;
};

export type QrCode = {
Expand All @@ -111,7 +111,7 @@ export interface Env {
SERVER: HttpServer;
STORE: StoreConf;
DATABASE: Database;
REDIS: Redis;
PROVIDER: ProviderSession;
LOG: Log;
INSTANCE_EXPIRATION_TIME: InstanceExpirationTime;
GLOBAL_WEBHOOK: GlobalWebhook;
Expand Down Expand Up @@ -176,10 +176,10 @@ export class ConfigService {
LOGS: process.env?.DATABASE_SAVE_LOGS === 'true',
},
},
REDIS: {
ENABLED: process.env?.REDIS_ENABLED === 'true',
URI: process.env.REDIS_URI,
PREFIX_KEY: process.env?.REDIS_PREFIX || 'codechat_v1',
PROVIDER: {
ENABLED: process.env?.PROVIDER_ENABLED === 'true',
HOST: process.env.PROVIDER_HOST,
PORT: process.env?.PROVIDER_PORT || '5656',
},
LOG: {
LEVEL: process.env?.LOG_LEVEL.split('|') as LogLevel[],
Expand Down
16 changes: 8 additions & 8 deletions src/guards/instance.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,22 @@ import { INSTANCE_DIR } from '../config/path.config';
import { BadRequestException, ForbiddenException } from '../exceptions';
import { InstanceDto } from '../whatsapp/dto/instance.dto';
import { WAMonitoringService } from '../whatsapp/services/monitor.service';
import { RedisCache } from '../cache/redis';
import 'express-async-errors';
import { ProviderFiles } from '../provider/sessions';

async function fetchInstanceFromCache(
instanceName: string,
waMonitor: WAMonitoringService,
redisCache: RedisCache,
providerFiles: ProviderFiles,
) {
try {
const exists = !!waMonitor.waInstances.get(instanceName);
if (exists) {
return exists;
}
if (redisCache?.isConnected) {
const keyExists = await redisCache.keys('*');
return keyExists[0]?.includes(instanceName);
if (providerFiles.isEnabled) {
const [keyExists] = await providerFiles.allInstances();
return keyExists?.data.includes(instanceName);
}

return existsSync(join(INSTANCE_DIR, instanceName));
Expand All @@ -76,7 +76,7 @@ async function fetchInstanceFromCache(
export class InstanceGuard {
constructor(
private readonly waMonitor: WAMonitoringService,
private readonly redisCache: RedisCache,
private readonly providerFiles: ProviderFiles,
) {}
async canActivate(req: Request, _: Response, next: NextFunction) {
if (req.originalUrl.includes('/instance/create')) {
Expand All @@ -85,7 +85,7 @@ export class InstanceGuard {
await fetchInstanceFromCache(
instance.instanceName,
this.waMonitor,
this.redisCache,
this.providerFiles,
)
) {
throw new ForbiddenException(
Expand Down Expand Up @@ -118,7 +118,7 @@ export class InstanceGuard {
const fetch = await fetchInstanceFromCache(
param.instanceName,
this.waMonitor,
this.redisCache,
this.providerFiles,
);

if (!fetch) {
Expand Down
6 changes: 3 additions & 3 deletions src/whatsapp/controllers/instance.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ import { Repository } from '../../repository/repository.service';
import { InstanceService, OldToken } from '../services/instance.service';
import { WAStartupService } from '../services/whatsapp.service';
import { isString } from 'class-validator';
import { RedisCache } from '../../cache/redis';
import { ProviderFiles } from '../../provider/sessions';

export class InstanceController {
constructor(
Expand All @@ -63,7 +63,7 @@ export class InstanceController {
private readonly repository: Repository,
private readonly eventEmitter: EventEmitter2,
private readonly instanceService: InstanceService,
private readonly redisCache: RedisCache,
private readonly providerFiles: ProviderFiles,
) {}

private readonly logger = new Logger(this.configService, InstanceController.name);
Expand Down Expand Up @@ -119,7 +119,7 @@ export class InstanceController {
this.configService,
this.eventEmitter,
this.repository,
this.redisCache,
this.providerFiles,
);
await instance.setInstanceName(instanceName);
this.waMonitor.waInstances.set(instance.instanceName, instance);
Expand Down
38 changes: 20 additions & 18 deletions src/whatsapp/services/monitor.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,32 +47,34 @@ import {
ConfigService,
Database,
InstanceExpirationTime,
Redis,
ProviderSession,
} from '../../config/env.config';
import { Repository } from '../../repository/repository.service';
import { RedisCache } from '../../cache/redis';
import { Instance } from '@prisma/client';
import { ProviderFiles } from '../../provider/sessions';

export class WAMonitoringService {
constructor(
private readonly eventEmitter: EventEmitter2,
private readonly configService: ConfigService,
private readonly repository: Repository,
private readonly redisCache: RedisCache,
private readonly providerFiles: ProviderFiles,
) {
this.removeInstance();
this.noConnection();

Object.assign(this.db, configService.get<Database>('DATABASE'));
Object.assign(this.redis, configService.get<Redis>('REDIS'));
}

private readonly db: Partial<Database> = {};
private readonly redis: Partial<Redis> = {};

private readonly logger = new Logger(this.configService, WAMonitoringService.name);
public readonly waInstances = new Map<string, WAStartupService>();

private readonly providerSession = Object.freeze(
this.configService.get<ProviderSession>('PROVIDER'),
);

public delInstanceTime(instance: string) {
const time = this.configService.get<InstanceExpirationTime>(
'INSTANCE_EXPIRATION_TIME',
Expand All @@ -90,12 +92,12 @@ export class WAMonitoringService {
}
}

private async cleaningUp({ name, id }: Instance) {
private async cleaningUp({ name }: Instance) {
this.waInstances.get(name)?.client?.ev.removeAllListeners('connection.update');
this.waInstances.get(name)?.client?.ev.flush();
this.waInstances.delete(name);
if (this.redis?.ENABLED) {
await this.redisCache.del(`${id}:${name}`);
if (this.providerSession?.ENABLED) {
await this.providerFiles.removeSession(name);
} else {
rmSync(join(INSTANCE_DIR, name), { recursive: true, force: true });
}
Expand All @@ -120,22 +122,20 @@ export class WAMonitoringService {
this.configService,
this.eventEmitter,
this.repository,
this.redisCache,
this.providerFiles,
);
await init.setInstanceName(name);
await init.connectToWhatsapp();
this.waInstances.set(name, init);
};

try {
if (this.redis.ENABLED) {
const keys = await this.redisCache.keys('*');
if (keys?.length > 0) {
keys.forEach(async (key) => {
const [prefix, id, name] = key.split(':');
await set(name);
});
}
if (this.providerSession.ENABLED) {
const [instances] = await this.providerFiles.allInstances();
instances.data.forEach(async (name: string) => {
await set(name);
});

return;
}

Expand All @@ -161,7 +161,9 @@ export class WAMonitoringService {
private removeInstance() {
this.eventEmitter.on('remove.instance', async (instance: Instance) => {
try {
await this.waInstances.get(instance.name)?.client?.logout();
if (!instance?.name) {
return;
}
this.waInstances
.get(instance.name)
?.client?.ev.removeAllListeners('connection.update');
Expand Down
Loading

0 comments on commit 9e6ffd2

Please sign in to comment.