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
271
use axum::{
body::Body,
extract::{Extension, Path},
http::{header::HeaderName, Request, StatusCode},
response::Response,
routing::{get, post},
Router,
};
use clap::{Args, ValueHint};
use miette::Result;
use opentelemetry::{
global,
trace::{TraceContextExt, Tracer},
Context, KeyValue,
};
use std::{collections::HashMap, net::SocketAddr, path::PathBuf};
use tokio::{
sync::{mpsc::Sender, oneshot},
time::Duration,
};
use tokio_graceful_shutdown::{SubsystemHandle, Toplevel};
use tower_http::{
catch_panic::CatchPanicLayer,
request_id::{PropagateRequestIdLayer, SetRequestIdLayer},
trace::TraceLayer,
};
use tracing::{debug, info};
mod requests;
use requests::*;
mod scheduler;
use scheduler::*;
mod trace;
use trace::*;
mod watch_installer;
const AWS_XRAY_TRACE_HEADER: &str = "x-amzn-trace-id";
const LAMBDA_RUNTIME_XRAY_TRACE_HEADER: &str = "lambda-runtime-trace-id";
const LAMBDA_RUNTIME_COGNITO_IDENTITY: &str = "lambda-runtime-cognito-identity";
const LAMBDA_RUNTIME_CLIENT_CONTEXT: &str = "lambda-runtime-client-context";
const LAMBDA_RUNTIME_AWS_REQUEST_ID: &str = "lambda-runtime-aws-request-id";
const LAMBDA_RUNTIME_DEADLINE_MS: &str = "lambda-runtime-deadline-ms";
const LAMBDA_RUNTIME_FUNCTION_ARN: &str = "lambda-runtime-invoked-function-arn";
#[derive(Args, Clone, Debug)]
#[clap(name = "watch", visible_alias = "start")]
pub struct Watch {
#[clap(long)]
no_reload: bool,
#[clap(short = 'p', long, default_value = "9000")]
invoke_port: u16,
#[clap(long)]
print_traces: bool,
#[clap(long, value_name = "PATH", parse(from_os_str), value_hint = ValueHint::FilePath)]
#[clap(default_value = "Cargo.toml")]
pub manifest_path: PathBuf,
}
impl Watch {
pub async fn run(&self) -> Result<()> {
if !self.no_reload && which::which("cargo-watch").is_err() {
watch_installer::install().await?;
}
let port = self.invoke_port;
let print_traces = self.print_traces;
let manifest_path = self.manifest_path.clone();
let no_reload = self.no_reload;
Toplevel::new()
.start("Lambda server", move |s| {
start_server(s, port, print_traces, manifest_path, no_reload)
})
.catch_signals()
.handle_shutdown_requests(Duration::from_millis(1000))
.await
.map_err(|e| miette::miette!("{}", e))
}
}
async fn start_server(
subsys: SubsystemHandle,
invoke_port: u16,
print_traces: bool,
manifest_path: PathBuf,
no_reload: bool,
) -> Result<(), axum::Error> {
init_tracing(print_traces);
let addr = SocketAddr::from(([127, 0, 0, 1], invoke_port));
let server_addr = format!("http://{addr}");
let req_cache = RequestCache::new(server_addr);
let req_tx = init_scheduler(&subsys, req_cache.clone(), manifest_path, no_reload).await;
let resp_cache = ResponseCache::new();
let x_request_id = HeaderName::from_static("lambda-runtime-aws-request-id");
let app = Router::new()
.route(
"/2015-03-31/functions/:function_name/invocations",
post(invoke_handler),
)
.route(
"/:function_name/2018-06-01/runtime/invocation/next",
get(next_request),
)
.route(
"/:function_name/2018-06-01/runtime/invocation/:req_id/response",
post(next_invocation_response),
)
.route(
"/:function_name/2018-06-01/runtime/invocation/:req_id/error",
post(next_invocation_error),
)
.layer(SetRequestIdLayer::new(
x_request_id.clone(),
RequestUuidService,
))
.layer(PropagateRequestIdLayer::new(x_request_id))
.layer(Extension(req_tx.clone()))
.layer(Extension(req_cache))
.layer(Extension(resp_cache))
.layer(TraceLayer::new_for_http())
.layer(CatchPanicLayer::new());
info!("invoke server listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.with_graceful_shutdown(subsys.on_shutdown_requested())
.await
.map_err(axum::Error::new)
}
async fn invoke_handler(
Extension(cmd_tx): Extension<Sender<InvokeRequest>>,
Path(function_name): Path<String>,
req: Request<Body>,
) -> Result<Response<Body>, ServerError> {
let mut req = req;
let headers = req.headers_mut();
let span = global::tracer("cargo-lambda/emulator").start("invoke request");
let cx = Context::current_with_span(span);
let mut injector = HashMap::new();
global::get_text_map_propagator(|propagator| {
propagator.inject_context(&cx, &mut injector);
});
let xray_header = injector
.get(AWS_XRAY_TRACE_HEADER)
.expect("x-amzn-trace-id header not injected by the propagator")
.parse()
.expect("x-amzn-trace-id header is not in the expected format");
headers.insert(LAMBDA_RUNTIME_XRAY_TRACE_HEADER, xray_header);
let (resp_tx, resp_rx) = oneshot::channel::<Response<Body>>();
let req = InvokeRequest {
function_name,
req,
resp_tx,
};
cmd_tx
.send(req)
.await
.map_err(|e| ServerError::SendInvokeMessage(Box::new(e)))?;
let resp = resp_rx.await.map_err(ServerError::ReceiveFunctionMessage)?;
cx.span().add_event(
"function call completed",
vec![KeyValue::new("status", resp.status().to_string())],
);
Ok(resp)
}
async fn next_request(
Extension(req_cache): Extension<RequestCache>,
Extension(resp_cache): Extension<ResponseCache>,
Path(function_name): Path<String>,
req: Request<Body>,
) -> Result<Response<Body>, ServerError> {
let req_id = req
.headers()
.get(LAMBDA_RUNTIME_AWS_REQUEST_ID)
.expect("missing request id");
let mut builder = Response::builder()
.header(LAMBDA_RUNTIME_AWS_REQUEST_ID, req_id)
.header(LAMBDA_RUNTIME_DEADLINE_MS, 600_000_u32)
.header(LAMBDA_RUNTIME_FUNCTION_ARN, "function-arn");
let resp = match req_cache.pop(&function_name).await {
None => builder.status(StatusCode::NO_CONTENT).body(Body::empty()),
Some(invoke) => {
let req_id = req_id
.to_str()
.map_err(ServerError::InvalidRequestIdHeader)?;
debug!(req_id = ?req_id, "processing request");
let (parts, body) = invoke.req.into_parts();
let resp_tx = invoke.resp_tx;
resp_cache.push(req_id, resp_tx).await;
let headers = parts.headers;
if let Some(h) = headers.get(LAMBDA_RUNTIME_CLIENT_CONTEXT) {
builder = builder.header(LAMBDA_RUNTIME_CLIENT_CONTEXT, h);
}
if let Some(h) = headers.get(LAMBDA_RUNTIME_COGNITO_IDENTITY) {
builder = builder.header(LAMBDA_RUNTIME_COGNITO_IDENTITY, h);
}
if let Some(h) = headers.get(LAMBDA_RUNTIME_XRAY_TRACE_HEADER) {
builder = builder.header(LAMBDA_RUNTIME_XRAY_TRACE_HEADER, h);
}
builder.status(StatusCode::OK).body(body)
}
};
resp.map_err(ServerError::ResponseBuild)
}
async fn next_invocation_response(
Extension(cache): Extension<ResponseCache>,
Path((_function_name, req_id)): Path<(String, String)>,
req: Request<Body>,
) -> Result<Response<Body>, ServerError> {
respond_to_next_invocation(&cache, &req_id, req, StatusCode::OK).await
}
async fn next_invocation_error(
Extension(cache): Extension<ResponseCache>,
Path((_function_name, req_id)): Path<(String, String)>,
req: Request<Body>,
) -> Result<Response<Body>, ServerError> {
respond_to_next_invocation(&cache, &req_id, req, StatusCode::INTERNAL_SERVER_ERROR).await
}
async fn respond_to_next_invocation(
cache: &ResponseCache,
req_id: &str,
req: Request<Body>,
response_status: StatusCode,
) -> Result<Response<Body>, ServerError> {
if let Some(resp_tx) = cache.pop(req_id).await {
let (_, body) = req.into_parts();
let resp = Response::builder()
.status(response_status)
.header("lambda-runtime-aws-request-id", req_id)
.body(body)
.map_err(ServerError::ResponseBuild)?;
resp_tx
.send(resp)
.map_err(|_| ServerError::SendFunctionMessage)?;
}
Ok(Response::new(Body::empty()))
}