Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor: remove duplicate Docker orchestration from main.ts

rmyndharisd69a43b4373a
diff --git a/src/app.module.ts b/src/app.module.ts
index ad3394476..68e4da1c9 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -85,6 +85,8 @@ if (process.env.QUEUE_ENABLED === 'true') {
username: configService.get<string>('dataDatabase.username'),
password: configService.get<string>('dataDatabase.password'),
database: 'openwa',
+ retryAttempts: 10,
+ retryDelay: 3000,
extra: {
max: configService.get<number>('dataDatabase.poolSize', 10),
},
diff --git a/src/main.ts b/src/main.ts
index e6042ed4c..79d45a3e2 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -6,7 +6,6 @@ import { AppModule } from './app.module';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as path from 'path';
-import Docker from 'dockerode';
// Configuration loading:
// 1. If data/.env.generated exists, load it (persisted config from dashboard)
@@ -51,117 +50,12 @@ STORAGE_PATH=./data/media
dotenv.config({ path: generatedEnvPath, override: true });
}
-// Pre-bootstrap PostgreSQL container if built-in is enabled
-// This runs BEFORE NestJS starts so TypeORM can connect
-async function preBootstrapPostgres(): Promise<void> {
- if (process.env.POSTGRES_BUILTIN !== 'true') {
- return; // Not using built-in PostgreSQL
- }
-
- console.log('[Pre-Bootstrap] PostgreSQL built-in enabled, ensuring container is ready...');
-
- const docker = new Docker({ socketPath: '/var/run/docker.sock' });
- const containerName = 'openwa-postgres';
- const networkName = 'openwa-network';
-
- try {
- // Check if container exists
- const containers = await docker.listContainers({ all: true });
- const existing = containers.find(c => c.Names.includes(`/${containerName}`));
-
- if (existing) {
- if (existing.State === 'running') {
- console.log('[Pre-Bootstrap] PostgreSQL container already running');
- } else {
- // Start existing container
- const container = docker.getContainer(existing.Id);
- await container.start();
- console.log('[Pre-Bootstrap] Started existing PostgreSQL container');
- }
- } else {
- // Create and start new container
- console.log('[Pre-Bootstrap] Creating PostgreSQL container...');
-
- // Ensure network exists
- const networks = await docker.listNetworks();
- if (!networks.find(n => n.Name === networkName)) {
- await docker.createNetwork({ Name: networkName });
- }
-
- // Ensure volume exists
- const volumes = await docker.listVolumes();
- if (!volumes.Volumes?.find(v => v.Name === 'openwa_postgres-data')) {
- await docker.createVolume({ Name: 'openwa_postgres-data' });
- }
-
- // Create container
- const container = await docker.createContainer({
- name: containerName,
- Image: 'postgres:16-alpine',
- Env: ['POSTGRES_USER=openwa', 'POSTGRES_PASSWORD=openwa', 'POSTGRES_DB=openwa'],
- Labels: {
- 'com.openwa.service': 'database',
- 'com.openwa.builtin': 'true',
- },
- HostConfig: {
- NetworkMode: networkName,
- RestartPolicy: { Name: 'unless-stopped' },
- Binds: ['openwa_postgres-data:/var/lib/postgresql/data'],
- },
- Healthcheck: {
- Test: ['CMD-SHELL', 'pg_isready -U openwa'],
- Interval: 5000000000, // 5s
- Timeout: 3000000000, // 3s
- Retries: 5,
- },
- NetworkingConfig: {
- EndpointsConfig: {
- [networkName]: {
- Aliases: ['postgres', 'openwa-postgres'],
- },
- },
- },
- });
-
- await container.start();
- console.log('[Pre-Bootstrap] PostgreSQL container created and started');
- }
-
- // Wait for PostgreSQL to be healthy (max 60 seconds)
- console.log('[Pre-Bootstrap] Waiting for PostgreSQL to be healthy...');
- const maxWaitMs = 60000;
- const startTime = Date.now();
-
- while (Date.now() - startTime < maxWaitMs) {
- const containerInfo = await docker.getContainer(containerName).inspect();
- const health = containerInfo.State?.Health?.Status;
-
- if (health === 'healthy') {
- console.log('[Pre-Bootstrap] PostgreSQL is healthy and ready!');
- return;
- }
-
- if (health === 'unhealthy') {
- throw new Error('PostgreSQL container became unhealthy');
- }
-
- // Wait 2 seconds before next check
- await new Promise(resolve => setTimeout(resolve, 2000));
- }
-
- throw new Error('PostgreSQL health check timeout after 60s');
- } catch (error) {
- console.error('[Pre-Bootstrap] PostgreSQL orchestration failed:', error);
- throw error;
- }
-}
-
async function bootstrap() {
- // Pre-bootstrap: ensure PostgreSQL is ready before NestJS starts
- await preBootstrapPostgres();
-
const app = await NestFactory.create(AppModule);
+ // Enable shutdown hooks for graceful shutdown
+ app.enableShutdownHooks();
+
// Enhanced Security Headers (Phase 3 Security Audit)
app.use(
helmet({