/**
* Sanitizes metadata input for scheduled runs with retry logic.
* @param {object} metadata - The input metadata object.
* @returns {object} - The sanitized metadata object. Returns null if sanitization fails.
*/
function sanitizeMetadata(metadata) {
if (!metadata || typeof metadata !== 'object') {
console.error("Invalid metadata input. Must be an object.");
return null;
}
const sanitizedMetadata = {};
for (const key in metadata) {
if (metadata.hasOwnProperty(key)) {
let value = metadata[key];
// Sanitize string values
if (typeof value === 'string') {
value = value.trim(); // Remove leading/trailing whitespace
if (value === '') {
console.warn(`Skipping key "${key}" due to empty string value.`);
continue; // Skip empty string
}
}
// Sanitize numeric values
if (typeof value === 'number') {
value = Number(value); // Ensure it's a number. Handle possible NaN
if (isNaN(value)) {
console.warn(`Skipping key "${key}" due to invalid numeric value.`);
continue;
}
}
// Sanitize boolean values
if (typeof value === 'boolean') {
value = value.toLowerCase() === 'true'; //normalize boolean to lowercase true/false
}
sanitizedMetadata[key] = value;
}
}
return sanitizedMetadata;
}
/**
* Executes a task with retry logic.
* @param {function} task - The task to execute.
* @param {number} maxRetries - The maximum number of retries.
* @param {number} delay - The delay between retries in milliseconds.
* @returns {Promise<any>} - A promise that resolves with the task result or rejects after maxRetries.
*/
async function executeWithRetry(task, maxRetries, delay) {
let retries = 0;
while (retries < maxRetries) {
try {
return await task(); // Execute the task
} catch (error) {
retries++;
if (retries >= maxRetries) {
console.error(`Task failed after ${maxRetries} retries:`, error);
throw error; // Re-throw the error after max retries
}
console.warn(`Task failed. Retry attempt ${retries} in ${delay}ms.`);
await new Promise(resolve => setTimeout(resolve, delay)); // Wait before retrying
}
}
}
export { sanitizeMetadata, executeWithRetry };
Add your comment