move the lock sync to _handle

This commit is contained in:
Son NK 2020-08-17 11:40:58 +02:00
parent d8a415c00a
commit 38bf117f29

View file

@ -1235,24 +1235,23 @@ async def get_spam_score(message: Message) -> float:
class MailHandler: class MailHandler:
lock = asyncio.Lock() def __init__(self, lock):
self.lock = lock
async def handle_DATA(self, server, session, envelope: Envelope): async def handle_DATA(self, server, session, envelope: Envelope):
async with self.lock:
try: try:
ret = await self._handle(envelope) ret = await self._handle(envelope)
return ret return ret
except Exception: except Exception:
LOG.exception( LOG.exception(
"email handling fail %s -> %s", "email handling fail %s -> %s", envelope.mail_from, envelope.rcpt_tos,
envelope.mail_from,
envelope.rcpt_tos,
) )
return "421 SL Retry later" return "421 SL Retry later"
async def _handle(self, envelope: Envelope): async def _handle(self, envelope: Envelope):
async with self.lock:
start = time.time() start = time.time()
LOG.debug( LOG.info(
"===>> New message, mail from %s, rctp tos %s ", "===>> New message, mail from %s, rctp tos %s ",
envelope.mail_from, envelope.mail_from,
envelope.rcpt_tos, envelope.rcpt_tos,
@ -1267,7 +1266,7 @@ class MailHandler:
app = new_app() app = new_app()
with app.app_context(): with app.app_context():
ret = await handle(envelope, smtp) ret = await handle(envelope, smtp)
LOG.debug("takes %s seconds <<===", time.time() - start) LOG.info("takes %s seconds <<===", time.time() - start)
return ret return ret
@ -1278,9 +1277,10 @@ if __name__ == "__main__":
with app.app_context(): with app.app_context():
load_pgp_public_keys() load_pgp_public_keys()
handler = MailHandler()
loop = asyncio.new_event_loop() loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) asyncio.set_event_loop(loop)
lock = asyncio.Lock()
handler = MailHandler(lock)
def factory(): def factory():
return aiosmtpd.smtp.SMTP(handler, enable_SMTPUTF8=True) return aiosmtpd.smtp.SMTP(handler, enable_SMTPUTF8=True)