Skip to content

Instantly share code, notes, and snippets.

@bsdahl
Created January 28, 2020 06:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsdahl/0f05a64dee084be60f5bd199ff9b1ccf to your computer and use it in GitHub Desktop.
Save bsdahl/0f05a64dee084be60f5bd199ff9b1ccf to your computer and use it in GitHub Desktop.
Watchdog timeout utility for aws serverless applications.
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);
}
}
@bsdahl
Copy link
Author

bsdahl commented Jan 28, 2020

Example usage inside a lambda handler.

export const handler = function(event, context) {
  const WatchDog = new watchDog(event, context);

  WatchDog.push('Example');

  WatchDog.end();

  return {};
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment