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

Feature: Handover the message for the middleware for the on_receive method #2070

Open
pafi-code opened this issue Feb 14, 2025 · 0 comments
Open
Labels
enhancement New feature or request

Comments

@pafi-code
Copy link

Is your feature request related to a problem? Please describe.

So implemented a middleware that injects the correlation id of the message to my loggers via contextvars. Initially I used the on_consume and after_consume for this. However the issue was that in case an error happend at input validation then my logger wouldn't have the correlation_id since on_consume seems to happen after input validation.
So now I'm using on_receive and after_processed. However for these message I only have access to the middleware via instanceattribute self.msg. The issue with this one is the type. In the BaseMiddleware we have self.msg: Optional[Any]. So since I can't really expect anything from it, I have to do ugly checks for if the msg isn't None and of a specific type.

Describe the solution you'd like

So it would be more convenient if this function could have a similar interface as on_consume or the typing of self.msg could be more specific.

Describe alternatives you've considered
For now I'm doing the ugly checks :D

async def on_receive(self):
        """Add the correlation id the the context on receive."""
        try:
            if (
                isinstance(self.msg, aio_pika.IncomingMessage)
                and self.msg.correlation_id is not None
            ):
                formated_correlation_id = self.msg.correlation_id.replace("-", "")
                self._token = context.correlation_id.set(formated_correlation_id)
        except Exception as error:
            _LOGGER.error(error)
            # We don't want the middleware to crash the service in case
            # something goes wrong.
            pass
        return await super().on_receive()
@pafi-code pafi-code added the enhancement New feature or request label Feb 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
Status: No status
Development

No branches or pull requests

1 participant