Repository navigation
Fix running hook issue and signal proxyserver updates. - #5512
Conversation
|
Thanks for all the great PRs!
That's a tricky problem and one that I brought up here #5288 (comment) . I am essentially using
Depends on the definition of "in sync", the UI would basically hide a listener. What I would love to see is each mode having a state. So that the mitmproxy UI (and my UI) can show you something like this: A new hook that tells us if any of the listeners' state changed would allow mitmproxy and me to react to it and update the UI. In my UI the user could then for example change the port of one of the listeners and tell mitmproxy about the new modes. One thing that would be important as well is "retry". So if one listener failed because the port wasn't available and I made it available, then I would expect to be able to tell mitmdump to try again. This could be as simple as |
That's a great idea.
That makes a lot more sense than my suggestion (which was rooted in If that sounds fine to everyone, I'm going to implement these changes. Any suggestions for the name of the hook? |
Startup HookI'm not sure if there's much of a use case outside of the proxyserver addon? Or differently, is there a plausible scenario why an addon other than Listener StateThis discussion is kind of adjacent to this PR, but overall that sounds good to me. It probably make sense to eventually have a self-updating
I would try to keep things as simple as possible here for now until we find out we have super special needs when building out the UI. In the simplest case, we could just notify everyone once
if shutdown fails I propose we just
Setting options to their current value does not trigger a |
Did you see my comment on the original PR? #5393 (comment) I know this is yet another discussion, but I just wanted to bring that up one last time. The discussion in this PR alone has shown to be that "mode" is not the correct terminology. They are listeners. Things like "starting the new mode" sounds odd to me. Listeners have a mode or are of a mode type.
That sounds a little backwards to me. Couldn't this empty "something has changed" just collect the state and send that instead of being empty? This sounds like you want to force mitmweb/mitmproxy to do a pull instead of doing a push.
I don't understand that part. No matter if we pull the state or the core pushes it, you still need a copy for rendering? As I said, to me this is just the difference between push and pull, the implementation of the other end will use the data in the exact same way. So for mitmweb the React component holds a copy anyway, it doesn't matter if it arrived there using a push (we already have a WebSocket) or a pull via I don't know if that makes sense? I'd like to see a |
From a UX point I'd love to have these states. That's the difference between clicking a button and after 700 confusing milliseconds the state changes from "stopped" to "started" and clicking a button and instantly getting feedback via "starting...". Yes, this could probably be simulated on each UI end, but we already have that information. |
On a greenfield I'd definitely opt for something else than
Let's take mitmweb: If a new browser window connects we need to deliver the current state to that browser instance (technically, the browser requests it). For that you either need to ask the proxyserver addon for the current state, or you need to remember the last state that was published ("keep a copy of the listener states"). So we need/want pull anyways. Does that make sense now?
Maybe a second generic "state updated" event within |
I still can't really follow 😄 . What keeps mitmweb from opening a WebSocket which would give you the current state and in the future all changes? How is the first "message" event different from a response using
I honestly still don't know what you mean with remember in this case. But maybe I'm misunderstanding the internals of mitmproxy. Is mitmproxy not able to ad-hoc tell me the current state of all listeners? Is this info only available when something changes? But even that wouldn't make sense, given you want to pull that data ad-hoc 🤔 |
Yes. The React code would/should do that, but then the Python API endpoint handler needs to obtain the state from somewhere (or remember the latest update). 😄 I'm talking about the Proxyserver <-> mitmweb REST API addon interaction, not the REST API <-> web client part. Does that make sense now? The Proxyserver addon notifies the REST API addon via a |
|
Alright, I think I see the problem here. I just looked at the dev tools in mitmweb. I had no idea about it's architecture. It looks like mitmweb fetches the current flows and then also opens a WebSocket (I assume that also opens a slight window for race conditions and you might miss flows). The pattern that I use exclusively in my app is that in the |
That's the missing piece. But I was assuming we had the power from an adddon (via |
|
(@meitinger: sorry for derailing your PR discussion)
Yes. This is done because sending a huge JSON block via WebSockets has (maybe had?) absymal performance on some browsers. There's no race condition because we open the WS connection first, then fetch the JSON, and then process all events that arrived in the meantime. It's tolerant towards re-receiving a flow that's both in events and JSON.
We absolutely have, that's the "pull" part I was referring to. Not sending the state as part of the event hook data, but instead notifying all interested parties that they should re-pull (and the broadcast via WebSockets/...). |
I swear that's the last comment 😄 . I understand now. There's a fundamental difference between my architecture and that of mitmweb. I don't need to pull at all, that's why a hook would've been enough for me. Because when the hook would fire (either initially or for future updates) I can send that to Electron immediately via gRPC. Which holds all the state ("remembers") and would send it to the frontend.
👍 🚀 I think I learned something, so it was worth it 😄 |
Sounds good to me too. I introduced the startup hook to not favor the built-in addons, then again, As for the rest: The only thing I would be careful with is blinker, because once you're outside And I'll (try) to implement the rest according to the requirements/preferences mentioned before :) Footnotes
|
|
The following has now been implemented:
@mhils The changes lean more towards what @Prinzhorn suggested in the UI example. But actually having separate notifications per instance allows us to better split tasks between |
|
I'm currently wondering what "stopping" of a listener is supposed to mean. We should define and document that. Right now on
from mitmproxy import ctx
def request(flow):
if flow.request.path == "/switch":
ctx.options.update(mode=["regular@8081"])
I can now send messages back and forth between the two
The proxy is now listening on |
|
This behavior is (currently) more or less by design, as removing a mode = stopping a server instance = closing the socket + wait on transport, but not cancelling all |
I don't think anyone has super strong opinions yet, so let's just keep things as-is unless convincing arguments show up. Of course you can make up some edge case arguments either way, but IMO the current behavior is relatively reasonable. :) |
There was a problem hiding this comment.
I'm perfectly happy with the fix for #5376, but I think I don't understand (yet) why we need most of the other complexity here.
- prevent one instance taking a long time to start or stop from affecting other instances
Do we have any evidence of this being a problem? My understanding is that binding and closing sockets is quick pretty much all the time. Most of the comment below is based on this assumption, so feel free to reject it right off the bat.
The new implementation here is really a bit harder to follow and I haven't fully wrapped my mind around it. Proxyserver.configure() calls Servers.setup(), which spawns instance.start(), which repeatedly calls instance.report(), which calls Proxyserver.update_instance(), which calls Servers.notify(), which then notifies all listeners? This looping around makes things hard to understand for me.
Just from reading the code I think changing the mode from reverse:example.com to reverse:example.org wouldn't work consistently because the new listener is already spawned while the old one is shut down? I might have missed something and this works just fine, but it's definitely a bit hard to reason about for me.
Some ideas on how we could simplify things:
- For shutting down, we just attempt to close the socket and then forget about the instance completely. Or do we have convincing examples where shutdown fails or takes a long time? Or examples where this is not good enough? Put differently, I don't see why retrying to shutdown would ever help. If shutdown fails, I'd be perfectly fine with emitting a log message and putting our hands up in the air.
- For starting, we try once and then give up. If someone wants retry logic in their UI, they shall send two consecutive option updates (the first one removing the mode the second one adding the mode).
- Instead of adding notify/report logic to the instances, we could also just do batched notifications from the proxyserver addon itself (see above: do we have cases where startup is surprisingly slow? Even if that would be the case, we could just add a timeout and treat them as failed). The individual instances would then only set
.stateattributes that are accessed by interested parties. This avoids the Proxyserver -> Servers -> Instance -> Proxyserver -> Servers loop described above.
Some smaller nits below, but that's only details. Sorry for the hard feedback, but it feels like we could simplify tremendously here (or I'm wrong and I get to learn why, also good)! :-)
| asyncio.create_task(self._shutdown_if_errored()) | ||
|
|
||
| async def _shutdown_if_errored(self): | ||
| await asyncio.sleep(0) |
There was a problem hiding this comment.
Side note: I have growing sympathies for replacing our logging event hook setup with the builtin logging module. We wouldn't need such asyncio.sleep(0) shenanigans anymore and we wouldn't need to add plumbing for log events everywhere. That's definitely a project for another day though.
| async def restart(instance: ServerInstance): | ||
| try: | ||
| await instance.start() | ||
| except: |
There was a problem hiding this comment.
Nit: except Exception: please, except: defaults to except BaseException: and we generally don't want to catch KeyboardInterrupt or SystemExit. Always using except Exception saves us from thinking about whether it's necessary or not.
| if ret is not None and inspect.iscoroutine(ret) | ||
| ] | ||
| if coroutines: | ||
| await asyncio.gather(*coroutines) |
There was a problem hiding this comment.
It might make sense to add a standalone async blinker implementation somewhere (simple homegrown or third-party) so that we can just await self.changed.send(...)? Implementation should be rather trivial, we can assume everything is safely on the same thread. It's basically a simple collection of weak references that can be called. Supporting both sync and async is easy (see here).
We can probably replace most of our usage of blinker with that if we add a SyncSignal subclass that errors when adding async listeners and provides a non-async send method.
There was a problem hiding this comment.
Good idea, I'll implement AsyncSignal and SyncSignal classes. Do you prefer in-order like with hooks in addons, i.e.
for aw in aws:
await awor concurrently as in this PR with asyncio.gather? (Since it's a signal, I personally lean towards gather.)
There was a problem hiding this comment.
Either is perfectly fine for me. Feel free to land this in a separate PR that just adds the signals (but does not add any usage), whatever is easier for you. :)
Not really, no. If we do #5512 (comment) within
I know, it could be more straight forward, and I had that in the beginning, i.e
No, you're right: If stopping takes a long time (it is scheduled before start), starting will fail. But starting can be retried as the instance is kept. We could actually add a check for instances with
IMHO a failed
This is what the current code does. The UI can also call
We definitely can do this for our instances. The question is, whether we should then allow such a generic
Basically, if we say that we'll never do something else in start and stop than what If we decide to allow more in start and stop, this won't work. (Or let's say: Won't be very user-friendly.) |
Ok, let's assume for now that it's always fast. If our assumptions change, we can always revisit and add complexity later.
I would argue we only want
I think that's perfectly fine as well. Again, when our assumptions change, we can always revisit and add complexity later.
We can definitely keep
That's even more complexity I would like to avoid. :-)
Do we have any concrete examples where shutdown even fails? If not I think it's mostly an academic question1 and we shouldn't add any additional complexity for it. Giving up is fine if we can't even think of a way to reach that state. :)
Yes. My not-very-well-articulated point here was that we don't even need to retry when
Let's not worry about third-party instances for this and only serve our own needs for now.
This seems much simpler to me, so I'd prefer this approach. I think it needs to be a ternary state (
I'd generally say that starting/stopping servers is a rare event that happens while the user is configuring mitmproxy (and not while running in production, whatever that would mean), so just having dumb starting/stopping makes our live easier and doesn't have a bad impact on user experience. So far the only way to configure that was to restart the entire proxy, and folks have not complained too loudly about that. :) Thanks for takings this constructively! 😃 Footnotes
|
I agree and changed the code of
With the simpler notifications, there is actually just one "updating" (starting/stopping) state, which can now be queried (and subscribed) in The new |
mhils
left a comment
There was a problem hiding this comment.
This looks so much better! 😃 🍰
Very happy with how this turned out, thanks! My only comment is that we should avoid
with pytest.raises(AssertionError):
await tctx.master.await_log("returned awaitable")in the future because that takes a second to run (see implementation) - fixed now. I've also taken the liberty to exterminate exceptions.TypeError so that old sins are not picked up (see comment here). 😅
| # def send(self, sender: Any, *args: P.args, **kwargs: P.kwargs) -> list[tuple[Callable[Concatenate[Any, P], R], R]]: | ||
| # ... | ||
| # | ||
| # Alternatively, once PEP 692 lands, we could make kwargs type-safe and use event args TypedDicts. |
There was a problem hiding this comment.
I strongly support adding better typing support, but let's not delay this PR here. While refactoring, have you seen any case where we use blinker for more than just simple notifications?
Description
Fix #5376 by introducing
StartupHook, which allows addons to execute tasks after everything is loaded, but before the running state is reached.For
proxyserver.pythis means: If any server instance fails to start, mitmproxy shows the appropriate error and exits, so there is no "half-loaded" state.@mhils: Ideally we should also handle the case if a mode change after startup fails.
What would you think about removing the mode from
ctx.options.modeif the shutdown succeeds but starting the new mode fails? That way the UI would be in sync with the current modes. Or maybe even starting the new instance first and do the shutdown later, that way having a better fallback? (I.e. keeping the old instance alive and reverting the mode to the old one.)Checklist