Skip to content

[RFC] Add middleware next()-fn - #718

Merged
KATT merged 23 commits into
mainfrom
feature/middleware-next
Aug 20, 2021
Merged

KATT merged 23 commits into
mainfrom
feature/middleware-next

Conversation

@KATT

@KATT KATT commented Jul 24, 2021 •

Copy link
Copy Markdown
Member

Middlewares will now have to call a next() function that you have to call.

Example

A middleware that measures the time of procedures

.middleware(async ({ ctx, path, next }) => {
  const start = Date.now()
  await next()
  const end = Date.now()
  console.log({path, took: end - start})
})

@mmkal @delaneyj - you've both championed this. I really don't like my implementation of the recursive async/await spaghetti, I wrote it in like 5 minutes, but the tests pass and it seems to work. You're both added as contributors so you can update the branch directly, would be great if one of you could clean up my implementation.


Todos

  • First draft
  • Add tests
  • Make a prettier implementation
  • Update docs
  • Update examples

Closes #564 #586 #564

@vercel

vercel Bot commented Jul 24, 2021 •

Copy link
Copy Markdown

@KATT
KATT requested a review from delaneyj July 24, 2021 17:49
@KATT KATT added the ⏭ major bump needed Requires a major version bump label Jul 24, 2021
@KATT KATT changed the title [RFC] ⚠️ Breaking change ⚠️ add middleware next()-fn [RFC] Add middleware next()-fn Jul 24, 2021
Comment thread www/docs/server/middlewares.md Resolved
@simonedelmann

Copy link
Copy Markdown
Contributor

I won't have time to review the code properly in the next days, sorry.

But I have a question about the purpose of the PR:

Currently a middleware has 2 states: success (fn returns) and failure (fn throws).

With this PR a middleware now gets a third state: whenever neither next() will be called nor an error will be thrown. I assume an unspecific error ("Missing next() call") will be thrown then?

I am not sure if this improves the user experience of tRPC or just makes it more complicated. You still cannot reuse express middlewares for example, because in our middlewares you don't have access to req and res.

I am sure there is some kind of benefit in this, which I am currently missing. ;)

@mmkal

mmkal commented Jul 24, 2021

Copy link
Copy Markdown
Contributor

@KATT thanks for adding me as a collaborator! I do have some untested ideas about how to implement this, as well as how to ensure that each middleware calls next exactly once at runtime and at the type-level. I was thinking of an approach using .reduce, but I will take a closer look at what you have here at some point this weekend. One note: I think it's important that the next() call always has an await or return, since downstream middleware might be async.

@simonedelmann I requested this because it can enable a bunch of use cases:

  • logging procedure calls in a standardized way to stdout
  • automatically sending timing metrics to tools like datadog
  • sending any thrown errors to sentry/other bug tracking tools
  • adding context to AsyncLocalStorage
  • possibly even transforming responses, though there may be better ways to do that already

With the right design, each of these could be implemented as a separate middleware function, and any combination of them would work together.

But yes, these wouldn't be 1-1 with express middleware. IMO that's ok because express middleware are kinda badly designed, using callbacks not promises. Koa has some pretty good docs on why. This design seems closer to koa.

@simonedelmann

Copy link
Copy Markdown
Contributor

Thanks @mmkal ! Totally convinced ;)

@KATT

KATT commented Jul 25, 2021

Copy link
Copy Markdown
Member Author

One note: I think it's important that the next() call always has an await or return, since downstream middleware might be async.

My implementation was that middlewares conform to () => Promise<void> | void - is this what you mean?

  • logging procedure calls in a standardized way to stdout

💯

  • automatically sending timing metrics to tools like datadog

💯

  • sending any thrown errors to sentry/other bug tracking tools

This is not the role of the type of middleware implementation I thought and rather something I'd use error reporting for.

💯

  • possibly even transforming responses, though there may be better ways to do that already

This should not be done in middlewares as far as I can tell and there's already support for this with data transformers.

A request can contain N requests to the same procedure which would all be passed through middlewares.

What you are looking for here is probably some over-arching middleware support on the request handler, so responses can be intersected before getting passed through res.send(). I've actually thought of a little refactoring here in order to be able to support SvelteKit endpints

But yes, these wouldn't be 1-1 with express middleware. IMO that's ok because express middleware are kinda badly designed, using callbacks not promises. Koa has some pretty good docs on why. This design seems closer to koa.

💯 This is also why I was okay with having the existing middleware implementation not having a next()-function, as the definition of a middleware is a bit wider than what we're used to in Node.js-land.

@KATT

KATT commented Jul 26, 2021

Copy link
Copy Markdown
Member Author

@mmkal (when) do you think you will have a stab at this?

@mmkal

mmkal commented Jul 26, 2021

Copy link
Copy Markdown
Contributor

@KATT I've set aside some time on Wednesday. If you're ok to wait until then? If not totally your call of course!

@mmkal

mmkal commented Jul 28, 2021 •

Copy link
Copy Markdown
Contributor

@KATT I pushed a change. I squashed into a single commit (8a028fb) so it's easy to revert if you don't like the implementation. I can also break this out into a separate branch if you'd like to do a side-by-side comparison.

The key change is: middlewares now have to pass on (return) the result from their next() function. Doing this means we can rely on typescript for a lot more correctness-checking. this.resolver gets wrapped to become the last middleware, effectively - the one that provides the actual output.

We don't really need as much bookkeeping, like try/catch wrappers or to check for calling next() twice anymore, because doing that would already stick out as an error:

router
  .middleware(async ({ next }) => {
    const first = await next()
    const second = await next()

    // which one should be returned??
  })

I also added a test using async_hooks and it works as expected.

I made middleware next functions always return a Promise, since they can't know whether downstream middlewares are sync or async.

I updated the docs that I found that used .middleware, but please let me know if there are others that I missed.


Re error reporting, a pattern I've seen used before (admittedly for a probably overcomplicated architecture) was to throw a "recoverable" error - you could imagine a middleware that could do something like:

router
  .middleware(async ({ ctx, path, type, next }) => {
    try {
      return next()
    } catch (e) {
      if (e instanceof RecoverableError) {
        // maybe service a failed, but we can fall back on service b which is slower/less ideal in some way
        myErrorLogger.log(e, {ctx, path, type})
        return e.recover()
      }
      throw e
    }
  })

This should now be doable, although I think it's reasonable to let users figure out for themselves since everything interesting is really happening in the .recover() method.

@mmkal

mmkal commented Aug 12, 2021

Copy link
Copy Markdown
Contributor

@KATT just to check - are you waiting on any more feedback from me on this? We're happily on the 9.0.0-alpha.0 version for now but don't want to miss out on other features!

Also re the conflicts, in case this is helpful, I use these commands sometimes to publish branch-specific canary releases from lerna without editing the actual package.json files/creating a commit. The dist-tag is the branch name. It generates a long, ugly version string including the branch, commit date and hash, so you might want to tweak/YMMV:

    "commit-date": "git log -n 1 --date=format:'%Y-%m-%d-%H-%M-%S' --pretty=format:'%ad'",
    "canary-preid": "echo \"$(yarn --silent current-branch)-$(yarn --silent commit-date)\"",
    "current-branch": "echo \"$(git rev-parse --abbrev-ref HEAD)\" | sed -E 's/refs\\/heads\\///' | sed -E 's/\\W|_/-/g'",
    "publish-canary": "lerna publish --canary --preid $(yarn --silent canary-preid) --dist-tag $(yarn --silent current-branch)",

Sample yarn publish-canary output in my repo:

Found 1 package to publish:
 - @slonik/migrator => 0.8.5-lock-transaction-fix-2021-08-11-14-47-52.6+c9cb3ff

? Are you sure you want to publish these packages? (ynH) 

@KATT

KATT commented Aug 15, 2021

Copy link
Copy Markdown
Member Author

I'm happy with this PR.

Why it's not merged is that I'm spending some time finding other things that requires some breaking changes here and there too and doing them as well.

See the v9 milestone. Also, if you've noticed any other structural stuff that you think we should change, this is a good opportunity to do so ☺

@KATT KATT mentioned this pull request Aug 15, 2021
@KATT KATT added the 🙏 review please needs community sign-off label Aug 15, 2021
@KATT
KATT marked this pull request as ready for review August 18, 2021 16:14
@KATT
KATT changed the base branch from main to feature/next-major August 19, 2021 15:14
@KATT
KATT changed the base branch from feature/next-major to main August 19, 2021 15:14
KATT added 2 commits August 20, 2021 12:06
# Conflicts:
#	examples/.wip/next-chat/package.json
#	examples/express-server/package.json
#	examples/next-prisma-starter-websockets/package.json
#	examples/next-prisma-starter/package.json
#	examples/next-prisma-todomvc/package.json
#	examples/standalone-server/package.json
#	lerna.json
#	packages/client/package.json
#	packages/next/package.json
#	packages/react/package.json
#	packages/server/package.json

This branch was successfully deployed

2 active deployments
Preview – todomvc — 9db70903 Deployed Aug 20, 2021 by vercel[bot]
Preview – www — 9db70903 Deployed Aug 20, 2021 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

⏭ major bump needed Requires a major version bump 🙏 review please needs community sign-off @trpc/server

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Middleware next?

5 participants