66'sentry_sdk.integrations.init_serverless_sdk.sentry_lambda_handler'
77"""
88
9+ import importlib
910import os
10- import re
11- import sys
1211from typing import TYPE_CHECKING
1312
1413import sentry_sdk
2726
2827
2928class AWSLambdaModuleLoader :
30- DIR_PATH_REGEX = r"^(.+)\/([^\/]+)$"
31-
3229 def __init__ (self , sentry_initial_handler ):
3330 try :
3431 module_path , self .handler_name = sentry_initial_handler .rsplit ("." , 1 )
@@ -41,35 +38,24 @@ def extract_and_load_lambda_function_module(self, module_path):
4138 """
4239 Method that extracts and loads lambda function module from module_path
4340 """
44- py_version = sys .version_info
45-
46- if re .match (self .DIR_PATH_REGEX , module_path ):
47- # With a path like -> `scheduler/scheduler/event`
48- # `module_name` is `event`, and `module_file_path` is `scheduler/scheduler/event.py`
49- module_name = module_path .split (os .path .sep )[- 1 ]
50- module_file_path = module_path + ".py"
51-
52- # Supported python versions are 3.7, 3.8
53- if py_version >= (3 , 7 ):
54- import importlib .util
55-
56- spec = importlib .util .spec_from_file_location (
57- module_name , module_file_path
58- )
59- self .lambda_function_module = importlib .util .module_from_spec (spec )
60- spec .loader .exec_module (self .lambda_function_module )
61- else :
62- raise ValueError ("Python version %s is not supported." % py_version )
63- else :
64- import importlib
65-
66- self .lambda_function_module = importlib .import_module (module_path )
41+ # the handler used to be loaded from a file path, so keep accepting
42+ # `./dir/file` and absolute `<task root>/dir/file` by making them relative
43+ # to the task root, which is on `sys.path`.
44+ task_root = os .environ .get ("LAMBDA_TASK_ROOT" , os .getcwd ())
45+ module_path = os .path .relpath (os .path .join (task_root , module_path ), task_root )
46+
47+ # like the Lambda runtime: `dir/file` is the module `dir.file`, which `sys.modules`
48+ # keeps, so its code only runs on the first invocation.
49+ # https://github.com/aws/aws-lambda-python-runtime-interface-client/blob/fa2462d93d11da632aad8f8bfb07a3e060438150/awslambdaric/bootstrap.py#L53
50+ self .lambda_function_module = importlib .import_module (
51+ module_path .replace ("/" , "." )
52+ )
6753
6854 def get_lambda_handler (self ):
6955 return getattr (self .lambda_function_module , self .handler_name )
7056
7157
72- def sentry_lambda_handler (event : "Any" , context : "Any" ) -> None :
58+ def sentry_lambda_handler (event : "Any" , context : "Any" ) -> "Any" :
7359 """
7460 Handler function that invokes a lambda handler which path is defined in
7561 environment variables as "SENTRY_INITIAL_HANDLER"
0 commit comments