Skip to content

Commit 5596509

Browse files
author
h4x0r
committed
feat: better implementation of async loop
1 parent fe91461 commit 5596509

File tree

1 file changed

+15
-2
lines changed
  • aws_lambda_powertools/utilities/batch

1 file changed

+15
-2
lines changed

aws_lambda_powertools/utilities/batch/base.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import copy
88
import inspect
99
import logging
10+
import os
1011
import sys
1112
from abc import ABC, abstractmethod
1213
from enum import Enum
@@ -120,8 +121,20 @@ async def async_process():
120121
# Do not use "asyncio.run(async_process())" due to Lambda container thaws/freeze, otherwise we might get "Event Loop is closed"
121122
# Instead, get_event_loop() can also create one if a previous was erroneously closed
122123
# More: https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html#runtimes-lifecycle-shutdown
123-
loop = asyncio.get_event_loop()
124-
return loop.run_until_complete(async_process())
124+
# Extra: just follow how the well-tested mangum library do:
125+
# https://github.com/jordaneremieff/mangum/discussions/256#discussioncomment-2638946
126+
# https://github.com/jordaneremieff/mangum/blob/b85cd4a97f8ddd56094ccc540ca7156c76081745/mangum/protocols/http.py#L44
127+
128+
# Detect environment and create a loop for each one
129+
coro = async_process()
130+
if os.environ.get('AWS_LAMBDA_RUNTIME_API'):
131+
# Running in lambda server
132+
loop = asyncio.get_event_loop()
133+
task_instance = loop.create_task(coro)
134+
return loop.run_until_complete(task_instance)
135+
else:
136+
# Running in another place like local tests
137+
return asyncio.run(coro)
125138

126139
def __enter__(self):
127140
self._prepare()

0 commit comments

Comments
 (0)