Add list method to AuthRepository and delete temp instances in WAMonitoringService

This commit is contained in:
Judson Cairo 2024-02-07 16:34:26 -03:00
parent 34c53d352a
commit 704701e251
2 changed files with 54 additions and 15 deletions

View File

@ -1,4 +1,4 @@
import { readFileSync } from 'fs'; import { opendirSync, readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { Auth, ConfigService } from '../../config/env.config'; import { Auth, ConfigService } from '../../config/env.config';
@ -64,6 +64,37 @@ export class AuthRepository extends Repository {
} }
} }
public async list(): Promise<AuthRaw[]> {
try {
if (this.dbSettings.ENABLED) {
this.logger.verbose('listing auth in db');
return await this.authModel.find();
}
this.logger.verbose('listing auth in store');
const auths: AuthRaw[] = [];
const openDir = opendirSync(join(AUTH_DIR, this.auth.TYPE), {
encoding: 'utf-8',
});
for await (const dirent of openDir) {
if (dirent.isFile()) {
auths.push(
JSON.parse(
readFileSync(join(AUTH_DIR, this.auth.TYPE, dirent.name), {
encoding: 'utf-8',
}),
),
);
}
}
return auths;
} catch (error) {
return [];
}
}
public async findInstanceNameById(instanceId: string): Promise<string | null> { public async findInstanceNameById(instanceId: string): Promise<string | null> {
try { try {
this.logger.verbose('finding auth by instanceId'); this.logger.verbose('finding auth by instanceId');

View File

@ -2,22 +2,19 @@ import { execSync } from 'child_process';
import EventEmitter2 from 'eventemitter2'; import EventEmitter2 from 'eventemitter2';
import { opendirSync, readdirSync, rmSync } from 'fs'; import { opendirSync, readdirSync, rmSync } from 'fs';
import { Db } from 'mongodb'; import { Db } from 'mongodb';
import { Collection } from 'mongoose';
import { join } from 'path'; import { join } from 'path';
import { Auth, ConfigService, Database, DelInstance, HttpServer, Redis } from '../../config/env.config'; import { Auth, ConfigService, Database, DelInstance, HttpServer, Redis } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config'; import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
import { NotFoundException } from '../../exceptions'; import { NotFoundException } from '../../exceptions';
import { dbserver } from '../../libs/db.connect';
import { RedisCache } from '../../libs/redis.client'; import { RedisCache } from '../../libs/redis.client';
import { import {
AuthModel, AuthModel,
ChamaaiModel, ChamaaiModel,
// ChatModel,
ChatwootModel, ChatwootModel,
// ContactModel, ContactModel,
// MessageModel,
// MessageUpModel,
ProxyModel, ProxyModel,
RabbitmqModel, RabbitmqModel,
SettingsModel, SettingsModel,
@ -41,7 +38,6 @@ export class WAMonitoringService {
this.removeInstance(); this.removeInstance();
this.noConnection(); this.noConnection();
// this.delInstanceFiles();
Object.assign(this.db, configService.get<Database>('DATABASE')); Object.assign(this.db, configService.get<Database>('DATABASE'));
Object.assign(this.redis, configService.get<Redis>('REDIS')); Object.assign(this.redis, configService.get<Redis>('REDIS'));
@ -56,8 +52,6 @@ export class WAMonitoringService {
private dbInstance: Db; private dbInstance: Db;
private dbStore = dbserver;
private readonly logger = new Logger(WAMonitoringService.name); private readonly logger = new Logger(WAMonitoringService.name);
public readonly waInstances: Record<string, WAStartupService> = {}; public readonly waInstances: Record<string, WAStartupService> = {};
@ -326,11 +320,6 @@ export class WAMonitoringService {
this.logger.verbose('cleaning store database instance: ' + instanceName); this.logger.verbose('cleaning store database instance: ' + instanceName);
// await ChatModel.deleteMany({ owner: instanceName });
// await ContactModel.deleteMany({ owner: instanceName });
// await MessageUpModel.deleteMany({ owner: instanceName });
// await MessageModel.deleteMany({ owner: instanceName });
await AuthModel.deleteMany({ _id: instanceName }); await AuthModel.deleteMany({ _id: instanceName });
await WebhookModel.deleteMany({ _id: instanceName }); await WebhookModel.deleteMany({ _id: instanceName });
await ChatwootModel.deleteMany({ _id: instanceName }); await ChatwootModel.deleteMany({ _id: instanceName });
@ -340,6 +329,7 @@ export class WAMonitoringService {
await TypebotModel.deleteMany({ _id: instanceName }); await TypebotModel.deleteMany({ _id: instanceName });
await WebsocketModel.deleteMany({ _id: instanceName }); await WebsocketModel.deleteMany({ _id: instanceName });
await SettingsModel.deleteMany({ _id: instanceName }); await SettingsModel.deleteMany({ _id: instanceName });
await ContactModel.deleteMany({ owner: instanceName });
return; return;
} }
@ -393,7 +383,7 @@ export class WAMonitoringService {
this.logger.verbose('Database enabled'); this.logger.verbose('Database enabled');
await this.repository.dbServer.connect(); await this.repository.dbServer.connect();
const collections: any[] = await this.dbInstance.collections(); const collections: any[] = await this.dbInstance.collections();
await this.deleteTempInstances(collections);
if (collections.length > 0) { if (collections.length > 0) {
this.logger.verbose('Reading collections and setting instances'); this.logger.verbose('Reading collections and setting instances');
await Promise.all(collections.map((coll) => this.setInstance(coll.namespace.replace(/^[\w-]+\./, '')))); await Promise.all(collections.map((coll) => this.setInstance(coll.namespace.replace(/^[\w-]+\./, ''))));
@ -482,4 +472,22 @@ export class WAMonitoringService {
} }
}); });
} }
private async deleteTempInstances(collections: Collection<Document>[]) {
this.logger.verbose('Cleaning up temp instances');
const auths = await this.repository.auth.list();
if (auths.length === 0) {
this.logger.verbose('No temp instances found');
return;
}
let tempInstances = 0;
auths.forEach((auth) => {
if (collections.find((coll) => coll.namespace.replace(/^[\w-]+\./, '') === auth._id)) {
return;
}
tempInstances++;
this.eventEmitter.emit('remove.instance', auth._id, 'inner');
});
this.logger.verbose('Temp instances removed: ' + tempInstances);
}
} }