PythonNest / PyNest

PyNest is a Python framework built on top of FastAPI that follows the modular architecture of NestJS
https://pythonnest.github.io/PyNest
MIT License
754 stars 52 forks source link

Issue: Services are not properly scoped to modules #82

Open danielmoumeny212 opened 1 month ago

danielmoumeny212 commented 1 month ago

While working with PyNest, I have noticed that services are not properly scoped within modules. Ideally, a service should only be accessible within the module where it is declared in the providers array, or in a module that imports it, provided the service is both in the providers and exports arrays of the exporting module.

However, it appears that each module can access services directly from the global container, without any strict validation to ensure that the requested service is either in the providers array of the module where it is being used, or in both the providers and exports arrays of a module that is being imported.

This lack of proper scoping leads to concerns about the isolation of services and could cause unexpected behaviors in the application.

Expected Behavior: Services should be accessible only within the module where they are declared or properly imported and exported by another module. There should be validation ensuring that services are not accessed globally without proper declaration in the relevant module.

ItayTheDar commented 1 month ago

@danielmoumeny212 this is so true. After we release your big pr with the Module decorator, iv'e also noticed that, but put that on the backlog and forgot about that. Do you have any suggestions how to implement those restrictions? I believe this should be as part as the PyNest container?

danielmoumeny212 commented 1 month ago

Yeah, it should be part of the PyNest container! However, I also noticed a limitation due to Python’s behavior: two modules can't import each other because it would create a circular import, which can become critical if you need to declare dependencies across both modules. For instance, ModuleA needs ServiceB, and ModuleB needs ServiceA. If you try to import the services directly into both modules , it will result in a circular import. The current behavior of non-scoped services solves this issue by allowing access to a service declared in one module without needing to import that module in the file where the service is required. PyNest’s global container makes the service accessible everywhere, even without explicitly importing the module that contains the service.