Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(storage): re-probe S3 after a boot-time fallback and warn while degraded (#945)
Yudhi Armyndharisba5bc30d41ea
diff --git a/.env.example b/.env.exampleindex e3ee2f1d6..d2509bda3 100644--- a/.env.example+++ b/.env.example@@ -294,6 +294,9 @@ WEBHOOK_SSRF_PROTECT=true# STORAGE_IMPORT_MAX_BYTES=209715200 # per-entry cap for a tar.gz import; aborts on overflow (default 200 MiB)# STORAGE_IMPORT_MAX_ENTRIES=100000 # max entries in an import archive; aborts beyond this (default 100000)# STORAGE_EXPORT_TTL_MS=3600000 # auto-delete an export archive after this long (default 1h)+# How often an S3-configured service re-probes a bucket that was unreachable at boot (media storage is+# degraded to the local fallback dir until it recovers; writes return to S3 automatically).+# S3_REPROBE_INTERVAL_MS=60000 # default 60s# =============================================================================# RATE LIMITING (all TTLs are in MILLISECONDS)diff --git a/src/common/storage/storage.service.s3-reprobe.spec.ts b/src/common/storage/storage.service.s3-reprobe.spec.tsnew file mode 100644index 000000000..95defaaef--- /dev/null+++ b/src/common/storage/storage.service.s3-reprobe.spec.ts@@ -0,0 +1,221 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { Readable } from 'stream';+import { ConfigService } from '@nestjs/config';++// `archiver` v8 ships ESM-only, which ts-jest can't parse transitively. These tests never touch the+// export path (archiver's only consumer), so a lightweight stub suffices — same approach as the+// other storage specs. Must run before importing StorageService.+jest.mock('archiver', () => ({ default: jest.fn() }));++// Mock the AWS SDK so no real network call is made. Each test drives `mockSend`: HeadBucket probes+// (boot + re-probe) and GetObject reads are distinguished by the mocked command constructors.+const mockSend = jest.fn();+jest.mock('@aws-sdk/client-s3', () => {+ const S3Client = jest.fn().mockImplementation(() => ({ send: mockSend }));+ return {+ S3Client,+ HeadBucketCommand: jest.fn(),+ CreateBucketCommand: jest.fn(),+ ListObjectsV2Command: jest.fn(),+ GetObjectCommand: jest.fn(),+ PutObjectCommand: jest.fn(),+ DeleteObjectCommand: jest.fn(),+ };+});++import { GetObjectCommand } from '@aws-sdk/client-s3';+import { DEFAULT_S3_REPROBE_INTERVAL_MS, StorageService } from './storage.service';++const ENV_KEYS = [+ 'S3_ENDPOINT',+ 'S3_ACCESS_KEY_ID',+ 'S3_SECRET_ACCESS_KEY',+ 'S3_REGION',+ 'S3_BUCKET',+ 'S3_ACCESS_KEY',+ 'S3_SECRET_KEY',+ 'S3_REPROBE_INTERVAL_MS',+];++/** Let fire-and-forget promises (boot HeadBucket, timer-tick probes) settle before asserting. */+async function flush(): Promise<void> {+ for (let i = 0; i < 10; i++) await Promise.resolve();+}++function s3Error(name: string): Error {+ return Object.assign(new Error(name), { name });+}++describe('StorageService S3 re-probe and recovery', () => {+ let tmpRoot: string;+ let localPath: string;++ beforeEach(() => {+ jest.useFakeTimers();+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-s3-reprobe-'));+ localPath = path.join(tmpRoot, 'media');+ mockSend.mockReset();+ for (const key of ENV_KEYS) delete process.env[key];+ });++ afterEach(() => {+ jest.useRealTimers();+ fs.rmSync(tmpRoot, { recursive: true, force: true });+ });++ function makeConfig(): ConfigService {+ return {+ get: (key: string) => {+ if (key === 'storage.type') return 's3';+ if (key === 'storage.localPath') return localPath;+ if (key === 'storage.s3') return { accessKeyId: 'k', secretAccessKey: 's', region: 'us-east-1' };+ return undefined;+ },+ } as unknown as ConfigService;+ }++ function warnSpyOf(svc: StorageService): jest.SpyInstance {+ const logger = (svc as unknown as { logger: { warn: (...args: unknown[]) => void } }).logger;+ return jest.spyOn(logger, 'warn').mockImplementation(() => undefined);+ }++ it('falls back to local with a WARN when S3 is down at boot', async () => {+ mockSend.mockRejectedValue(s3Error('NetworkingError'));+ const svc = new StorageService(makeConfig());+ const warn = warnSpyOf(svc);+ await flush();++ expect(svc.isS3Available()).toBe(false);+ expect(svc.getCurrentStorageType()).toBe('s3');+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('degraded'));+ });++ it('keeps WARNing once per re-probe interval while S3 stays down (rate-limited by the interval)', async () => {+ mockSend.mockRejectedValue(s3Error('NetworkingError'));+ const svc = new StorageService(makeConfig());+ const warn = warnSpyOf(svc);+ await flush();+ expect(warn).toHaveBeenCalledTimes(1); // boot fallback++ await jest.advanceTimersByTimeAsync(DEFAULT_S3_REPROBE_INTERVAL_MS);+ expect(warn).toHaveBeenCalledTimes(2);+ await jest.advanceTimersByTimeAsync(DEFAULT_S3_REPROBE_INTERVAL_MS);+ expect(warn).toHaveBeenCalledTimes(3);+ expect(svc.isS3Available()).toBe(false);+ });++ it('recovers to S3 via the periodic probe (no dashboard poll) and stops probing afterwards', async () => {+ mockSend.mockRejectedValueOnce(s3Error('NetworkingError')); // boot probe fails+ const svc = new StorageService(makeConfig());+ const warn = warnSpyOf(svc);+ await flush();+ expect(svc.isS3Available()).toBe(false);++ mockSend.mockResolvedValue({}); // S3 is back+ await jest.advanceTimersByTimeAsync(DEFAULT_S3_REPROBE_INTERVAL_MS);++ expect(svc.isS3Available()).toBe(true);+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('recovered'));++ // Timer stops after recovery: no further probes, and availability never flips back on its own.+ mockSend.mockClear();+ mockSend.mockRejectedValue(s3Error('NetworkingError'));+ await jest.advanceTimersByTimeAsync(DEFAULT_S3_REPROBE_INTERVAL_MS * 5);+ expect(mockSend).not.toHaveBeenCalled();+ expect(svc.isS3Available()).toBe(true);+ });++ it('never transitions true→false: an S3-healthy boot ignores later transient probe failures', async () => {+ mockSend.mockResolvedValue({}); // boot probe succeeds+ const svc = new StorageService(makeConfig());+ await flush();+ expect(svc.isS3Available()).toBe(true);++ mockSend.mockClear();+ mockSend.mockRejectedValue(s3Error('NetworkingError'));+ await jest.advanceTimersByTimeAsync(DEFAULT_S3_REPROBE_INTERVAL_MS * 3);++ expect(mockSend).not.toHaveBeenCalled(); // no re-probe of a healthy backend+ expect(svc.isS3Available()).toBe(true);+ });++ it('honors S3_REPROBE_INTERVAL_MS for the periodic probe', async () => {+ process.env.S3_REPROBE_INTERVAL_MS = '5000';+ mockSend.mockRejectedValue(s3Error('NetworkingError'));+ new StorageService(makeConfig());+ await flush();+ expect(mockSend).toHaveBeenCalledTimes(1); // boot HeadBucket++ await jest.advanceTimersByTimeAsync(4999);+ expect(mockSend).toHaveBeenCalledTimes(1);+ await jest.advanceTimersByTimeAsync(1);+ expect(mockSend).toHaveBeenCalledTimes(2); // first scheduled re-probe+ });++ it('uses the 60s default when S3_REPROBE_INTERVAL_MS is unset or garbage', async () => {+ process.env.S3_REPROBE_INTERVAL_MS = 'not-a-number';+ mockSend.mockRejectedValue(s3Error('NetworkingError'));+ new StorageService(makeConfig());+ await flush();+ expect(mockSend).toHaveBeenCalledTimes(1);++ await jest.advanceTimersByTimeAsync(DEFAULT_S3_REPROBE_INTERVAL_MS - 1);+ expect(mockSend).toHaveBeenCalledTimes(1);+ await jest.advanceTimersByTimeAsync(1);+ expect(mockSend).toHaveBeenCalledTimes(2);+ });++ it('reads a missing S3 object through from the local fallback dir (media written during the outage)', async () => {+ mockSend.mockImplementation((cmd: unknown) => {+ if (cmd instanceof GetObjectCommand) return Promise.reject(s3Error('NoSuchKey'));+ return Promise.resolve({}); // HeadBucket etc.+ });+ const svc = new StorageService(makeConfig());+ await flush();+ expect(svc.isS3Available()).toBe(true);++ // Simulate gap media: written to the local fallback dir while S3 was down, never uploaded.+ fs.mkdirSync(path.join(localPath, 'sub'), { recursive: true });+ fs.writeFileSync(path.join(localPath, 'sub/gap.bin'), 'gap-media');++ const data = await svc.getFile('sub/gap.bin');+ expect(data.toString()).toBe('gap-media');+ });++ it('surfaces the original NoSuchKey when neither S3 nor the local fallback has the object', async () => {+ mockSend.mockImplementation((cmd: unknown) => {+ if (cmd instanceof GetObjectCommand) return Promise.reject(s3Error('NoSuchKey'));+ return Promise.resolve({});+ });+ const svc = new StorageService(makeConfig());+ await flush();++ await expect(svc.getFile('missing.bin')).rejects.toThrow('NoSuchKey');+ });++ it('does not read through on non-NoSuchKey S3 errors', async () => {+ mockSend.mockImplementation((cmd: unknown) => {+ if (cmd instanceof GetObjectCommand) return Promise.reject(s3Error('AccessDenied'));+ return Promise.resolve({});+ });+ const svc = new StorageService(makeConfig());+ await flush();+ fs.writeFileSync(path.join(localPath, 'secret.bin'), 'local-copy');++ await expect(svc.getFile('secret.bin')).rejects.toThrow('AccessDenied');+ });++ it('still serves objects straight from S3 when they exist there', async () => {+ mockSend.mockImplementation((cmd: unknown) => {+ if (cmd instanceof GetObjectCommand) return Promise.resolve({ Body: Readable.from([Buffer.from('from-s3')]) });+ return Promise.resolve({});+ });+ const svc = new StorageService(makeConfig());+ await flush();++ const data = await svc.getFile('present.bin');+ expect(data.toString()).toBe('from-s3');+ });+});diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.tsindex 2c5e5131e..cad7611ea 100644--- a/src/common/storage/storage.service.ts+++ b/src/common/storage/storage.service.ts@@ -1,4 +1,4 @@-import { Injectable } from '@nestjs/common';+import { Injectable, OnModuleDestroy } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import * as fs from 'fs';import * as path from 'path';@@ -34,6 +34,8 @@ const DEFAULT_IMPORT_MAX_ENTRIES = 100_000;const DEFAULT_LIST_MAX_FILES = 100_000;/** Max directory depth a local traversal descends. Prevents a pathological tree from running unbounded. */const LOCAL_TRAVERSAL_MAX_DEPTH = 20;+/** How often an S3-configured service re-probes a bucket that was unreachable at boot. */+export const DEFAULT_S3_REPROBE_INTERVAL_MS = 60_000;function positiveIntFromEnv(name: string, fallback: number): number {const parsed = Number.parseInt(process.env[name] ?? '', 10);@@ -41,13 +43,15 @@ function positiveIntFromEnv(name: string, fallback: number): number {}@Injectable()-export class StorageService {+export class StorageService implements OnModuleDestroy {private readonly logger = createLogger('StorageService');private readonly storageType: string;private readonly localPath: string;private s3Client: S3Client | null = null;private s3Bucket = 'openwa';private s3Available = false;+ private s3ReprobeTimer: NodeJS.Timeout | null = null;+ private readonly s3ReprobeIntervalMs = positiveIntFromEnv('S3_REPROBE_INTERVAL_MS', DEFAULT_S3_REPROBE_INTERVAL_MS);constructor(private readonly configService: ConfigService) {this.storageType = this.configService.get<string>('storage.type') || 'local';@@ -80,6 +84,7 @@ export class StorageService {});this.s3Bucket = process.env.S3_BUCKET || s3Config.bucket || 'openwa';void this.initializeS3Bucket();+ this.startS3Reprobe();}}@@ -89,6 +94,10 @@ export class StorageService {}}+ onModuleDestroy(): void {+ this.clearS3Reprobe();+ }+private async initializeS3Bucket(): Promise<void> {if (!this.s3Client) return;@@ -106,10 +115,46 @@ export class StorageService {this.logger.log(`Created S3 bucket '${this.s3Bucket}'`);} catch (createError) {this.logger.error('Failed to create S3 bucket', String(createError));+ this.warnLocalFallback();}} else {this.logger.error('S3 bucket check failed', String(error));+ this.warnLocalFallback();+ }+ }+ }++ private warnLocalFallback(): void {+ this.logger.warn(+ `S3 bucket '${this.s3Bucket}' is unreachable — media storage degraded, using the local fallback dir ` ++ `'${this.localPath}'. Re-probing every ${this.s3ReprobeIntervalMs}ms; writes return to S3 once it recovers.`,+ );+ }++ /**+ * Periodically re-probe S3 while the effective backend is the local fallback (S3 was unreachable at+ * boot). Recovery is one-way: availability only ever transitions false→true here, and once S3 is+ * back the timer stops — a session already on S3 is never dropped to local by a transient error+ * without an explicit re-evaluation.+ */+ private startS3Reprobe(): void {+ this.s3ReprobeTimer = setInterval(() => {+ if (this.s3Available) {+ this.clearS3Reprobe();+ return;}+ void this.refreshS3Availability().then(available => {+ if (!available) this.warnLocalFallback();+ });+ }, this.s3ReprobeIntervalMs);+ // Don't keep the process alive for a probe; shutdown clears it via onModuleDestroy.+ this.s3ReprobeTimer.unref();+ }++ private clearS3Reprobe(): void {+ if (this.s3ReprobeTimer) {+ clearInterval(this.s3ReprobeTimer);+ this.s3ReprobeTimer = null;}}@@ -131,8 +176,8 @@ export class StorageService {/*** Re-probe S3/MinIO reachability when it's currently marked unavailable — e.g. a bundled MinIO that* came up AFTER the app booted (the init HeadBucket raced and latched false). Throttled (10s) and- * in-flight-deduped so the status endpoint can call it on every poll cheaply. Once available it- * stays available (no need to re-probe a healthy backend here).+ * in-flight-deduped so the status endpoint and the periodic re-probe can call it cheaply. Once+ * available it stays available (no need to re-probe a healthy backend here).*/async refreshS3Availability(): Promise<boolean> {if (this.storageType !== 's3' || !this.s3Client || this.s3Available) return this.s3Available;@@ -147,7 +192,13 @@ export class StorageService {try {await this.s3Client!.send(new HeadBucketCommand({ Bucket: this.s3Bucket }));this.s3Available = true;- this.logger.log(`S3 bucket '${this.s3Bucket}' is now reachable`);+ // WARN (not log): the degraded window matters — media written to the local fallback dir while+ // S3 was down stays local-only; reads for those keys keep working via the NoSuchKey+ // read-through in getS3File, but the operator should reconcile/acknowledge the gap.+ this.logger.warn(+ `S3 bucket '${this.s3Bucket}' recovered — media storage back on S3. Files written to the local ` ++ `fallback dir '${this.localPath}' during the outage remain there (still readable via read-through).`,+ );} catch {// still unreachable — leave s3Available false; a later poll retries after the throttle window} finally {@@ -506,12 +557,28 @@ export class StorageService {private async getS3File(filePath: string): Promise<Buffer> {if (!this.s3Client) throw new Error('S3 client not initialized');- const response = await this.s3Client.send(- new GetObjectCommand({- Bucket: this.s3Bucket,- Key: `media/${filePath}`,- }),- );+ let response;+ try {+ response = await this.s3Client.send(+ new GetObjectCommand({+ Bucket: this.s3Bucket,+ Key: `media/${filePath}`,+ }),+ );+ } catch (error: unknown) {+ // Read-through: media written while S3 was down lives only in the local fallback dir, so after+ // recovery a plain S3 read would split-brain (NoSuchKey even though the app served the file+ // fine during the outage). Fall through to the local copy; if there is none, surface the+ // original S3 error so "not found" semantics are unchanged.+ if ((error as { name?: string }).name !== 'NoSuchKey') throw error;+ try {+ const local = await this.getLocalFile(filePath);+ this.logger.debug(`Served '${filePath}' from the local fallback dir (not yet in S3)`);+ return local;+ } catch {+ throw error;+ }+ }if (!response.Body) throw new Error('Empty response body');