-
Notifications
You must be signed in to change notification settings - Fork 394
feat: add lambda-runtime-invocation-id header #1159
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
darklight3it
wants to merge
5
commits into
main
Choose a base branch
from
feat/add-runtime-invocation-id-header-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
07de1f5
feat: add support for invocation-id
darklight3it de1f2e4
test: add multiconcurrency testing
darklight3it a75e5f1
chore: additional fixes
darklight3it 2cabdac
cohre: other changes
darklight3it 1152b7c
chore: code review
darklight3it File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| [package] | ||
| name = "invocation-id-concurrent" | ||
| version = "0.1.0" | ||
| edition = "2021" | ||
|
|
||
| [dependencies] | ||
| lambda_runtime = { path = "../../lambda-runtime", features = ["concurrency-tokio"] } | ||
| serde = "1.0.219" | ||
| tokio = { version = "1", features = ["macros", "rt", "time"] } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| // This example requires the following input to succeed: | ||
| // { "command": "do something" } | ||
|
|
||
| use lambda_runtime::{service_fn, tracing, Diagnostic, Error, LambdaEvent}; | ||
| use serde::{Deserialize, Serialize}; | ||
|
|
||
| #[derive(Deserialize)] | ||
| struct Request { | ||
| #[serde(rename = "command")] | ||
| _command: String, | ||
| sleep: u32, | ||
| } | ||
|
|
||
| #[derive(Serialize, Debug, PartialEq)] | ||
| struct Response { | ||
| from: String, | ||
| } | ||
|
|
||
| #[derive(Debug)] | ||
| struct HandlerError(String); | ||
|
|
||
| impl std::fmt::Display for HandlerError { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| write!(f, "{}", self.0) | ||
| } | ||
| } | ||
|
|
||
| impl From<HandlerError> for Diagnostic { | ||
| fn from(e: HandlerError) -> Diagnostic { | ||
| Diagnostic { | ||
| error_type: "HandlerError".into(), | ||
| error_message: e.0, | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| /** | ||
| * Cross-wiring protection: duplicate request-id after timeout. | ||
|
|
||
| Timeline: | ||
| t=0: Invoke A starts, handler sleeps 7s | ||
| t=5: A times out (timeout=5s). Batch 1 completes with timeout error. | ||
| t=5: Invoke B starts (same request-id), handler sleeps 4s | ||
| t=7: A's handler wakes up, posts stale /response/{same-id} | ||
| t=9: B's handler wakes up, posts correct /response/{same-id} | ||
|
|
||
| With invocation-id: A's stale post at t=7 gets 410 Gone. B responds at t=9 correctly. | ||
| Without: A's stale response at t=7 is accepted for B (cross-wired). | ||
| */ | ||
|
|
||
| #[tokio::main] | ||
| async fn main() -> Result<(), Error> { | ||
| // required to enable CloudWatch error logging by the runtime | ||
| tracing::init_default_subscriber(); | ||
| let max_concurrency = std::env::var("AWS_LAMBDA_MAX_CONCURRENCY").unwrap_or_else(|_| "not set".to_string()); | ||
| tracing::info!(AWS_LAMBDA_MAX_CONCURRENCY = %max_concurrency, "starting concurrent handler"); | ||
|
|
||
| let func = service_fn(my_handler); | ||
| if let Err(err) = lambda_runtime::run_concurrent(func).await { | ||
| tracing::error!(error = %err, "run error"); | ||
| return Err(err); | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| pub(crate) async fn my_handler(event: LambdaEvent<Request>) -> Result<Response, HandlerError> { | ||
| if event.payload.sleep > 0 { | ||
| tokio::time::sleep(tokio::time::Duration::from_secs(event.payload.sleep.into())).await; | ||
| } | ||
|
|
||
| Ok(Response { | ||
| from: event.payload._command, | ||
| }) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use lambda_runtime::{Context, LambdaEvent}; | ||
|
|
||
| #[tokio::test] | ||
| async fn handler_echoes_marker() { | ||
| let event = LambdaEvent { | ||
| payload: Request { | ||
| _command: "invoke-B".into(), | ||
| sleep: 0, | ||
| }, | ||
| context: Context::default(), | ||
| }; | ||
|
|
||
| let result = my_handler(event).await.unwrap(); | ||
|
|
||
| assert_eq!(result, Response { from: "invoke-B".into() }); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| /// Header names used in the Lambda Runtime API. | ||
| pub(crate) const LAMBDA_RUNTIME_REQUEST_ID: &str = "lambda-runtime-aws-request-id"; | ||
| pub(crate) const LAMBDA_RUNTIME_DEADLINE_MS: &str = "lambda-runtime-deadline-ms"; | ||
| pub(crate) const LAMBDA_RUNTIME_INVOKED_FUNCTION_ARN: &str = "lambda-runtime-invoked-function-arn"; | ||
| pub(crate) const LAMBDA_RUNTIME_TRACE_ID: &str = "lambda-runtime-trace-id"; | ||
| pub(crate) const LAMBDA_RUNTIME_CLIENT_CONTEXT: &str = "lambda-runtime-client-context"; | ||
| pub(crate) const LAMBDA_RUNTIME_COGNITO_IDENTITY: &str = "lambda-runtime-cognito-identity"; | ||
| pub(crate) const LAMBDA_RUNTIME_TENANT_ID: &str = "lambda-runtime-aws-tenant-id"; | ||
| pub(crate) const LAMBDA_RUNTIME_INVOCATION_ID: &str = "lambda-runtime-invocation-id"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| use crate::{ | ||
| constants::LAMBDA_RUNTIME_INVOCATION_ID, | ||
| deserializer, | ||
| requests::{EventCompletionRequest, IntoRequest}, | ||
| runtime::LambdaInvocation, | ||
|
|
@@ -123,9 +124,20 @@ where | |
| }; | ||
|
|
||
| let request_id = req.context.request_id.clone(); | ||
|
|
||
| // The invocation ID assigned by the Lambda runtime for cross-wiring protection. | ||
| // Echoed back on `/response` and `/error` to allow RAPID to reject stale responses | ||
| // from timed-out invocations. `None` when running against older RAPID versions | ||
| // that don't send this header | ||
| let invocation_id = req | ||
| .parts | ||
| .headers | ||
| .get(LAMBDA_RUNTIME_INVOCATION_ID) | ||
| .map(|v| String::from_utf8_lossy(v.as_bytes()).to_string()); | ||
|
|
||
| let lambda_event = match deserializer::deserialize::<EventPayload>(&req.body, req.context) { | ||
| Ok(lambda_event) => lambda_event, | ||
| Err(err) => match build_event_error_request(&request_id, err) { | ||
| Err(err) => match build_event_error_request(request_id, invocation_id, err) { | ||
| Ok(request) => return RuntimeApiResponseFuture::Ready(Box::new(Some(Ok(request)))), | ||
| Err(err) => { | ||
| error!(error = ?err, "failed to build error response for Lambda Runtime API"); | ||
|
|
@@ -137,23 +149,28 @@ where | |
| // Once the handler input has been generated successfully, pass it through to inner services | ||
| // allowing processing both before reaching the handler function and after the handler completes. | ||
| let fut = self.inner.call(lambda_event); | ||
| RuntimeApiResponseFuture::Future(fut, request_id, PhantomData) | ||
| RuntimeApiResponseFuture::Future(fut, request_id, invocation_id, PhantomData) | ||
| } | ||
| } | ||
|
|
||
| fn build_event_error_request<T>(request_id: &str, err: T) -> Result<http::Request<Body>, BoxError> | ||
| fn build_event_error_request<T>( | ||
| request_id: String, | ||
| invocation_id: Option<String>, | ||
| err: T, | ||
| ) -> Result<http::Request<Body>, BoxError> | ||
| where | ||
| T: Into<Diagnostic> + Debug, | ||
| { | ||
| error!(error = ?err, "Request payload deserialization into LambdaEvent<T> failed. The handler will not be called. Log at TRACE level to see the payload."); | ||
| EventErrorRequest::new(request_id, err).into_req() | ||
| EventErrorRequest::new(&request_id, invocation_id.as_deref(), err).into_req() | ||
| } | ||
|
|
||
| #[pin_project(project = RuntimeApiResponseFutureProj)] | ||
| pub enum RuntimeApiResponseFuture<F, Response, BufferedResponse, StreamingResponse, StreamItem, StreamError> { | ||
| Future( | ||
| #[pin] F, | ||
| String, | ||
| Option<String>, | ||
| PhantomData<( | ||
| (), | ||
| Response, | ||
|
|
@@ -183,11 +200,47 @@ where | |
|
|
||
| fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<Self::Output> { | ||
| task::Poll::Ready(match self.as_mut().project() { | ||
| RuntimeApiResponseFutureProj::Future(fut, request_id, _) => match ready!(fut.poll(cx)) { | ||
| Ok(ok) => EventCompletionRequest::new(request_id, ok).into_req(), | ||
| Err(err) => EventErrorRequest::new(request_id, err).into_req(), | ||
| RuntimeApiResponseFutureProj::Future(fut, request_id, invocation_id, _) => match ready!(fut.poll(cx)) { | ||
| Ok(ok) => EventCompletionRequest::new(request_id, invocation_id.as_deref(), ok).into_req(), | ||
| Err(err) => EventErrorRequest::new(request_id, invocation_id.as_deref(), err).into_req(), | ||
| }, | ||
| RuntimeApiResponseFutureProj::Ready(ready) => ready.take().expect("future polled after completion"), | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use crate::{constants::LAMBDA_RUNTIME_INVOCATION_ID, runtime::LambdaInvocation, Context}; | ||
| use http::{HeaderValue, Response}; | ||
| use serde_json::json; | ||
| use tower::{service_fn, Service}; | ||
|
|
||
| #[tokio::test] | ||
| async fn forwards_invocation_id_from_next_response_headers() { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be good to have a test covering the deserialization error path as well |
||
| let mut response = Response::new(()); | ||
| response | ||
| .headers_mut() | ||
| .insert(LAMBDA_RUNTIME_INVOCATION_ID, HeaderValue::from_static("invocation-123")); | ||
| let (parts, _) = response.into_parts(); | ||
|
|
||
| let mut service = RuntimeApiResponseService::new(service_fn(|_event: LambdaEvent<serde_json::Value>| async { | ||
| Ok::<_, Diagnostic>(json!({"ok": true})) | ||
| })); | ||
|
|
||
| let request = service | ||
| .call(LambdaInvocation { | ||
| parts, | ||
| body: bytes::Bytes::from_static(b"{}"), | ||
| context: Context::default(), | ||
| }) | ||
| .await | ||
| .expect("response request should be created"); | ||
|
|
||
| assert_eq!( | ||
| request.headers().get(LAMBDA_RUNTIME_INVOCATION_ID), | ||
| Some(&HeaderValue::from_static("invocation-123")), | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should have
#[serde(default)], otherwise the example command in the header will actually have a deserialization failure.