1. /**
  2. * Sanitizes metadata input for scheduled runs with retry logic.
  3. * @param {object} metadata - The input metadata object.
  4. * @returns {object} - The sanitized metadata object. Returns null if sanitization fails.
  5. */
  6. function sanitizeMetadata(metadata) {
  7. if (!metadata || typeof metadata !== 'object') {
  8. console.error("Invalid metadata input. Must be an object.");
  9. return null;
  10. }
  11. const sanitizedMetadata = {};
  12. for (const key in metadata) {
  13. if (metadata.hasOwnProperty(key)) {
  14. let value = metadata[key];
  15. // Sanitize string values
  16. if (typeof value === 'string') {
  17. value = value.trim(); // Remove leading/trailing whitespace
  18. if (value === '') {
  19. console.warn(`Skipping key "${key}" due to empty string value.`);
  20. continue; // Skip empty string
  21. }
  22. }
  23. // Sanitize numeric values
  24. if (typeof value === 'number') {
  25. value = Number(value); // Ensure it's a number. Handle possible NaN
  26. if (isNaN(value)) {
  27. console.warn(`Skipping key "${key}" due to invalid numeric value.`);
  28. continue;
  29. }
  30. }
  31. // Sanitize boolean values
  32. if (typeof value === 'boolean') {
  33. value = value.toLowerCase() === 'true'; //normalize boolean to lowercase true/false
  34. }
  35. sanitizedMetadata[key] = value;
  36. }
  37. }
  38. return sanitizedMetadata;
  39. }
  40. /**
  41. * Executes a task with retry logic.
  42. * @param {function} task - The task to execute.
  43. * @param {number} maxRetries - The maximum number of retries.
  44. * @param {number} delay - The delay between retries in milliseconds.
  45. * @returns {Promise<any>} - A promise that resolves with the task result or rejects after maxRetries.
  46. */
  47. async function executeWithRetry(task, maxRetries, delay) {
  48. let retries = 0;
  49. while (retries < maxRetries) {
  50. try {
  51. return await task(); // Execute the task
  52. } catch (error) {
  53. retries++;
  54. if (retries >= maxRetries) {
  55. console.error(`Task failed after ${maxRetries} retries:`, error);
  56. throw error; // Re-throw the error after max retries
  57. }
  58. console.warn(`Task failed. Retry attempt ${retries} in ${delay}ms.`);
  59. await new Promise(resolve => setTimeout(resolve, delay)); // Wait before retrying
  60. }
  61. }
  62. }
  63. export { sanitizeMetadata, executeWithRetry };

Add your comment