Repository navigation
Expand file tree
/
Copy pathlambda_function.py
More file actions
270 lines (226 loc) · 9.65 KB
/
Copy pathlambda_function.py
File metadata and controls
270 lines (226 loc) · 9.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
"""AWS Lambda entry point for Welt, the Slack frontend for AgentCore agents.
Serves the same conversation flow as `main.py` over the Slack Events API
(HTTP request URL) instead of Socket Mode, for deployments on the Lambda
Python runtime. Bolt acks each event within Slack's 3-second window and
re-invokes this same function asynchronously to run the lazy listener, so
the function's IAM role must allow `lambda:InvokeFunction` on the function
itself. Configure the handler as `lambda_function.lambda_handler` (the
Python runtime default) and point the Slack app's Events API request URL at
the function.
"""
from __future__ import annotations
import asyncio
import functools
import logging
import os
from collections.abc import Mapping
from cobito import QueuedRequest, answer_queued_message
from slack_bolt import Ack, App, BoltContext
from slack_bolt.adapter.aws_lambda import SlackRequestHandler
from slack_sdk.http_retry.builtin_async_handlers import AsyncRateLimitErrorRetryHandler
from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
from slack_sdk.web.async_client import AsyncWebClient
from app import bolt_listeners
from app.agent_service import init_client, init_url_client, log_local_mode
from app.bolt_logic import INTERRUPT_ACTION_PATTERN
from app.bolt_middlewares import before_authorize_http
from app.env import (
SLACK_SECRET_KEYS,
Env,
apply_slack_secret,
load_env,
require_env,
)
from app.queue_logic import is_sqs_event, scopes_from_header
from app.secret_service import fetch_slack_secret
logger = logging.getLogger(__name__)
def lambda_handler(event: dict, context: object) -> dict:
"""
Handle one Lambda invocation: an Events API request, a lazy run, or
requests from an SQS queue.
Args:
event (dict): The Lambda event (an HTTP request from a Function URL
or API Gateway, Bolt's lazy-listener re-invocation, or an SQS
trigger's batch).
context (object): The Lambda context object.
Returns:
dict: The HTTP response for the Lambda runtime, or for an SQS batch,
the messages to deliver again (`batchItemFailures`).
"""
environ, secret_warnings = _slack_environ(os.environ)
credentials = tuple(
(name, environ[name]) for name in SLACK_SECRET_KEYS if name in environ
)
if is_sqs_event(event):
env = _get_env(credentials, secret_warnings)
return asyncio.run(_answer_queued_records(env, event["Records"]))
return _get_handler(credentials, secret_warnings).handle(event, context)
async def _answer_queued_records(env: Env, records: list[dict]) -> dict:
"""
Answer the requests in an SQS trigger's batch, in order.
A message whose answer could not be opened is delivered again, and so is
every message after it in the batch, which a FIFO queue's order puts
behind it.
Args:
env (Env): The validated configuration.
records (list[dict]): The batch's records.
Returns:
dict: The messages to deliver again, as the trigger's
`batchItemFailures` response.
"""
client = AsyncWebClient(token=env.slack_bot_token)
client.retry_handlers.append(AsyncRateLimitErrorRetryHandler(max_retry_count=2))
identity = await client.auth_test()
bot_scopes = scopes_from_header(identity.headers.get("x-oauth-scopes", ""))
async def answer(request: QueuedRequest, thread_ts: str) -> None:
await bolt_listeners.answer_queued_request(
env=env,
client=client,
request=request,
thread_ts=thread_ts,
team_id=identity["team_id"],
bot_user_id=identity["user_id"],
bot_scopes=bot_scopes,
)
for index, record in enumerate(records):
if not await answer_queued_message(client, record["body"], answer):
return {
"batchItemFailures": [
{"itemIdentifier": later["messageId"]} for later in records[index:]
]
}
return {"batchItemFailures": []}
@functools.lru_cache(maxsize=1)
def _get_handler(
credentials: tuple[tuple[str, str], ...], secret_warnings: tuple[str, ...]
) -> SlackRequestHandler:
"""
Build the request handler for one set of Slack credentials.
Deferring the build to the first invocation (instead of import time)
keeps the module importable without configuration; a misconfigured
function still fails with a clear error. The handler is reused until the
credentials change, which happens when SLACK_SECRET_ARN's secret is
edited and its cached copy expires. Only the credentials key the cache,
because Lambda changes other environment variables, such as
`_X_AMZN_TRACE_ID`, on every invocation.
Args:
credentials (tuple[tuple[str, str], ...]): The Slack credentials in
effect, as (name, value) pairs.
secret_warnings (tuple[str, ...]): Boot warnings from applying the
secret.
Returns:
SlackRequestHandler: The handler wrapping the configured Bolt app.
"""
environ = {**os.environ, **dict(credentials)}
env = _get_env(credentials, secret_warnings)
signing_secret = require_env(environ, "SLACK_SIGNING_SECRET")
return SlackRequestHandler(app=create_bolt_app(env, signing_secret))
@functools.lru_cache(maxsize=1)
def _get_env(
credentials: tuple[tuple[str, str], ...], secret_warnings: tuple[str, ...]
) -> Env:
"""
Configure Welt for one set of Slack credentials.
Reads the configuration, sets up logging and the agent client, and
reuses them until the credentials change (see `_get_handler`).
Args:
credentials (tuple[tuple[str, str], ...]): The Slack credentials in
effect, as (name, value) pairs.
secret_warnings (tuple[str, ...]): Boot warnings from applying the
secret.
Returns:
Env: The validated configuration.
"""
env = load_env({**os.environ, **dict(credentials)})
SlackRequestHandler.clear_all_log_handlers()
logging.basicConfig(level=env.deps_log_level)
# LOG_LEVEL applies to Welt's own loggers only, cobito's among them (it
# holds Welt's Slack side); the root level above (DEPS_LOG_LEVEL) covers
# the dependencies. See Env.deps_log_level.
logging.getLogger("app").setLevel(env.log_level)
logging.getLogger("cobito").setLevel(env.log_level)
logger.setLevel(env.log_level)
for warning in (*secret_warnings, *env.boot_warnings):
logger.warning(warning)
# An agent addressed by AGENT_URL needs no ARN; with no ARN, Gateway URL
# or AGENT_URL, there is no signing region, and the resulting local
# target is named in the log, including on Lambda.
if env.agent_url is not None:
init_url_client(url=env.agent_url, signing=env.agent_sigv4)
elif env.agent_region is None:
log_local_mode()
else:
init_client(
region_name=env.agent_region,
gateway_url=env.agent_gateway_url,
gateway_only=env.agent_arn is None,
)
return env
def _slack_environ(
environ: Mapping[str, str],
) -> tuple[dict[str, str], tuple[str, ...]]:
"""
Apply the Slack credentials from SLACK_SECRET_ARN's secret, if it is set.
Args:
environ (Mapping[str, str]): The process environment (`os.environ`).
Returns:
tuple[dict[str, str], tuple[str, ...]]: The environment to configure
Welt from, and the boot warnings from applying the secret.
"""
secret_arn = environ.get("SLACK_SECRET_ARN")
if not secret_arn:
return dict(environ), ()
return apply_slack_secret(environ, fetch_slack_secret(secret_arn))
def create_bolt_app(env: Env, signing_secret: str) -> App:
"""
Create and configure the sync Slack Bolt app instance for HTTP serving.
The listener body is the same async flow Socket Mode runs; each lazy
invocation carries one message, so it bridges with `asyncio.run` and an
`AsyncWebClient` of its own.
Args:
env (Env): The validated configuration.
signing_secret (str): The Slack signing secret for request
verification.
Returns:
App: The configured Slack Bolt app instance.
"""
app = App(
token=env.slack_bot_token,
signing_secret=signing_secret,
before_authorize=before_authorize_http,
process_before_response=True,
)
app.client.retry_handlers.append(RateLimitErrorRetryHandler(max_retry_count=2))
def respond_to_new_post(context: BoltContext, payload: dict) -> None:
client = AsyncWebClient(token=env.slack_bot_token)
client.retry_handlers.append(AsyncRateLimitErrorRetryHandler(max_retry_count=2))
asyncio.run(
bolt_listeners.respond_to_new_post(
env=env, context=context, payload=payload, client=client
)
)
def respond_to_interrupt_action(
context: BoltContext, body: dict, payload: dict
) -> None:
client = AsyncWebClient(token=env.slack_bot_token)
client.retry_handlers.append(AsyncRateLimitErrorRetryHandler(max_retry_count=2))
asyncio.run(
bolt_listeners.respond_to_interrupt_action(
env=env, context=context, body=body, payload=payload, client=client
)
)
app.event("message")(ack=just_ack, lazy=[respond_to_new_post])
app.action(INTERRUPT_ACTION_PATTERN)(
ack=just_ack, lazy=[respond_to_interrupt_action]
)
return app
def just_ack(ack: Ack) -> None:
"""
Acknowledge the incoming request immediately.
The real work happens in the lazy listener, keeping the 3-second ack.
Args:
ack (Ack): The acknowledgment function provided by Slack Bolt.
Returns:
None
"""
ack()