|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const axios = require('axios') |
| 4 | +const https = require('https') |
| 5 | +let cachedToken = null |
| 6 | +let tokenExpiry = null |
| 7 | +const CPX_METEOALARM_API_URL = process.env.CPX_METEOALARM_API_URL |
| 8 | +const CPX_METEOALARM_API_USERNAME = process.env.CPX_METEOALARM_API_USERNAME |
| 9 | +const CPX_METEOALARM_API_PASSWORD = process.env.CPX_METEOALARM_API_PASSWORD |
| 10 | +const MAX_RETRIES = 3 |
| 11 | +const config = { |
| 12 | + retryDelayMultiplier: 1000 // Default 1000ms, can be overridden for testing |
| 13 | +} |
| 14 | + |
| 15 | +const getValidToken = async () => { |
| 16 | + // Check if we have a cached token that hasn't expired |
| 17 | + if (cachedToken && tokenExpiry && new Date() < tokenExpiry) { |
| 18 | + return cachedToken |
| 19 | + } |
| 20 | + |
| 21 | + try { |
| 22 | + const response = await axios.post(`${CPX_METEOALARM_API_URL}/tokens`, { |
| 23 | + username: CPX_METEOALARM_API_USERNAME, |
| 24 | + password: CPX_METEOALARM_API_PASSWORD |
| 25 | + }, { |
| 26 | + headers: { |
| 27 | + 'Content-Type': 'application/json' |
| 28 | + }, |
| 29 | + httpsAgent: new https.Agent({ |
| 30 | + rejectUnauthorized: false |
| 31 | + }) |
| 32 | + }) |
| 33 | + |
| 34 | + if (response.status !== 200) { |
| 35 | + throw new Error(`Failed to authenticate: ${response.status} ${response.statusText}`) |
| 36 | + } |
| 37 | + |
| 38 | + cachedToken = response.data.token |
| 39 | + // Set token expiry to 1 hour from now |
| 40 | + tokenExpiry = new Date(Date.now() + 3600000) |
| 41 | + return cachedToken |
| 42 | + } catch (err) { |
| 43 | + console.error('Error fetching bearer token:', err.message) |
| 44 | + throw new Error(`Failed to authenticate with Meteoalarm: ${err.message}`) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +const postWarning = async (xmlMessage, identifier) => { |
| 49 | + let lastError = null |
| 50 | + for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) { |
| 51 | + try { |
| 52 | + const token = await getValidToken() |
| 53 | + const response = await axios.post(`${CPX_METEOALARM_API_URL}/warnings`, xmlMessage, { |
| 54 | + headers: { |
| 55 | + Authorization: `Bearer ${token}`, |
| 56 | + 'Content-Type': 'application/xml' |
| 57 | + }, |
| 58 | + timeout: 10000, |
| 59 | + httpsAgent: new https.Agent({ |
| 60 | + rejectUnauthorized: false |
| 61 | + }) |
| 62 | + }) |
| 63 | + |
| 64 | + if (response.status === 201) { |
| 65 | + console.log(`Successfully posted warning to Meteoalarm: ${identifier}`) |
| 66 | + console.log(response.data) |
| 67 | + return response.data |
| 68 | + } |
| 69 | + throw new Error(`Received non-201 response: ${response.status}`) |
| 70 | + } catch (err) { |
| 71 | + lastError = err |
| 72 | + console.error(`Meteoalarm post attempt ${attempt} failed: ${err.message}`) |
| 73 | + if (err.response?.data) { |
| 74 | + console.error(JSON.stringify(err.response.data)) |
| 75 | + } |
| 76 | + |
| 77 | + // If it's a 401 error, clear the cached token and retry |
| 78 | + if (err.response?.status === 401) { |
| 79 | + console.log('Received 401, clearing cached token') |
| 80 | + cachedToken = null |
| 81 | + tokenExpiry = null |
| 82 | + } |
| 83 | + |
| 84 | + // If this isn't the last attempt, wait before retrying |
| 85 | + if (attempt < MAX_RETRIES) { |
| 86 | + const delayMs = attempt * config.retryDelayMultiplier |
| 87 | + console.log(`Waiting ${delayMs}ms before retry...`) |
| 88 | + await new Promise(resolve => setTimeout(resolve, delayMs)) |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + throw new Error(`Failed to post warning to Meteoalarm after ${MAX_RETRIES} attempts: ${lastError.message}`) |
| 93 | +} |
| 94 | + |
| 95 | +const clearTokenCache = () => { |
| 96 | + cachedToken = null |
| 97 | + tokenExpiry = null |
| 98 | +} |
| 99 | + |
| 100 | +const setRetryDelayMultiplier = (multiplier) => { |
| 101 | + config.retryDelayMultiplier = multiplier |
| 102 | +} |
| 103 | + |
| 104 | +module.exports = { |
| 105 | + postWarning, |
| 106 | + clearTokenCache, |
| 107 | + // Export for testing |
| 108 | + getValidToken, |
| 109 | + setRetryDelayMultiplier |
| 110 | +} |
0 commit comments