从Slack调用Lambda函数时超时

2024-09-30 23:32:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这段与斜杠命令相关联的代码,后面是this article,斜杠命令正在工作

如果延迟超过3秒,则出现超时错误,如何避免此情况

import json
from urllib import parse as urlparse
import base64
from functools import lru_cache
import math

@lru_cache(maxsize=60)
def isPrime(i):
    if (i in [2,3]):  # shortcut low primes
        return True
    else:
        if (i % 2 == 0 or i % 3 == 0):  # special since we go 3-> sqrt
            return False
        sqrt = int(math.sqrt(i) // 1)
        for s in range(3,sqrt+1,2):  # check odd vals, or all prior primes + new primes
            if (i % s == 0):
                return False
        return True

commands = {'isprime':isPrime,'prime':isPrime }   # map of command aliases

def lambda_handler(event, context):
    msg_map = dict(urlparse.parse_qsl(base64.b64decode(str(event['body'])).decode('ascii')))  # data comes b64 and also urlencoded name=value& pairs
    command = msg_map.get('command','err')  # will be /command name
    params = msg_map.get('text','err').split(" ")  # params ['isPrime','50']
    subcommand = params[0].lower()
    if (len(params) < 2):
        response = f'available subcommands: {list(commands.keys())} + 1 parameter'
    elif (subcommand in commands.keys()):
        response = f'{subcommand} needs an numeric param' if len(params) < 2 else f'{subcommand} = {commands[subcommand](int(float(params[1])))}'
    else:
        response = f'illegal sub command >{subcommand}<, commands available {list(commands.keys())}'

    # logging
    print (str(command) + ' ' + str(params) +' -> '+ response + ',original: '+ str(msg_map))

    return  {
        "response_type": "in_channel",
        "text": command + ' ' + " ".join(params),
        "attachments": [
            {
                "text": response
            }
        ]
    }

如何添加5分钟等待响应。Slack在三秒钟后超时

failed with the error "operation_timeout"

更新

这与Lambda超时无关。我增加了它,在进一步的研究中,似乎有一个由slack施加的3000毫秒的硬限制,如对this question的回答中所述


Tags: inimportmapreturnifresponsemsgsqrt
1条回答
网友
1楼 · 发布于 2024-09-30 23:32:31

你可能遇到了Lambda超时。AWS Lambda运行代码以响应事件,最长运行时间为900秒/15分钟。此限制可以配置为as described in the docs,默认情况下3秒

解决方案:增加Lambda函数超时值


更新

由于您能够消除Lambda超时这一问题,并指出this question表示响应的硬限制为3000ms,因此我们遇到了一个不同的问题:

代码变慢了

检查素数是一个计算密集型的过程,如果需要在短时间内完成,您可以花钱解决这个问题(CPU马力)。在Lambda中,这意味着增加函数的内存容量,因为在Lambda CPU中,RAM和网络性能随分配的内存而扩展

内存设置为1280 MB的lambda函数应该提供大致完整的vCPU,这是单线程实现的上限。下一步你可以试试

如果这不起作用,您需要更有效地实现isPrime算法

相关问题 更多 >