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

Experimental getAsyncCtx() #776

Merged
merged 23 commits into from
Dec 12, 2024
Merged

Experimental getAsyncCtx() #776

merged 23 commits into from
Dec 12, 2024

Conversation

jpwilliams
Copy link
Member

@jpwilliams jpwilliams commented Dec 10, 2024

Summary

Adds a new getAsyncCtx() function exported from "inngest/experimental" that will attempt to retrieve the function input arguments.

  • Uses @inngest/test@workspace:^ internally, exclusively for the inngest package. This can be a bit weird, as inngest is a peer dep of @inngest/test so typing can be flaky.
  • Altered exports of @inngest/test to have simpler compilation and publishing.
  • Added the experimental getAsyncCtx()
import { getAsyncCtx } from "inngest/experimental";

const ctx = await getAsyncCtx();

Questions

  • Should we remove the store for a particular execution context when the run completes?
    No. It will still be garbage collected and info may still be useful.

Checklist

  • Added a docs PR that references this PR N/A Experimental for now
  • Added unit/integration tests
  • Added changesets if applicable

@jpwilliams jpwilliams self-assigned this Dec 10, 2024
Copy link

changeset-bot bot commented Dec 10, 2024

🦋 Changeset detected

Latest commit: 0796d70

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
inngest Minor
@inngest/test Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@inngest-release-bot inngest-release-bot added the 📦 inngest Affects the `inngest` package label Dec 10, 2024
@jpwilliams jpwilliams added 🧪 experimental The addition of a new experimental API, feature, or fix. prerelease/inngest Create snapshot releases for a PR for the "inngest" package. labels Dec 10, 2024
@inngest-release-bot
Copy link
Collaborator

inngest-release-bot commented Dec 10, 2024

A user has added the prerelease/inngest label, so this PR will be published to npm with the tag pr-776. It will be updated with the latest changes as you push commits to this PR.

You can install this prerelease version with:

npm install inngest@pr-776

The last release was built and published from 0796d70.

pnpm is a pain at not sharing versions between packages with differing
peer dependencies, resulting in packages utilizing >1 `inngest` package
internally.

This is exclusive to our monorepo here; in userland, the same package
will be shared.
Comment on lines +41 to +45
- name: Build test dependencies
if: ${{ inputs.install-dependencies == 'true' }}
run: pnpm run build
shell: bash
working-directory: ${{ inputs.working-directory }}/packages/test
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inngest now relies on @inngest/test@workspace:^, so we make sure that's built during CI too.

@@ -6,7 +6,7 @@ module.exports = {
roots: ["<rootDir>/src"],
moduleNameMapper: {
"(\\..+)\\.js": "$1",
inngest: "<rootDir>/src",
"^inngest$": "<rootDir>/src",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This regex was picking up anything containing inngest and redirecting it to src/ - bit of a problem when importing @inngest/test!

@@ -17,6 +17,7 @@
],
"exports": {
".": "./src/index.ts",
"./experimental": "./src/experimental.ts",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A new entrypoint to mark out experimental APIs.

Comment on lines 462 to +464
private async startExecution(): Promise<void> {
/**
* Mutate input as neccessary based on middleware.
*/
await this.transformInput();
return getAsyncLocalStorage().then((als) =>
als.run({ ctx: this.fnArg }, async (): Promise<void> => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When executing, we now wrap the entire operation in our AsyncLocalStorage.run() call. This also ensures that middleware is included in the async chain.

// eslint-disable-next-line @typescript-eslint/no-misused-promises, no-async-promise-executor
als ??= new Promise<AsyncLocalStorageIsh>(async (resolve) => {
try {
const { AsyncLocalStorage } = await import("node:async_hooks");
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bun, Deno, and Node all expose this as node:async_hooks.

Cloudflare Workers requires a compatibility flag of node_compat or node_compat_v2. A singular node_als should be possible but doesn't currently work with any version of Wrangler.

In the case that these flags have not been specified, this AsyncLocalStorage instance will essentially become a no-op; no store will ever be returned and .run() will just run the function given directly.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

On a side note, how many lines of code would it take you to do this in go!?

als ??= new Promise<AsyncLocalStorageIsh>(async (resolve) => ...

Comment on lines +21 to +26
/**
* Retrieve the async context for the current execution.
*/
export const getAsyncCtx = async (): Promise<AsyncContext | undefined> => {
return getAsyncLocalStorage().then((als) => als.getStore());
};
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only piece exposed to the public API, used to retrieve the input to the current function run.

Comment on lines +3 to +5
export interface AsyncContext {
ctx: Context.Any;
}
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If found, this is the value returned when a developer calls getAsyncCtx() in userland code. It will likely expand to contain more information over time.

Copy link
Contributor

@tonyhb tonyhb left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is AMAZING work!!!

@jpwilliams jpwilliams merged commit 0dbcc87 into main Dec 12, 2024
51 checks passed
@jpwilliams jpwilliams deleted the experimental/hooks branch December 12, 2024 15:51
jpwilliams pushed a commit that referenced this pull request Dec 12, 2024
This PR was opened by the [Changesets
release](https://github.com/changesets/action) GitHub action. When
you're ready to do a release, you can merge this and the packages will
be published to npm automatically. If you're not ready to do a release
yet, that's fine, whenever you add more changesets to main, this PR will
be updated.


# Releases
## [email protected]

### Minor Changes

- [#776](#776)
[`0dbcc87`](0dbcc87)
Thanks [@jpwilliams](https://github.com/jpwilliams)! - Add experimental
`getAsyncCtx()`, allowing the retrieval of a run's input (`event`,
`step`, `runId`, etc) from the relevant async chain.

    ```ts
    import { getAsyncCtx } from "inngest/experimental";

    const ctx = await getAsyncCtx();
    ```

### Patch Changes

- [#776](#776)
[`0dbcc87`](0dbcc87)
Thanks [@jpwilliams](https://github.com/jpwilliams)! - Use
`@inngest/test@workspace:^` internally for testing

## @inngest/[email protected]

### Patch Changes

- [#776](#776)
[`0dbcc87`](0dbcc87)
Thanks [@jpwilliams](https://github.com/jpwilliams)! - Altered exports
to now be namespaced by `./dist/`; if you have directly imported files
from `@inngest/test`, you may need to change the imports

- Updated dependencies
\[[`0dbcc87`](0dbcc87),
[`0dbcc87`](0dbcc87)]:
    -   [email protected]

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
jpwilliams added a commit that referenced this pull request Dec 12, 2024
## Summary
<!-- Succinctly describe your change, providing context, what you've
changed, and why. -->

Fixes `@inngest/test` releasing; there's no longer a `dist/` dir
following #776.

## Checklist
<!-- Tick these items off as you progress. -->
<!-- If an item isn't applicable, ideally please strikeout the item by
wrapping it in "~~"" and suffix it with "N/A My reason for skipping
this." -->
<!-- e.g. "- [ ] ~~Added tests~~ N/A Only touches docs" -->

- [ ] ~Added a [docs PR](https://github.com/inngest/website) that
references this PR~ N/A CI fix
- [ ] ~Added unit/integration tests~ N/A CI fix
- [ ] ~Added changesets if applicable~ N/A CI fix

## Related
<!-- A space for any related links, issues, or PRs. -->
<!-- Linear issues are autolinked. -->
<!-- e.g. - INN-123 -->
<!-- GitHub issues/PRs can be linked using shorthand. -->
<!-- e.g. "- inngest/inngest#123" -->
<!-- Feel free to remove this section if there are no applicable related
links.-->
- Bug introduced in #776
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🧪 experimental The addition of a new experimental API, feature, or fix. 📦 @inngest/middleware-validation 📦 @inngest/test 📦 inngest Affects the `inngest` package prerelease/inngest Create snapshot releases for a PR for the "inngest" package.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants