added short poll endpoint to be called after zap req broadcasted and will run for 120 seconds initially, long running cron will kick in after that

This commit is contained in:
austinkelsay 2024-11-08 14:03:53 -06:00
parent c350e43b7b
commit 4a5e427b26
No known key found for this signature in database
GPG Key ID: 44CB4EC6D9F2FA02
3 changed files with 55 additions and 24 deletions

View File

@ -0,0 +1,44 @@
import axios from "axios";
const PLEBDEVS_API_KEY = process.env.PLEBDEVS_API_KEY;
const BACKEND_URL = process.env.BACKEND_URL;
export default async function handler(req, res) {
// Verify API key
const apiKey = req.headers['authorization'];
if (!apiKey || apiKey !== PLEBDEVS_API_KEY) {
res.status(401).json({ error: 'Unauthorized' });
return;
}
try {
// Poll for 120 seconds maximum
const startTime = Date.now();
const timeoutDuration = 120000; // 120 seconds in milliseconds
while (Date.now() - startTime < timeoutDuration) {
const pollResponse = await axios.get(`${BACKEND_URL}/api/invoices/polling`, {
headers: {
'Authorization': PLEBDEVS_API_KEY
}
});
console.log('Polling response', pollResponse.data);
// If no pending invoices, we can stop polling
if (pollResponse.data.pending === 0) {
res.status(200).json({ success: true, settled: true });
return;
}
// Wait 1 second before next poll
await new Promise(resolve => setTimeout(resolve, 1000));
}
// If we reach here, we timed out
res.status(200).json({ success: true, settled: false });
} catch (error) {
console.error('Polling error:', error);
res.status(500).json({ error: 'Polling failed' });
}
}

View File

@ -78,30 +78,17 @@ export default async function handler(req, res) {
settled: false
}, { ex: expiry || 86400 });
// Start polling for this zap request
let attempts = 0;
console.log('Starting polling interval', attempts);
const pollInterval = setInterval(async () => {
console.log('Polling for invoice', attempts);
try {
const pollResponse = await axios.get(`${BACKEND_URL}/api/invoices/polling`, {
headers: {
'Authorization': PLEBDEVS_API_KEY
}
});
console.log('Polling response', pollResponse.data);
// If no pending invoices or we've reached max attempts, stop polling
if (pollResponse.data.pending === 0 || attempts >= 120) {
clearInterval(pollInterval);
// Trigger the polling endpoint
try {
await axios.get(`${BACKEND_URL}/api/invoices/short-poll`, {
headers: {
'Authorization': PLEBDEVS_API_KEY
}
attempts++;
} catch (error) {
console.error('Polling error:', error);
clearInterval(pollInterval);
}
}, 1000); // Poll every second
});
} catch (error) {
console.error('Error triggering polling:', error);
// Continue even if polling fails
}
res.status(200).json({
invoice,

View File

@ -11,7 +11,7 @@
}
],
"functions": {
"src/pages/api/invoices/polling.js": {
"src/pages/api/invoices/short-poll.js": {
"maxDuration": 120
}
}