Created
January 28, 2020 06:57
-
-
Save bsdahl/0f05a64dee084be60f5bd199ff9b1ccf to your computer and use it in GitHub Desktop.
Watchdog timeout utility for aws serverless applications.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function watchDog(event, context) { | |
let messageStack = []; | |
let timeoutId; | |
const push = function(message) { | |
messageStack.push(message); | |
}; | |
const setupTimer = function(event, context, callback) { | |
messageStack.push('Start'); | |
const timeoutHandler = () => { | |
console.error( | |
'WatchDog timed out: ', | |
readable(messageStack), | |
readable(event), | |
readable(context) | |
); | |
if (typeof callback === 'function') { | |
callback(); | |
} | |
}; | |
timeoutId = setTimeout(timeoutHandler, context.getRemainingTimeInMillis() - 1000); | |
}; | |
const end = function() { | |
clearTimeout(timeoutId); | |
}; | |
setupTimer(event, context); | |
return Object.freeze({ | |
push: push, | |
end: end, | |
}); | |
} | |
function readable(obj) { | |
if (typeof obj === 'string') { | |
return obj; | |
} | |
try { | |
return JSON.stringify(obj, null, 2); | |
} catch (err) { | |
return String(obj); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage inside a lambda handler.