The variable description states that $env.$datasource represents the "Active datasource for the current request". However, this is not what happens when the datasource is changed during request execution using the "Set Data Source" function.
The "Set Data Source" function works correctly. After changing the datasource, all subsequent database operations are executed against the newly selected datasource, both when used inside an endpoint and when used within a pre-middleware.
The issue is that $env.$datasource is not updated after the datasource change. It continues to return the datasource that was active at the beginning of the request, even though the actual active datasource has already been changed and is being used by all subsequent functions.
This creates an inconsistency between the real execution context and the value exposed by the system variable. In practice, $env.$datasource behaves like a Constant containing the original datasource rather than a Variable representing the currently active datasource.
Since the variable is documented as the active datasource for the current request, its value should be updated immediately after a successful "Set Data Source" operation. The system variable should always reflect the datasource that is currently active and being used by the request at that point in execution. I believe this should be corrected so that $env.$datasource remains synchronized with datasource changes performed through the "Set Data Source" function.
FA