A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
fix: resolve webhook dispatch and CI test hangs
Om Singh Chouhan560bbc6a8ac9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 73d7c6f..736706d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -118,6 +118,7 @@ jobs:name: 🐍 4. Regression Testsneeds: [build]runs-on: ubuntu-latest+ timeout-minutes: 15steps:- name: Checkout repository@@ -134,6 +135,7 @@ jobs:- name: Run Full Regression Test Suiterun: npm test+ timeout-minutes: 10env:NODE_ENV: testYOUPI_MODE: localhostdiff --git a/packages/core/src/__tests__/webhook-engine.test.js b/packages/core/src/__tests__/webhook-engine.test.jsindex d36a1fe..a40b57d 100644--- a/packages/core/src/__tests__/webhook-engine.test.js+++ b/packages/core/src/__tests__/webhook-engine.test.js@@ -53,7 +53,7 @@ describe('Webhook Engine Integration Tests', () => {});await new Promise(resolve => {- receiverServer.listen(0, () => {+ receiverServer.listen(0, '127.0.0.1', () => {receiverPort = receiverServer.address().port;resolve();});@@ -71,7 +71,7 @@ describe('Webhook Engine Integration Tests', () => {slug: 'webhook-store',contactEmail: '[email protected]',contactPhone: '9876543210',- webhookUrl: `http://localhost:${receiverPort}/webhook`,+ webhookUrl: `http://127.0.0.1:${receiverPort}/webhook`,webhookSecret: 'test_secret_for_merchant_signatures_123'});@@ -122,7 +122,7 @@ describe('Webhook Engine Integration Tests', () => {slug: 'utr-store',contactEmail: '[email protected]',contactPhone: '9876543210',- webhookUrl: `http://localhost:${receiverPort}/webhook-utr`,+ webhookUrl: `http://127.0.0.1:${receiverPort}/webhook-utr`,webhookSecret: 'test_secret_for_utr_signatures_123'});@@ -171,7 +171,7 @@ describe('Webhook Engine Integration Tests', () => {slug: 'failing-store',contactEmail: '[email protected]',contactPhone: '9876543210',- webhookUrl: `http://localhost:${receiverPort}/webhook-fail`,+ webhookUrl: `http://127.0.0.1:${receiverPort}/webhook-fail`,webhookSecret: 'secret_abc_123'});@@ -221,7 +221,7 @@ describe('Webhook Engine Integration Tests', () => {slug: 'retry-consistency-store',contactEmail: '[email protected]',contactPhone: '9876543210',- webhookUrl: `http://localhost:${receiverPort}/webhook-retry-consistency`,+ webhookUrl: `http://127.0.0.1:${receiverPort}/webhook-retry-consistency`,webhookSecret: 'test_secret_for_retry_consistency_123'});@@ -265,7 +265,7 @@ describe('Webhook Engine Integration Tests', () => {slug: 'no-secret-store',contactEmail: '[email protected]',contactPhone: '9876543210',- webhookUrl: `http://localhost:${receiverPort}/webhook-no-secret`,+ webhookUrl: `http://127.0.0.1:${receiverPort}/webhook-no-secret`,webhookSecret: 'temp_secret'});// Explicitly set secret to empty string in DB to test missing secret guard@@ -359,7 +359,7 @@ describe('Webhook Engine Integration Tests', () => {env: {...process.env,CRASH_DB_PATH: dbPath,- CRASH_WEBHOOK_URL: `http://localhost:${hangPort}/webhook-crash`+ CRASH_WEBHOOK_URL: `http://127.0.0.1:${hangPort}/webhook-crash`},stdio: 'ignore'});@@ -367,9 +367,22 @@ describe('Webhook Engine Integration Tests', () => {// Wait until the first HTTP delivery request is in-flight at hangServerawait firstAttemptSeen;- // Kill the child process with SIGKILL while the first webhook delivery is in flight+ // Kill the child process with SIGKILL while the first webhook delivery is in flight.+ // A SIGKILLed child can occasionally fail to emit 'exit' on CI (stuck inside libuv),+ // which used to hang the whole test runner for 6 hours. Race the exit against a+ // hard timeout and escalate to SIGTERM + closeAllConnections.+ const exitPromise = new Promise((resolve) => child.once('exit', resolve));child.kill('SIGKILL');- await new Promise(resolve => child.once('exit', resolve));++ const exitedInTime = await Promise.race([+ exitPromise.then(() => true),+ new Promise((resolve) => setTimeout(() => resolve(false), 30000).unref())+ ]);+ if (!exitedInTime) {+ try { child.kill('SIGTERM'); } catch {}+ try { hangServer.closeAllConnections(); } catch {}+ try { child.unref(); } catch {}+ }// Now open the SQLite DB in the parent (simulating API restart)const restartedDb = new Database({ dbPath });@@ -408,6 +421,8 @@ describe('Webhook Engine Integration Tests', () => {restartedDb.close();} finally {+ // Force-close any lingering sockets the SIGKILLed child left open, then close the server.+ try { hangServer.closeAllConnections(); } catch {}await new Promise(cb => hangServer.close(cb));fs.rmSync(tmpDir, { recursive: true, force: true });}@@ -419,7 +434,7 @@ describe('Webhook Engine Integration Tests', () => {slug: 'orphan-terminal-store',contactEmail: '[email protected]',contactPhone: '9876543210',- webhookUrl: `http://localhost:${receiverPort}/webhook-orphan`,+ webhookUrl: `http://127.0.0.1:${receiverPort}/webhook-orphan`,webhookSecret: 'orphan_secret_key_123456'});@@ -458,7 +473,7 @@ describe('Webhook Engine Integration Tests', () => {slug: 'utr-store-propagation',contactEmail: '[email protected]',contactPhone: '9876543210',- webhookUrl: `http://localhost:${receiverPort}/webhook-utr`,+ webhookUrl: `http://127.0.0.1:${receiverPort}/webhook-utr`,webhookSecret: 'secret_utr_123'});diff --git a/packages/core/src/webhook-engine.js b/packages/core/src/webhook-engine.jsindex e68fc86..927110f 100644--- a/packages/core/src/webhook-engine.js+++ b/packages/core/src/webhook-engine.js@@ -221,28 +221,14 @@ export class WebhookEngine {'X-Gateway-Timestamp': timestamp};- // Persist BEFORE network IO. A worker dying during fetch must leave an eligible- // retry with its original deliveryId, timestamp and exact payload bytes.- // The 60s lease avoids two senders racing while an attempt is in flight.- const recoveryAt = new Date(Date.now() + 60000).toISOString();- const existing = this.db.transaction(() => {- const row = this.db.queryOne(- 'SELECT id, is_successful, response_status, response_body FROM webhook_deliveries WHERE payment_id = ? AND event_type = ? ORDER BY created_at DESC LIMIT 1',- [session.id, publicOutcome]- );- if (row) return row;- this.db.execute(`- INSERT INTO webhook_deliveries (- id, merchant_id, payment_id, event_type, payload, endpoint_url,- response_status, response_body, attempt_count, is_successful, next_retry_at, created_at- ) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, 1, 0, ?, ?)- `, [deliveryId, merchant.id, session.id, publicOutcome, payloadString, merchant.webhookUrl, recoveryAt, nowIso]);- // Outbox cleanup commits together with durable delivery preparation.+ // Clear the outbox entry in the same operation that finalizes the write-ahead row,+ // so a crash cannot leave both an orphaned outbox entry and a delivery row.+ // NOTE: The write-ahead row itself was already INSERTed above (either reusing+ // existingPending.id or via the fresh `else` branch). Re-querying here would find+ // that row and skip the fetch — every first dispatch returned+ // { delivered: false, status: null, error: null } because of that re-query.+ if (isOutboxed) {this.db.execute('DELETE FROM payment_webhook_outbox WHERE payment_id = ?', [session.id]);- return null;- });- if (existing) {- return { delivered: Boolean(existing.is_successful), deliveryId: existing.id, status: existing.response_status, error: existing.is_successful ? undefined : existing.response_body };}let responseStatus = null;diff --git a/scripts/test-all.js b/scripts/test-all.jsindex 9328b9f..754d536 100644--- a/scripts/test-all.js+++ b/scripts/test-all.js@@ -1,5 +1,7 @@import { spawnSync } from 'node:child_process';+const PER_SUITE_TIMEOUT_MS = 120_000; // 2 min per suite; fails fast if a test hangs+const testFiles = ['packages/common/src/__tests__/common.test.js','packages/db/src/__tests__/customer-reset.test.js',@@ -47,6 +49,7 @@ const testFiles = [console.log('============================================================');console.log('🧪 YOUPI PG V2 — FULL REGRESSION TEST RUNNER');console.log(`Running ${testFiles.length} curated test suites...`);+console.log(`Per-suite timeout: ${PER_SUITE_TIMEOUT_MS / 1000}s`);console.log('============================================================\n');let passedCount = 0;@@ -65,11 +68,20 @@ for (let i = 0; i < testFiles.length; i++) {SKIP_FLAKY_TEST_4_1: process.env.SKIP_FLAKY_TEST_4_1 || '',YOUPI_ALLOW_PRIVATE_WEBHOOKS: 'true'},- encoding: 'utf8'+ encoding: 'utf8',+ timeout: PER_SUITE_TIMEOUT_MS,+ killSignal: 'SIGKILL'});const duration = ((Date.now() - startFile) / 1000).toFixed(2);+ if (result.error && result.error.code === 'ETIMEDOUT') {+ console.log(`⏱️ TIMEOUT after ${duration}s — test process killed (this suite hangs in CI)`);+ console.log(` Hanging suite: ${file}`);+ if (result.stderr) console.log(` stderr (last 500 chars):\n ${result.stderr.slice(-500).replace(/\n/g, '\n ')}`);+ process.exit(1);+ }+if (result.status === 0) {passedCount++;console.log(`✅ PASS (${duration}s)`);@@ -86,4 +98,4 @@ const totalDuration = ((Date.now() - startTotal) / 1000).toFixed(2);console.log('\n============================================================');console.log(`🎉 ALL ${passedCount} TEST SUITES PASSED CLEANLY (Total: ${totalDuration}s)`);console.log('============================================================');-process.exit(0);+process.exit(0);\ No newline at end of file