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(payment-api): consolidate observer polling loops and eliminate SQLite lock contention (Closes #43)
ArunGupta1526391b0f9fa747
diff --git a/apps/control-center/src/server.js b/apps/control-center/src/server.jsindex 8c0f016..440bb71 100644--- a/apps/control-center/src/server.js+++ b/apps/control-center/src/server.js@@ -183,6 +183,7 @@ export class ControlCenterServer {const pingTimer = setInterval(() => {try { res.write(': keepalive\n\n'); } catch { clearInterval(pingTimer); }}, 15000);+ if (pingTimer.unref) pingTimer.unref();res.on('close', () => {clearInterval(pingTimer);diff --git a/apps/gmail-observer/src/browser-automator.js b/apps/gmail-observer/src/browser-automator.jsindex 1609fb7..b34f05f 100644--- a/apps/gmail-observer/src/browser-automator.js+++ b/apps/gmail-observer/src/browser-automator.js@@ -2,6 +2,7 @@ import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';import { BrowserLauncher } from '@youpi/observer-sdk';+import { getObserverToken } from '@youpi/common';import { BankEmailParser } from './parser.js';const __filename = fileURLToPath(import.meta.url);@@ -39,7 +40,13 @@ export class GmailBrowserAutomator {async fetchActivePaymentAmounts() {try {- const res = await fetch(`${this.apiBaseUrl}/api/v1/pollers/active-window`, { signal: AbortSignal.timeout(1500) });+ if (this.gmailPoller && this.gmailPoller.observerClient && typeof this.gmailPoller.observerClient.getActiveWindow === 'function') {+ return await this.gmailPoller.observerClient.getActiveWindow();+ }+ const res = await fetch(`${this.apiBaseUrl}/api/v1/pollers/active-window`, {+ headers: { 'Authorization': `Bearer ${getObserverToken()}` },+ signal: AbortSignal.timeout(1500)+ });if (res.ok) {const data = await res.json();return data.sessions || [];@@ -216,6 +223,7 @@ export class GmailBrowserAutomator {// Target busy or initializing}}, 2000);+ if (this.checkTimer.unref) this.checkTimer.unref();}/**@@ -231,10 +239,15 @@ export class GmailBrowserAutomator {// Session idle or updating}}, 3000);+ if (this.extractionTimer.unref) this.extractionTimer.unref();}async pollInboxEmails() {- const targets = await BrowserLauncher.getTargets(this.debuggingPort);+ if (this._isPollingInbox) return;+ this._isPollingInbox = true;++ try {+ const targets = await BrowserLauncher.getTargets(this.debuggingPort);const target = targets.find(t => (t.type === 'page' || !t.type) && t.url && t.url.includes('mail.google.com') && t.webSocketDebuggerUrl)|| targets.find(t => t.url && t.url.includes('mail.google.com') && t.webSocketDebuggerUrl);if (!target) return;@@ -360,6 +373,9 @@ export class GmailBrowserAutomator {}}}+ } finally {+ this._isPollingInbox = false;+ }}getStatus() {diff --git a/apps/gmail-observer/src/gmail-poller.js b/apps/gmail-observer/src/gmail-poller.jsindex e66dc98..1f72ff7 100644--- a/apps/gmail-observer/src/gmail-poller.js+++ b/apps/gmail-observer/src/gmail-poller.js@@ -197,6 +197,7 @@ export class GmailPoller {this.timer = setInterval(() => {this.pollCycle().catch(() => {});}, this.pollIntervalMs);+ if (this.timer.unref) this.timer.unref();}stop() {@@ -205,13 +206,16 @@ export class GmailPoller {this.timer = null;}this.isRunning = false;+ this._isPolling = false;console.log('[Gmail Observer] Poller stopped.');}async pollCycle() {- this.lastPollAt = new Date();+ if (this._isPolling) return;+ this._isPolling = true;try {+ this.lastPollAt = new Date();const accessToken = await this.getAccessToken();if (!accessToken) return;@@ -268,6 +272,8 @@ export class GmailPoller {}} catch (err) {console.warn('[Gmail Observer] pollCycle error:', err.message);+ } finally {+ this._isPolling = false;}}}diff --git a/apps/payment-api/src/__tests__/observer-poller.test.js b/apps/payment-api/src/__tests__/observer-poller.test.jsnew file mode 100644index 0000000..6682a39--- /dev/null+++ b/apps/payment-api/src/__tests__/observer-poller.test.js@@ -0,0 +1,188 @@+import { test, describe, beforeEach, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { EventEmitter } from 'node:events';+import { getDatabase, ensureDatabaseInitialized, runMigrations, PaymentSessionRepository, ObservationRepository } from '@youpi/db';+import { AttributionEngine } from '@youpi/core';+import { ObserverPollerService } from '../services/observer-poller.service.js';++describe('ObserverPollerService Hardening & Concurrency Protection', () => {+ let db;+ let eventEmitter;+ let sessionRepo;+ let obsRepo;+ let attributionEngine;+ let pollerService;++ beforeEach(() => {+ db = getDatabase(':memory:');+ ensureDatabaseInitialized(db);+ runMigrations(db);++ eventEmitter = new EventEmitter();+ sessionRepo = new PaymentSessionRepository(db);+ obsRepo = new ObservationRepository(db);+ attributionEngine = new AttributionEngine({+ sessionRepo,+ obsRepo,+ eventEmitter+ });+ });++ afterEach(() => {+ if (pollerService) {+ pollerService.destroy();+ pollerService = null;+ }+ });++ test('Requirement 5: Daemon automatically idles when no active or processing sessions exist', async () => {+ pollerService = new ObserverPollerService({+ db,+ sessionRepo,+ obsRepo,+ attributionEngine,+ eventEmitter,+ pollIntervalMs: 1000,+ minSweepCooldownMs: 2000,+ autoStart: false+ });++ // Run poll cycle when DB is completely empty of active sessions+ await pollerService.pollCycle();++ assert.equal(pollerService.isIdle, true, 'Poller must be idle when 0 active sessions exist');+ assert.equal(pollerService.isSmsSweepInFlight, false);+ assert.equal(pollerService.isGmailSweepInFlight, false);+ assert.equal(pollerService.lastSmsSweepTime, 0, 'No SMS sweep should be dispatched when idle');+ assert.equal(pollerService.lastGmailSweepTime, 0, 'No Gmail sweep should be dispatched when idle');+ });++ test('Requirement 3: Enforces minimum cooldown between consecutive sweeps and drops redundant in-flight calls', async () => {+ pollerService = new ObserverPollerService({+ db,+ sessionRepo,+ obsRepo,+ attributionEngine,+ eventEmitter,+ pollIntervalMs: 1000,+ minSweepCooldownMs: 1500, // 1.5s cooldown+ autoStart: false+ });++ // First sweep attempt: should dispatch (returns a promise)+ const sweep1Promise = pollerService.sweepSmsObserver();+ assert.equal(pollerService.isSmsSweepInFlight, true, 'In-flight flag must be true during execution');++ // Immediate second sweep while in-flight: MUST BE DROPPED+ const sweep2 = await pollerService.sweepSmsObserver();+ assert.equal(sweep2, false, 'Redundant in-flight sweep must return false and be dropped');++ await sweep1Promise;+ assert.equal(pollerService.isSmsSweepInFlight, false, 'In-flight flag must reset after completion');++ // Third sweep immediately after, within the 1.5s cooldown window: MUST BE DROPPED+ const sweep3 = await pollerService.sweepSmsObserver();+ assert.equal(sweep3, false, 'Sweep within 1.5s cooldown window must be rejected');++ // Same behavior for Gmail observer+ const gmail1Promise = pollerService.sweepGmailObserver();+ assert.equal(pollerService.isGmailSweepInFlight, true);+ const gmail2 = await pollerService.sweepGmailObserver();+ assert.equal(gmail2, false, 'Concurrent in-flight Gmail sweep must be dropped');+ await gmail1Promise;+ const gmail3 = await pollerService.sweepGmailObserver();+ assert.equal(gmail3, false, 'Gmail sweep within cooldown window must be dropped');+ });++ test('Requirement 4: Mutex and deduplication prevent concurrent attribution and SQLite contention', async () => {+ pollerService = new ObserverPollerService({+ db,+ sessionRepo,+ obsRepo,+ attributionEngine,+ eventEmitter,+ pollIntervalMs: 1000,+ minSweepCooldownMs: 2000,+ autoStart: false+ });++ // Mock active sessions sharing the same receiving account ID+ const activeSessions = [+ { id: 'sess-1', receiving_account_id: 'acc-duplicate-1', amount_paise: 50000, status: 'PROCESSING' },+ { id: 'sess-2', receiving_account_id: 'acc-duplicate-1', amount_paise: 50000, status: 'PROCESSING' },+ { id: 'sess-3', receiving_account_id: 'acc-duplicate-1', amount_paise: 50000, status: 'PROCESSING' }+ ];++ let queryCount = 0;+ const originalFindUnattributed = obsRepo.findUnattributed.bind(obsRepo);+ obsRepo.findUnattributed = (accId) => {+ queryCount++;+ return originalFindUnattributed(accId);+ };++ await pollerService.processPendingAttributions(activeSessions);++ // Invariant: Account IDs are deduplicated so findUnattributed is called exactly ONCE per account!+ assert.equal(queryCount, 1, 'findUnattributed should only be queried once per distinct receiving account');+ assert.equal(pollerService.isAttributionInProgress, false);+ });++ test('Reactive wake-up on SESSION.PROCESSING and SESSION.ACTIVATED without waiting for timer interval', async () => {+ pollerService = new ObserverPollerService({+ db,+ sessionRepo,+ obsRepo,+ attributionEngine,+ eventEmitter,+ pollIntervalMs: 60000, // 60s slow timer+ minSweepCooldownMs: 2000,+ autoStart: true+ });++ let expeditedCalled = false;+ pollerService.triggerExpeditedSweep = () => {+ expeditedCalled = true;+ };++ // Customer clicks "I have paid" -> SESSION.PROCESSING event emitted+ eventEmitter.emit('SESSION.PROCESSING', {+ sessionId: 'sess-active-1',+ receivingAccountId: 'acc-1'+ });++ assert.equal(expeditedCalled, true, 'SESSION.PROCESSING must wake up poller immediately');++ expeditedCalled = false;+ // New session activated -> SESSION.ACTIVATED event emitted+ eventEmitter.emit('SESSION.ACTIVATED', {+ sessionId: 'sess-active-2',+ receivingAccountId: 'acc-1'+ });++ assert.equal(expeditedCalled, true, 'SESSION.ACTIVATED must wake up poller immediately');+ });++ test('Clean lifecycle destruction removes event listeners and clears intervals', () => {+ pollerService = new ObserverPollerService({+ db,+ sessionRepo,+ obsRepo,+ attributionEngine,+ eventEmitter,+ pollIntervalMs: 1000,+ autoStart: true+ });++ assert.equal(pollerService.isRunning, true);+ assert.notEqual(pollerService._timer, null);++ const listenerCountBefore = eventEmitter.listenerCount('SESSION.PROCESSING');+ assert.ok(listenerCountBefore >= 1);++ pollerService.destroy();++ assert.equal(pollerService.isRunning, false);+ assert.equal(pollerService._timer, null);+ assert.equal(eventEmitter.listenerCount('SESSION.PROCESSING'), listenerCountBefore - 1);+ });+});diff --git a/apps/payment-api/src/index.js b/apps/payment-api/src/index.jsindex e2bddac..4e8c57d 100644--- a/apps/payment-api/src/index.js+++ b/apps/payment-api/src/index.js@@ -48,6 +48,7 @@ import { registerAdminRoutes } from './routes/admin.routes.js';import { registerCustomerRoutes } from './routes/customer.routes.js';import { registerDeviceRoutes } from './routes/device.routes.js';import { getWhatsAppBerryService, WhatsAppBerryService } from './services/whatsapp-berry.service.js';+import { ObserverPollerService } from './services/observer-poller.service.js';export function createPaymentApp(customDb = null, options = {}) {const db = customDb || getDatabase();@@ -228,72 +229,6 @@ export function createPaymentApp(customDb = null, options = {}) {}});- // Active 30-Second Verification Polling Orchestrator (Triple Verification Standard):- // Concurrently sweeps Gmail, Google Messages SMS, and Android Observer every 1.5s- // Continues polling for remaining sources until Level 3 (Triple Verification) is reached or 30s window finishes!- const activeSweepTimers = new Set();-- eventEmitter.on('SESSION.PROCESSING', (data) => {- const sessionId = data.sessionId;- let sweepCount = 0;- const maxSweeps = 20; // 20 sweeps * 1.5s = 30 seconds-- const sweepTimer = setInterval(async () => {- try {- sweepCount++;- const current = sessionRepo.findById(sessionId);-- // Stop polling if session is terminal failed/expired/cancelled, or reached full Triple Verification (level >= 3), or exceeded 30s- const isCompleteOrCancelled = !current ||- current.status === PaymentStatus.FAILED ||- current.status === PaymentStatus.EXPIRED ||- current.status === PaymentStatus.CANCELLED ||- (current.verificationLevel >= 3) ||- sweepCount >= maxSweeps;-- if (isCompleteOrCancelled) {- clearInterval(sweepTimer);- activeSweepTimers.delete(sweepTimer);- return;- }-- // Sweep 1: Google Messages Web SMS- try {- const smsPort = Number(process.env.SMS_OBSERVER_PORT || 6002);- fetch(`http://localhost:${smsPort}/api/sweep`, { method: 'POST', signal: AbortSignal.timeout(1200) }).catch(() => {});- } catch {}-- // Sweep 2: Gmail Inbox- try {- const gmailPort = Number(process.env.GMAIL_OBSERVER_PORT || 6003);- fetch(`http://localhost:${gmailPort}/api/sweep`, { method: 'POST', signal: AbortSignal.timeout(1200) }).catch(() => {});- } catch {}-- // Sweep 3: Check pending/unattributed Android push notifications in DB- try {- const unattributed = obsRepo.findUnattributed(current.receivingAccountId);- for (const obs of unattributed) {- attributionEngine.processObservation({- source: obs.source,- receivingAccountId: obs.receivingAccountId,- amountPaise: obs.amountPaise,- observedAt: obs.observedAt,- bankReferenceNumber: obs.bankReferenceNumber,- senderVpa: obs.senderVpa,- rawPayload: obs.rawPayload,- fingerprintHash: obs.fingerprintHash- });- }- } catch {}- } catch {- clearInterval(sweepTimer);- activeSweepTimers.delete(sweepTimer);- }- }, 1500);-- if (sweepTimer.unref) sweepTimer.unref();- activeSweepTimers.add(sweepTimer);- });// Continuous 1-second background queue sync and auto-expiry daemonconst queueSyncDaemon = setInterval(() => {@@ -338,52 +273,19 @@ export function createPaymentApp(customDb = null, options = {}) {if (queueSyncDaemon.unref) queueSyncDaemon.unref();- // Continuous 1-Second Aggressive Polling Daemon across SMS Gateway & Gmail Observers- const aggressivePollerDaemon = setInterval(async () => {- try {- // Find all active/processing sessions currently waiting for bank confirmation- const activeSessions = db.query(`- SELECT id, receiving_account_id, amount_paise, status- FROM payment_sessions- WHERE status IN ('ACTIVE', 'PROCESSING') AND method = 'UPI'- `);-- if (activeSessions.length === 0) return;-- // 1. Poll SMS Observer- try {- const smsPort = Number(process.env.SMS_OBSERVER_PORT || 6002);- fetch(`http://localhost:${smsPort}/api/sweep`, { method: 'POST', signal: AbortSignal.timeout(800) }).catch(() => {});- } catch {}-- // 2. Poll Gmail Observer- try {- const gmailPort = Number(process.env.GMAIL_OBSERVER_PORT || 6003);- fetch(`http://localhost:${gmailPort}/api/sweep`, { method: 'POST', signal: AbortSignal.timeout(800) }).catch(() => {});- } catch {}-- // 3. Sweep any pending unattributed observations in DB matching active sessions- for (const session of activeSessions) {- try {- const unattributed = obsRepo.findUnattributed(session.receiving_account_id);- for (const obs of unattributed) {- attributionEngine.processObservation({- source: obs.source,- receivingAccountId: obs.receivingAccountId,- amountPaise: obs.amountPaise,- observedAt: obs.observedAt,- bankReferenceNumber: obs.bankReferenceNumber,- senderVpa: obs.senderVpa,- rawPayload: obs.rawPayload,- fingerprintHash: obs.fingerprintHash- });- }- } catch {}- }- } catch {}- }, 1000);-- if (aggressivePollerDaemon.unref) aggressivePollerDaemon.unref();+ // Consolidated, Coordinated Observer Polling & Verification Daemon+ // Eliminates duplicate HTTP sweeps, enforces 1.5s-2s cooldown, and prevents SQLite write contention+ const observerPollerService = new ObserverPollerService({+ db,+ sessionRepo,+ obsRepo,+ attributionEngine,+ eventEmitter,+ pollIntervalMs: Number(process.env.OBSERVER_POLL_INTERVAL_MS || 1500),+ minSweepCooldownMs: Number(process.env.OBSERVER_SWEEP_COOLDOWN_MS || 2000),+ smsPort: Number(process.env.SMS_OBSERVER_PORT || 6002),+ gmailPort: Number(process.env.GMAIL_OBSERVER_PORT || 6003)+ });// Execute crash recovery on bootconst recoveryStats = recoveryEngine.recover();@@ -432,7 +334,8 @@ export function createPaymentApp(customDb = null, options = {}) {defaultMerchant,checkoutBaseUrl,whatsappBerryService,- webhookEngine+ webhookEngine,+ observerPollerService};registerPaymentRoutes(server, context);@@ -444,11 +347,7 @@ export function createPaymentApp(customDb = null, options = {}) {function destroy() {clearInterval(queueSyncDaemon);- clearInterval(aggressivePollerDaemon);- for (const timer of activeSweepTimers) {- clearInterval(timer);- }- activeSweepTimers.clear();+ observerPollerService.destroy();timingEngine.destroy();if (typeof attributionEngine.destroy === 'function') {attributionEngine.destroy();diff --git a/apps/payment-api/src/server.js b/apps/payment-api/src/server.jsindex 8ead048..45fd4d5 100644--- a/apps/payment-api/src/server.js+++ b/apps/payment-api/src/server.js@@ -105,7 +105,6 @@ export class HttpServer {const set = this.sseClients.get(topic);set.add(res);- // Keepalive ping every 15sconst pingInterval = setInterval(() => {try {res.write(': keepalive\n\n');@@ -113,6 +112,7 @@ export class HttpServer {clearInterval(pingInterval);}}, 15000);+ if (pingInterval.unref) pingInterval.unref();res.on('close', () => {clearInterval(pingInterval);diff --git a/apps/payment-api/src/services/observer-poller.service.js b/apps/payment-api/src/services/observer-poller.service.jsnew file mode 100644index 0000000..e8da52b--- /dev/null+++ b/apps/payment-api/src/services/observer-poller.service.js@@ -0,0 +1,366 @@+import { getObserverToken } from '@youpi/common';++/**+ * ObserverPollerService+ *+ * Consolidated, coordinated background poller and verification daemon.+ * Replaces duplicate, uncoordinated polling loops with a single unified orchestrator:+ * - Automatically idles when no active/processing UPI sessions exist.+ * - Enforces minimum 1.5s–2.0s cooldown between external observer sweeps (SMS and Gmail).+ * - Drops redundant in-flight HTTP requests to prevent observer socket exhaustion.+ * - Serializes observation attribution with a mutex lock to eliminate SQLite lock contention (SQLITE_BUSY).+ * - Reacts immediately to payment events (SESSION.PROCESSING, SESSION.ACTIVATED) without waiting for timer ticks.+ */+export class ObserverPollerService {+ /**+ * @param {{+ * db: import('@youpi/db').Database,+ * sessionRepo: import('@youpi/db').PaymentSessionRepository,+ * obsRepo: import('@youpi/db').ObservationRepository,+ * attributionEngine: import('@youpi/core').AttributionEngine,+ * eventEmitter: import('node:events').EventEmitter,+ * pollIntervalMs?: number,+ * minSweepCooldownMs?: number,+ * smsPort?: number,+ * gmailPort?: number,+ * observerToken?: string,+ * autoStart?: boolean+ * }} options+ */+ constructor(options) {+ if (!options || !options.db || !options.sessionRepo || !options.obsRepo || !options.attributionEngine || !options.eventEmitter) {+ throw new Error('ObserverPollerService requires db, sessionRepo, obsRepo, attributionEngine, and eventEmitter');+ }++ this.db = options.db;+ this.sessionRepo = options.sessionRepo;+ this.obsRepo = options.obsRepo;+ this.attributionEngine = options.attributionEngine;+ this.eventEmitter = options.eventEmitter;++ // Configurable timing parameters+ this.pollIntervalMs = Number(options.pollIntervalMs || process.env.OBSERVER_POLL_INTERVAL_MS || 1500);+ this.minSweepCooldownMs = Number(options.minSweepCooldownMs || process.env.OBSERVER_SWEEP_COOLDOWN_MS || 2000);+ this.smsPort = Number(options.smsPort || process.env.SMS_OBSERVER_PORT || 6002);+ this.gmailPort = Number(options.gmailPort || process.env.GMAIL_OBSERVER_PORT || 6003);+ this.observerToken = options.observerToken || null;++ // Lifecycle and concurrency control state+ this._isRunning = false;+ this._isPollingCycle = false;+ this._isIdle = true;+ this._timer = null;++ // Cooldown and in-flight tracking for observer endpoints+ this._lastSmsSweepTime = 0;+ this._lastGmailSweepTime = 0;+ this._isSmsSweepInFlight = false;+ this._isGmailSweepInFlight = false;++ // Attribution mutex & in-flight hash set to prevent SQLite write contention+ this._isAttributionInProgress = false;+ this._inFlightObservationHashes = new Set();++ // Event listener bindings+ this._boundOnSessionProcessing = this.handleSessionProcessing.bind(this);+ this._boundOnSessionActivated = this.handleSessionActivated.bind(this);+ this._boundOnPaymentTerminal = this.handlePaymentTerminal.bind(this);++ if (options.autoStart !== false) {+ this.start();+ }+ }++ get isRunning() {+ return this._isRunning;+ }++ get isIdle() {+ return this._isIdle;+ }++ get isSmsSweepInFlight() {+ return this._isSmsSweepInFlight;+ }++ get isGmailSweepInFlight() {+ return this._isGmailSweepInFlight;+ }++ get isAttributionInProgress() {+ return this._isAttributionInProgress;+ }++ get lastSmsSweepTime() {+ return this._lastSmsSweepTime;+ }++ get lastGmailSweepTime() {+ return this._lastGmailSweepTime;+ }++ /**+ * Starts the consolidated poller daemon and binds event listeners.+ */+ start() {+ if (this._isRunning) return;+ this._isRunning = true;++ // Bind reactive lifecycle events+ this.eventEmitter.on('SESSION.PROCESSING', this._boundOnSessionProcessing);+ this.eventEmitter.on('SESSION.ACTIVATED', this._boundOnSessionActivated);+ this.eventEmitter.on('PAYMENT.SUCCESS', this._boundOnPaymentTerminal);+ this.eventEmitter.on('PAYMENT.FAILED', this._boundOnPaymentTerminal);+ this.eventEmitter.on('PAYMENT.EXPIRED', this._boundOnPaymentTerminal);+ this.eventEmitter.on('PAYMENT.CANCELLED', this._boundOnPaymentTerminal);++ // Start single consolidated daemon interval+ this._timer = setInterval(() => {+ this.pollCycle().catch(() => {});+ }, this.pollIntervalMs);++ if (this._timer.unref) {+ this._timer.unref();+ }++ // Initial check+ this.pollCycle().catch(() => {});+ }++ /**+ * Stops the daemon, cleans up timers, and removes event listeners.+ */+ stop() {+ this._isRunning = false;++ if (this._timer) {+ clearInterval(this._timer);+ this._timer = null;+ }++ if (this.eventEmitter) {+ this.eventEmitter.removeListener('SESSION.PROCESSING', this._boundOnSessionProcessing);+ this.eventEmitter.removeListener('SESSION.ACTIVATED', this._boundOnSessionActivated);+ this.eventEmitter.removeListener('PAYMENT.SUCCESS', this._boundOnPaymentTerminal);+ this.eventEmitter.removeListener('PAYMENT.FAILED', this._boundOnPaymentTerminal);+ this.eventEmitter.removeListener('PAYMENT.EXPIRED', this._boundOnPaymentTerminal);+ this.eventEmitter.removeListener('PAYMENT.CANCELLED', this._boundOnPaymentTerminal);+ }++ this._inFlightObservationHashes.clear();+ this._isPollingCycle = false;+ this._isAttributionInProgress = false;+ this._isSmsSweepInFlight = false;+ this._isGmailSweepInFlight = false;+ this._isIdle = true;+ }++ /**+ * Alias for stop() for standard engine lifecycle parity.+ */+ destroy() {+ this.stop();+ }++ /**+ * Reactive handler when a customer initiates payment confirmation.+ * Wakes up the poller immediately without waiting for the next interval tick.+ * @param {{ sessionId?: string, receivingAccountId?: string }} data+ */+ handleSessionProcessing(data) {+ this.triggerExpeditedSweep(data?.receivingAccountId);+ }++ /**+ * Reactive handler when a new session transitions to ACTIVE.+ * @param {{ sessionId?: string, receivingAccountId?: string }} data+ */+ handleSessionActivated(data) {+ this._isIdle = false;+ this.triggerExpeditedSweep(data?.receivingAccountId);+ }++ /**+ * Reactive handler on terminal payment outcomes.+ */+ handlePaymentTerminal() {+ // Next poll cycle will automatically update idle state+ }++ /**+ * Immediately triggers a poll sweep, waking the poller if idle.+ * @param {string} [preferredAccountId]+ */+ triggerExpeditedSweep(preferredAccountId = null) {+ if (!this._isRunning || this._isPollingCycle) return;+ this.pollCycle(preferredAccountId).catch(() => {});+ }++ /**+ * Finds all active payment sessions waiting for bank verification.+ * Includes ACTIVE, PROCESSING, and recent SUCCESS sessions awaiting secondary channel dual/triple match.+ * @returns {Array<{ id: string, receiving_account_id: string, amount_paise: number, status: string, verification_level?: number }>}+ */+ getActiveSessions() {+ try {+ const sixtySecsAgo = new Date(Date.now() - 60000).toISOString();+ return this.db.query(`+ SELECT id, receiving_account_id, amount_paise, status, verification_level+ FROM payment_sessions+ WHERE method = 'UPI' AND (+ status IN ('ACTIVE', 'PROCESSING')+ OR (status = 'SUCCESS' AND verification_level < 2 AND completed_at >= ?)+ )+ `, [sixtySecsAgo]);+ } catch {+ return [];+ }+ }++ /**+ * Executes a single coordinated polling cycle:+ * 1. Evaluates active sessions; idles immediately if none are active.+ * 2. Fires throttled sweeps to SMS and Gmail observers (respecting cooldown & in-flight lock).+ * 3. Sequentially processes unattributed bank observations under mutex lock.+ * @param {string} [preferredAccountId]+ */+ async pollCycle(preferredAccountId = null) {+ if (!this._isRunning || this._isPollingCycle) return;+ this._isPollingCycle = true;++ try {+ const activeSessions = this.getActiveSessions();++ if (activeSessions.length === 0) {+ this._isIdle = true;+ return;+ }++ this._isIdle = false;++ // 1. Concurrently trigger external observer sweeps with strict cooldown & in-flight locks+ await Promise.allSettled([+ this.sweepSmsObserver(),+ this.sweepGmailObserver()+ ]);++ // 2. Process pending unattributed bank observations in DB under sequential mutex lock+ await this.processPendingAttributions(activeSessions, preferredAccountId);+ } finally {+ this._isPollingCycle = false;+ }+ }++ /**+ * Sweeps Google Messages SMS Observer with cooldown and in-flight protection.+ * Drops redundant calls if cooldown has not elapsed or another sweep is currently in flight.+ * @returns {Promise<boolean>} True if sweep was dispatched, false if dropped/in-flight/cooldown.+ */+ async sweepSmsObserver() {+ const now = Date.now();+ if (this._isSmsSweepInFlight || (now - this._lastSmsSweepTime < this.minSweepCooldownMs)) {+ return false;+ }++ this._isSmsSweepInFlight = true;+ this._lastSmsSweepTime = now;++ try {+ const token = this.observerToken || getObserverToken();+ const headers = token ? { 'Authorization': `Bearer ${token}` } : {};++ await fetch(`http://localhost:${this.smsPort}/api/sweep`, {+ method: 'POST',+ headers,+ signal: AbortSignal.timeout(1200)+ });+ return true;+ } catch {+ return false;+ } finally {+ this._isSmsSweepInFlight = false;+ }+ }++ /**+ * Sweeps Gmail Observer with cooldown and in-flight protection.+ * Drops redundant calls if cooldown has not elapsed or another sweep is currently in flight.+ * @returns {Promise<boolean>} True if sweep was dispatched, false if dropped/in-flight/cooldown.+ */+ async sweepGmailObserver() {+ const now = Date.now();+ if (this._isGmailSweepInFlight || (now - this._lastGmailSweepTime < this.minSweepCooldownMs)) {+ return false;+ }++ this._isGmailSweepInFlight = true;+ this._lastGmailSweepTime = now;++ try {+ const token = this.observerToken || getObserverToken();+ const headers = token ? { 'Authorization': `Bearer ${token}` } : {};++ await fetch(`http://localhost:${this.gmailPort}/api/sweep`, {+ method: 'POST',+ headers,+ signal: AbortSignal.timeout(1200)+ });+ return true;+ } catch {+ return false;+ } finally {+ this._isGmailSweepInFlight = false;+ }+ }++ /**+ * Processes unattributed observations for active accounts under strict sequential mutex lock.+ * Deduplicates receivingAccountIds and tracks in-flight observation hashes to prevent+ * concurrent SQLite write transactions and SQLITE_BUSY contention.+ * @param {Array<{ receiving_account_id: string }>} activeSessions+ * @param {string} [preferredAccountId]+ */+ async processPendingAttributions(activeSessions, preferredAccountId = null) {+ if (this._isAttributionInProgress) return;+ this._isAttributionInProgress = true;++ try {+ const rawAccountIds = activeSessions.map(s => s.receiving_account_id).filter(Boolean);+ const accountIds = [...new Set(rawAccountIds)];++ if (preferredAccountId && accountIds.includes(preferredAccountId)) {+ accountIds.sort((a, b) => a === preferredAccountId ? -1 : (b === preferredAccountId ? 1 : 0));+ }++ for (const accountId of accountIds) {+ const unattributed = this.obsRepo.findUnattributed(accountId);+ if (!Array.isArray(unattributed) || unattributed.length === 0) continue;++ for (const obs of unattributed) {+ const hash = obs.fingerprintHash || obs.id;+ if (this._inFlightObservationHashes.has(hash)) continue;++ this._inFlightObservationHashes.add(hash);+ try {+ this.attributionEngine.processObservation({+ source: obs.source,+ receivingAccountId: obs.receivingAccountId,+ amountPaise: obs.amountPaise,+ observedAt: obs.observedAt,+ bankReferenceNumber: obs.bankReferenceNumber,+ senderVpa: obs.senderVpa,+ rawPayload: obs.rawPayload,+ fingerprintHash: obs.fingerprintHash+ });+ } catch {+ // Silently absorb individual observation attribution failures to avoid interrupting poller loop+ } finally {+ this._inFlightObservationHashes.delete(hash);+ }+ }+ }+ } finally {+ this._isAttributionInProgress = false;+ }+ }+}diff --git a/apps/sms-observer/src/browser-automator.js b/apps/sms-observer/src/browser-automator.jsindex f4dadf0..5b7e7c4 100644--- a/apps/sms-observer/src/browser-automator.js+++ b/apps/sms-observer/src/browser-automator.js@@ -2,6 +2,7 @@ import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';import { BrowserLauncher } from '@youpi/observer-sdk';+import { getObserverToken } from '@youpi/common';import { BankSmsParser } from './sms-parser.js';const __filename = fileURLToPath(import.meta.url);@@ -39,7 +40,13 @@ export class GoogleMessagesAutomator {async fetchActivePaymentAmounts() {try {- const res = await fetch(`${this.apiBaseUrl}/api/v1/pollers/active-window`, { signal: AbortSignal.timeout(1500) });+ if (this.smsService && this.smsService.observerClient && typeof this.smsService.observerClient.getActiveWindow === 'function') {+ return await this.smsService.observerClient.getActiveWindow();+ }+ const res = await fetch(`${this.apiBaseUrl}/api/v1/pollers/active-window`, {+ headers: { 'Authorization': `Bearer ${getObserverToken()}` },+ signal: AbortSignal.timeout(1500)+ });if (res.ok) {const data = await res.json();return data.sessions || [];@@ -211,6 +218,7 @@ export class GoogleMessagesAutomator {// Target busy or initializing}}, 2000);+ if (this.checkTimer.unref) this.checkTimer.unref();}/**@@ -226,10 +234,15 @@ export class GoogleMessagesAutomator {// Target busy or updating}}, 3000);+ if (this.extractionTimer.unref) this.extractionTimer.unref();}async pollRecentMessages() {- const targets = await BrowserLauncher.getTargets(this.debuggingPort);+ if (this._isPollingMessages) return;+ this._isPollingMessages = true;++ try {+ const targets = await BrowserLauncher.getTargets(this.debuggingPort);const target = targets.find(t => (t.type === 'page' || !t.type) && t.url && t.url.includes('messages.google.com') && t.webSocketDebuggerUrl)|| targets.find(t => t.url && t.url.includes('messages.google.com') && t.webSocketDebuggerUrl);if (!target) return;@@ -335,6 +348,9 @@ export class GoogleMessagesAutomator {}}}+ } finally {+ this._isPollingMessages = false;+ }}getStatus() {diff --git a/apps/sms-observer/src/sms-service.js b/apps/sms-observer/src/sms-service.jsindex 62e228b..46224f6 100644--- a/apps/sms-observer/src/sms-service.js+++ b/apps/sms-observer/src/sms-service.js@@ -84,6 +84,7 @@ export class SmsObserverService {this.timer = setInterval(() => {this.pollCycle();}, this.pollIntervalMs);+ if (this.timer.unref) this.timer.unref();}stop() {diff --git a/scripts/test-all.js b/scripts/test-all.jsindex 7ba8d26..c18f436 100644--- a/scripts/test-all.js+++ b/scripts/test-all.js@@ -31,6 +31,7 @@ const testFiles = ['apps/payment-api/src/__tests__/whatsapp-berry-auth.test.js','apps/payment-api/src/__tests__/whitelabel-branding.test.js','apps/payment-api/src/__tests__/cod-parallel-timer-decoupling.test.js',+ 'apps/payment-api/src/__tests__/observer-poller.test.js','scripts/chaos-concurrency.test.js','scripts/production-infrastructure.test.js'];