Fixes agent calls and adds error reporting

main
Yasen Pramatarov 2024-09-30 11:09:01 +03:00
parent e1888cce8a
commit 37398b5986
4 changed files with 85 additions and 15 deletions

View File

@ -123,15 +123,20 @@ class Agent {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $agent[0]['url']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // timeout 10 seconds
$response = curl_exec($ch);
$curl_error = curl_error($ch); // curl error for debugging
curl_close($ch);
// Cache the result and the timestamp if the response is successful
if ($response !== false) {
$_SESSION[$agent_cache_name] = $response;
$_SESSION[$agent_cache_time] = time();
} else {
$response = "Error: " . $curl_error;
}
return $response;
}

View File

@ -10,8 +10,11 @@ $agentObject = new Agent($dbWeb);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// FIXME code here
// header("Location: $app_root?platform=$platform_id&page=config");
// exit();
$force = isset($_POST['force']) && $_POST['force'] == 'true';
$agent_id = $_POST['agent'];
$result = fetchAgent($agent_id, $force);
if ($result !== false) {
@ -20,9 +23,6 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo json_encode(['error' => 'Failed to fetch API data']);
}
// header("Location: $app_root?platform=$platform_id&page=config");
// exit();
// no form submitted, show the templates
} else {
$agentDetails = $agentObject->getAgentDetails($platform_id);

View File

@ -6,10 +6,10 @@
<?php foreach ($agentDetails as $agent) { ?>
<p class="card-text">
agent id<?= htmlspecialchars($agent['id']) ?>: type <?= htmlspecialchars($agent['agent_type_id']) ?>, url <?= htmlspecialchars($agent['url']) ?>
<button onclick="fetchData()">fetch data</button>
<button onclick="fetchData(true)">force refresh</button>
<button onclick="fetchData('<?= htmlspecialchars($agent['id']) ?>', '<?= htmlspecialchars($agent['url']) ?>')">fetch data</button>
<button onclick="fetchData('<?= htmlspecialchars($agent['id']) ?>', '<?= htmlspecialchars($agent['url']) ?>', true)">force refresh</button>
</p>
<p>Result:</p>
<pre id="result">click a button to fetch data from the agent.</pre>
<pre id="result<?= htmlspecialchars($agent['id']) ?>">click a button to fetch data from the agent.</pre>
<?php } ?>

View File

@ -1,20 +1,85 @@
function fetchData(force = false) {
function fetchData(agent_id, url, force = false) {
let counter = 0;
const resultElement = document.getElementById("result" + agent_id);
// Show loading text
document.getElementById("result").innerHTML = "Loading...";
resultElement.innerHTML = "Loading... (0 seconds)";
// Create an interval to update the counter every second
const intervalId = setInterval(() => {
counter++;
resultElement.innerHTML = `Loading... (${counter} seconds)`;
}, 1000);
// Create an AJAX request
var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php?page=agents", true);
// Handle invalid URL error
try {
xhr.open("POST", url, true);
} catch (e) {
clearInterval(intervalId); // Stop the counter on error
resultElement.innerHTML = `Error: Invalid URL ${url}<br />` + e.message;
return; // Exit the function early
}
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Set a timeout in milliseconds (10 seconds = 10000 ms)
xhr.timeout = 10000;
// Handle the request state change
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
if (xhr.readyState === 4) {
clearInterval(intervalId); // Stop the counter when the request completes
clearTimeout(requestTimeout); // Clear the timeout if response is received
if (xhr.status === 200) {
try {
// Parse and display the result
let result = JSON.parse(xhr.responseText);
document.getElementById("result").innerHTML = JSON.stringify(result, null, 2);
resultElement.innerHTML = JSON.stringify(result, null, 2);
} catch (e) {
// Display the error
resultElement.innerHTML = "Error: Response is not a valid JSON.<br />Response: " + xhr.responseText;
}
} else {
resultElement.innerHTML = `Error: Unable to fetch data from ${url}<br />Status Code: ${xhr.status}<br />Status Text: ${xhr.statusText}<br />Response: ${xhr.responseText}`;
}
}
};
// Handle network-level errors (e.g., connection refused)
xhr.onerror = function() {
clearInterval(intervalId); // Stop the counter on error
resultElement.innerHTML = `Network Error:<br />Unable to connect to ${url}<br />Check network connection or try again later.`;
};
// Handle the timeout event
xhr.ontimeout = function() {
clearInterval(intervalId); // Stop the counter on timeout
resultElement.innerHTML = "Request timed out. Please try again.";
};
// Additional manual timeout
var requestTimeout = setTimeout(function() {
if (xhr.readyState !== 4) {
xhr.abort(); // Abort the request if still pending after timeout
clearInterval(intervalId); // Stop the counter
resultElement.innerHTML = "Request timed out.";
}
}, 10000); // 10 seconds
// Send the AJAX request, with force flag
xhr.send("action=fetch&force=" + (force ? 'true' : 'false'));
xhr.send("action=fetch&agent_id=" + agent_id + "&force=" + (force ? 'true' : 'false'));
// // If the request finishes quickly, set this up to show at least 1 second delay
// setTimeout(function() {
// if (counter === 0) {
// counter++;
// resultElement.innerHTML = `Loading... (${counter} seconds)`;
// }
// }, 1000); // Simulate a minimum 1 second delay for testing
}