2525from typing import TypeVar , Type , Union , List
2626
2727from grpclib import GRPCError
28- from nitricapi .nitric .resource .v1 import Action , PolicyResource , Resource , ResourceType , ResourceDeclareRequest , \
29- ResourceServiceStub
30-
31- from nitric .api .exception import exception_from_grpc_error
28+ from nitricapi .nitric .resource .v1 import (
29+ Action ,
30+ PolicyResource ,
31+ Resource ,
32+ ResourceType ,
33+ ResourceDeclareRequest ,
34+ ResourceServiceStub ,
35+ )
36+
37+ from nitric .api .exception import exception_from_grpc_error , NitricResourceException
3238from nitric .utils import new_default_channel
3339
3440T = TypeVar ("T" , bound = "BaseResource" )
@@ -69,7 +75,7 @@ def make(cls: Type[T], name: str) -> T:
6975
7076
7177class SecureResource (BaseResource ):
72- """A secure base resource class"""
78+ """A secure base resource class. """
7379
7480 @abstractmethod
7581 def _to_resource (self ) -> Resource :
@@ -90,12 +96,20 @@ async def _register_policy_async(self, *args: str):
9096 )
9197 try :
9298 await self ._resources_stub .declare (
93- resource_declare_request = ResourceDeclareRequest (resource = Resource (type = ResourceType .Policy ),
94- policy = policy ))
99+ resource_declare_request = ResourceDeclareRequest (
100+ resource = Resource (type = ResourceType .Policy ), policy = policy
101+ )
102+ )
95103 except GRPCError as grpc_err :
96104 raise exception_from_grpc_error (grpc_err )
97105
98106 def _register_policy (self , * args : str ):
99- loop = asyncio .get_event_loop ()
100- loop .run_until_complete (self ._register_policy_async (* args ))
101-
107+ try :
108+ loop = asyncio .get_event_loop ()
109+ loop .run_until_complete (self ._register_policy_async (* args ))
110+ except RuntimeError :
111+ # TODO: Check nitric runtime ENV variable
112+ raise NitricResourceException (
113+ "Nitric resources cannot be declared at runtime e.g. within the scope of a function. \
114+ Move resource declarations to the top level of scripts so that they can be safely provisioned"
115+ )
0 commit comments