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,40 +1235,39 @@ 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", envelope.mail_from, envelope.rcpt_tos,
"email handling fail %s -> %s", )
envelope.mail_from, return "421 SL Retry later"
envelope.rcpt_tos,
)
return "421 SL Retry later"
async def _handle(self, envelope: Envelope): async def _handle(self, envelope: Envelope):
start = time.time() async with self.lock:
LOG.debug( start = time.time()
"===>> New message, mail from %s, rctp tos %s ", LOG.info(
envelope.mail_from, "===>> New message, mail from %s, rctp tos %s ",
envelope.rcpt_tos, envelope.mail_from,
) envelope.rcpt_tos,
)
if POSTFIX_SUBMISSION_TLS: if POSTFIX_SUBMISSION_TLS:
smtp = SMTP(POSTFIX_SERVER, 587) smtp = SMTP(POSTFIX_SERVER, 587)
smtp.starttls() smtp.starttls()
else: else:
smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25) smtp = SMTP(POSTFIX_SERVER, POSTFIX_PORT or 25)
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
if __name__ == "__main__": if __name__ == "__main__":
@ -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)