Add SMS rate-limit retry queue
Browse files1234561 unmodified line891011121314151617181920212223242526272829303132333435363738394041424344454647484950const axios = require('axios');const db = require('../config/db');function normalizePhone(phone) {const d = phone.replace(/\D/g, '');if (d.startsWith('255')) return '+' + d;1 unmodified linereturn '+255' + d;}async function sendSMS(phone, message) {const to = normalizePhone(phone);let status = 'sent';let gatewayId = null;let error = null;try {const res = await axios.post(process.env.SMS_GATEWAY_URL,{textMessage: { text: message },phoneNumbers: [to],withDeliveryReport: false,},{auth: {username: process.env.SMS_GATEWAY_USER,password: process.env.SMS_GATEWAY_PASS,},timeout: 10000,});gatewayId = res.data?.id || null;console.log(`[SMS] Sent to ${to}: "${message.slice(0, 40)}..."`);} catch (err) {status = 'failed';error = err.message;console.error(`[SMS] Failed to ${to}:`, err.message);}// Fire-and-forget logdb.query('INSERT INTO sms_log (phone, message, status, gateway_id, error) VALUES (?, ?, ?, ?, ?)',[to, message, status, gatewayId, error]).catch(() => {});return status === 'sent';}module.exports = { sendSMS };12345678910111213141 unmodified line161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122const axios = require('axios');const db = require('../config/db');const SEND_INTERVAL_MS = Number(process.env.SMS_SEND_INTERVAL_MS || 1500);const MAX_ATTEMPTS = Number(process.env.SMS_MAX_ATTEMPTS || 3);const RATE_LIMIT_BACKOFF_MS = Number(process.env.SMS_RATE_LIMIT_BACKOFF_MS || 15000);const MAX_BACKOFF_MS = Number(process.env.SMS_MAX_BACKOFF_MS || 30000);let sendQueue = Promise.resolve();let lastSendAt = 0;function normalizePhone(phone) {const d = phone.replace(/\D/g, '');if (d.startsWith('255')) return '+' + d;1 unmodified linereturn '+255' + d;}function delay(ms) {return new Promise(resolve => setTimeout(resolve, ms));}function errorDetails(err) {const statusCode = err.response?.status;const body = err.response?.data;const bodyText = body? ` body=${typeof body === 'string' ? body : JSON.stringify(body).slice(0, 180)}`: '';return `${err.message}${statusCode ? ` status=${statusCode}` : ''}${bodyText}`.slice(0, 255);}function retryAfterMs(err) {const retryAfter = err.response?.headers?.['retry-after'];if (!retryAfter) return null;const seconds = Number(retryAfter);if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);const dateMs = Date.parse(retryAfter);if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now());return null;}async function waitForTurn() {const elapsed = Date.now() - lastSendAt;const waitMs = Math.max(0, SEND_INTERVAL_MS - elapsed);if (waitMs > 0) await delay(waitMs);lastSendAt = Date.now();}async function postSMS(to, message) {await waitForTurn();const res = await axios.post(process.env.SMS_GATEWAY_URL,{textMessage: { text: message },phoneNumbers: [to],withDeliveryReport: false,},{auth: {username: process.env.SMS_GATEWAY_USER,password: process.env.SMS_GATEWAY_PASS,},timeout: 10000,});return res.data?.id || null;}async function sendWithRetry(to, message) {let lastError = null;for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {try {return { sent: true, gatewayId: await postSMS(to, message), error: null };} catch (err) {lastError = err;const statusCode = err.response?.status;const isRateLimited = statusCode === 429;const canRetry = isRateLimited && attempt < MAX_ATTEMPTS;if (!canRetry) break;const gatewayWait = retryAfterMs(err);const backoffMs = Math.min(gatewayWait || RATE_LIMIT_BACKOFF_MS * attempt, MAX_BACKOFF_MS);console.warn(`[SMS] Rate limited for ${to}; retrying attempt ${attempt + 1}/${MAX_ATTEMPTS} in ${backoffMs}ms`);await delay(backoffMs);}}return { sent: false, gatewayId: null, error: errorDetails(lastError) };}async function sendNow(phone, message) {const to = normalizePhone(phone);const result = await sendWithRetry(to, message);const status = result.sent ? 'sent' : 'failed';if (result.sent) {console.log(`[SMS] Sent to ${to}: "${message.slice(0, 40)}..."`);} else {console.error(`[SMS] Failed to ${to}:`, result.error);}db.query('INSERT INTO sms_log (phone, message, status, gateway_id, error) VALUES (?, ?, ?, ?, ?)',[to, message, status, result.gatewayId, result.error]).catch(() => {});return result.sent;}async function sendSMS(phone, message) {const queued = sendQueue.then(() => sendNow(phone, message));sendQueue = queued.catch(() => {});return queued;}module.exports = { sendSMS };
src/services/sms.js+101-29