Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add callback for invocation end with streaming functions #245

Merged
merged 6 commits into from
Apr 13, 2024

Conversation

Skn0tt
Copy link
Contributor

@Skn0tt Skn0tt commented Apr 11, 2024

Streaming functions can end the response stream before they finish their invocation. Here's an example function where this applies:

export const handler = awslambda.streamifyResponse(async (event, responseStream) => {
  responseStream.write("<html>...")
  const data = await fetchFromDB(...)
  responseStream.write(data.as_html())
  responseStream.write("<footer>...")
  responseStream.end()

  await trackRequestInAnalytics()
});

If we want to test that this works as intended, we need to ensure that the Lambda continues running after the response stream ended.

For most Lambdas, that's straightforward because the Lambda is killed immediately after the response is sent. Checking if all required work was completed once opts.callback is called is sufficient in that case.

For streaming Lambdas though, opts.callback is already called when the response headers are sent (aka when .write is first called). This is much earlier, and the Lambda can still perform operations after that.

This PR adds a onInvocationEnd callback that gets notified when the Promise returned by the handler resolves. At this point, all operations should be completed, because AWS might kill the Lambda afterwards. onInvocationEnd can be used in testing to ensure that's the case.

@Skn0tt
Copy link
Contributor Author

Skn0tt commented Apr 11, 2024

3c62e71 is published under https://www.npmjs.com/package/@skn0tt/lambda-local/v/2.1.2 for anybody who needs this right now.

@gpotter2 gpotter2 merged commit 5ad5685 into ashiina:develop Apr 13, 2024
7 checks passed
@gpotter2
Copy link
Collaborator

Thanks for the PR !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants