Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(docker): bound the calls that decide whether Docker is available
Yudhi Armyndharisf80f5373410f
diff --git a/src/modules/docker/docker-unresponsive.spec.ts b/src/modules/docker/docker-unresponsive.spec.tsnew file mode 100644index 000000000..e27e51553--- /dev/null+++ b/src/modules/docker/docker-unresponsive.spec.ts@@ -0,0 +1,43 @@+import * as net from 'net';+import type { AddressInfo } from 'net';+import { DockerService } from './docker.service';++/**+ * dockerode sets no timeout. A daemon or socket proxy that accepts the connection and never answers+ * (a firewall dropping packets, a wedged upstream behind docker-socket-proxy) must read as "Docker not+ * available" rather than hold the boot that awaits the ping.+ */+describe('DockerService against a daemon that never answers', () => {+ const sockets = new Set<net.Socket>();+ let server: net.Server;+ let previousHost: string | undefined;++ beforeEach(async () => {+ previousHost = process.env.DOCKER_HOST;+ server = net.createServer(socket => {+ sockets.add(socket);+ socket.on('data', () => undefined);+ socket.on('close', () => sockets.delete(socket));+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ process.env.DOCKER_HOST = `tcp://127.0.0.1:${(server.address() as AddressInfo).port}`;+ });++ afterEach(async () => {+ if (previousHost === undefined) delete process.env.DOCKER_HOST;+ else process.env.DOCKER_HOST = previousHost;+ for (const socket of sockets) socket.destroy();+ await new Promise<void>(resolve => server.close(() => resolve()));+ });++ it('boots with Docker unavailable once the ping is not answered in time', async () => {+ const service = new DockerService();+ service.callTimeoutMs = 150;++ const started = Date.now();+ await service.onModuleInit();++ expect(Date.now() - started).toBeLessThan(2000);+ expect(service.isDockerAvailable()).toBe(false);+ }, 10_000);+});diff --git a/src/modules/docker/docker.service.ts b/src/modules/docker/docker.service.tsindex 0a44d73c6..53f71b511 100644--- a/src/modules/docker/docker.service.ts+++ b/src/modules/docker/docker.service.ts@@ -27,12 +27,37 @@ interface OrchestrationResult {estimatedTime: number; // Estimated restart time in seconds}+/** How long a reachability or listing call may take before the daemon is read as unavailable. */+const DOCKER_CALL_TIMEOUT_MS = 10_000;+@Injectable()export class DockerService implements OnModuleInit {private readonly logger = createLogger(DockerService.name);private docker: Docker | null = null;private isAvailable = false;private reinitInFlight = false;+ /** Visible for testing. */+ callTimeoutMs = DOCKER_CALL_TIMEOUT_MS;++ /**+ * dockerode sets no timeout, so a daemon or socket proxy that accepts the connection and never+ * answers (a dropped SYN, a wedged upstream) would hold the caller, boot included, until the OS or+ * the proxy gave up. Short calls are bounded here; image pulls and container starts are not.+ */+ private async answered<T>(call: Promise<T>, what: string): Promise<T> {+ let timer: NodeJS.Timeout | undefined;+ const deadline = new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error(`Docker did not answer ${what} within ${this.callTimeoutMs}ms`)),+ this.callTimeoutMs,+ );+ });+ try {+ return await Promise.race([call, deadline]);+ } finally {+ clearTimeout(timer);+ }+ }async onModuleInit() {await this.initializeDocker();@@ -90,7 +115,7 @@ export class DockerService implements OnModuleInit {private async initializeDocker(): Promise<void> {try {this.docker = new Docker(this.buildDockerOptions());- await this.docker.ping();+ await this.answered(this.docker.ping(), 'a ping');this.isAvailable = true;this.logger.log('Docker API connected successfully');} catch (error) {@@ -142,7 +167,7 @@ export class DockerService implements OnModuleInit {}try {- const containers = await this.docker.listContainers({ all: true });+ const containers = await this.answered(this.docker.listContainers({ all: true }), 'a container list');return containers.filter(c => {// Filter by OpenWA labels or name prefix@@ -186,12 +211,15 @@ export class DockerService implements OnModuleInit {}try {- const containers = await this.docker.listContainers({- all: true,- filters: {- label: [`com.openwa.service=${service}`],- },- });+ const containers = await this.answered(+ this.docker.listContainers({+ all: true,+ filters: {+ label: [`com.openwa.service=${service}`],+ },+ }),+ 'a container list',+ );if (containers.length > 0) {return this.docker.getContainer(containers[0].Id);@@ -200,7 +228,7 @@ export class DockerService implements OnModuleInit {// Fallback: try by EXACT name (never a substring — a substring, and especially the empty// string, would resolve an arbitrary container). OpenWA-managed containers are `openwa-<service>`.const target = `openwa-${service}`;- const allContainers = await this.docker.listContainers({ all: true });+ const allContainers = await this.answered(this.docker.listContainers({ all: true }), 'a container list');const match = allContainers.find(c => c.Names?.some(n => n === target || n === `/${target}`));if (match) {@@ -624,7 +652,7 @@ export class DockerService implements OnModuleInit {}try {- const info = (await this.docker.info()) as {+ const info = (await this.answered(this.docker.info(), 'the daemon info')) as {Containers: number;ContainersRunning: number;ContainersPaused: number;