Badgerati / Pode

Pode is a Cross-Platform PowerShell web framework for creating REST APIs, Web Sites, and TCP/SMTP servers
https://badgerati.github.io/Pode
MIT License
857 stars 93 forks source link

Invoking arbitrary command in all the created runspaces ? #1098

Open avin3sh opened 1 year ago

avin3sh commented 1 year ago

Question

How do I invoke, say a script block, in all the runspaces spun by Pode ?

My usecase is that I need to set certain context (not to confuse with http context) before my routes execute, and the context should be set as part of the same executing thread as the route. This has to be done only once and when a new runspace is created.

Doing this in Start-Server scriptblock would not help. Adding a Global Custom Middleware would also not help since it may not necessarily execute in the same thread as the route scriptblock. My only available option is to invoke this script that sets the context in every route, but that leads to lot of duplication since nothing in the context is specific to the route. It is also expensive since it has to be done once but doing so in route means it gets executed all the time unless I use a shared state to check.

Is there a way to run a user-provided script block inside every runspace pode creates ?

Badgerati commented 1 year ago

Hi @avin3sh,

If you only need to run the command once in Pode's web runspaces, where routes, middleware, etc. are run, then building a global middleware to run the command and checking if it's already run once before will work. The middleware that invokes along a route from a request do all run in the same runspace/thread - so this trick should work, and has for others in the past.

If however you need to run the command in Pode's other runspaces, such as the runspaces for schedules; web-sockets; logging; etc., then yes that above trick won't work.

I have thought about this in the past here - idea being to add runspace level events in Pode, so you could run an arbitrary command once when a runspace is created. I can look add support for this in the next release.

avin3sh commented 1 year ago

The middleware that invokes along a route from a request do all run in the same runspace/thread - so this trick should work, and has for others in the past.

I tested this and this is indeed the case!

I also want to run some house keeping commands in runspaces that Pode creates internally for own use, so having the following would be still very helpful :)

If however you need to run the command in Pode's other runspaces, such as the runspaces for schedules; web-sockets; logging; etc., then yes that above trick won't work.