From a0aea3dae985284314be76033e4319f2e9d06d14 Mon Sep 17 00:00:00 2001 From: Jad Chaar Date: Tue, 24 Nov 2026 00:28:18 +0000 Subject: [PATCH 1/2] fix(lambda-runtime-api-client): enable TCP_NODELAY on the Runtime API connection hyper-util's HttpConnector leaves TCP_NODELAY off. With Nagle's algorithm on, the kernel holds the small tail of a streamed response until the Runtime API sends its delayed ACK. This adds about 40 ms to a small streamed response. Enable TCP_NODELAY on the default connector of ClientBuilder and PooledClientBuilder. A connector passed to with_connector is used as-is. Also add an integration test for response streaming through API Gateway. --- .github/workflows/run-integration-test.yml | 3 ++ lambda-integration-tests/Cargo.toml | 4 ++ lambda-integration-tests/src/authorizer.rs | 10 ++-- .../src/response_streaming.rs | 39 ++++++++++++++ lambda-integration-tests/template.yaml | 31 ++++++++++- .../tests/response_streaming_test.rs | 20 +++++++ lambda-runtime-api-client/Cargo.toml | 3 ++ lambda-runtime-api-client/src/lib.rs | 54 ++++++++++++++++++- 8 files changed, 157 insertions(+), 7 deletions(-) create mode 100644 lambda-integration-tests/src/response_streaming.rs create mode 100644 lambda-integration-tests/tests/response_streaming_test.rs diff --git a/.github/workflows/run-integration-test.yml b/.github/workflows/run-integration-test.yml index d43ed9c71..b6a403df0 100644 --- a/.github/workflows/run-integration-test.yml +++ b/.github/workflows/run-integration-test.yml @@ -54,13 +54,16 @@ jobs: sam deploy --stack-name "${stackName}" --parameter-overrides "ParameterKey=SecretToken,ParameterValue=${{ secrets.SECRET_TOKEN }}" "ParameterKey=LambdaRole,ParameterValue=${{ secrets.AWS_LAMBDA_ROLE }}" --no-confirm-changeset --no-progressbar > disable_output TEST_ENDPOINT=$(sam list stack-outputs --stack-name "${stackName}" --output json | jq -r '.[] | select(.OutputKey=="HelloApiEndpoint") | .OutputValue') TENANT_ID_TEST_FUNCTION=$(sam list stack-outputs --stack-name "${stackName}" --output json | jq -r '.[] | select(.OutputKey=="TenantIdTestFunction") | .OutputValue') + STREAM_TEST_ENDPOINT=$(sam list stack-outputs --stack-name "${stackName}" --output json | jq -r '.[] | select(.OutputKey=="StreamApiEndpoint") | .OutputValue') echo "TEST_ENDPOINT=$TEST_ENDPOINT" >> "$GITHUB_OUTPUT" echo "TENANT_ID_TEST_FUNCTION=$TENANT_ID_TEST_FUNCTION" >> "$GITHUB_OUTPUT" + echo "STREAM_TEST_ENDPOINT=$STREAM_TEST_ENDPOINT" >> "$GITHUB_OUTPUT" - name: run test env: SECRET_TOKEN: ${{ secrets.SECRET_TOKEN }} TEST_ENDPOINT: ${{ steps.deploy_stack.outputs.TEST_ENDPOINT }} TENANT_ID_TEST_FUNCTION: ${{ steps.deploy_stack.outputs.TENANT_ID_TEST_FUNCTION }} + STREAM_TEST_ENDPOINT: ${{ steps.deploy_stack.outputs.STREAM_TEST_ENDPOINT }} run: cd lambda-integration-tests && cargo test - name: cleanup if: always() && steps.deploy_stack.outputs.STACK_NAME diff --git a/lambda-integration-tests/Cargo.toml b/lambda-integration-tests/Cargo.toml index e2497333e..9a4d3056b 100644 --- a/lambda-integration-tests/Cargo.toml +++ b/lambda-integration-tests/Cargo.toml @@ -36,3 +36,7 @@ path = "src/authorizer.rs" [[bin]] name = "tenant-id-test" path = "src/tenant_id_test.rs" + +[[bin]] +name = "response-streaming" +path = "src/response_streaming.rs" diff --git a/lambda-integration-tests/src/authorizer.rs b/lambda-integration-tests/src/authorizer.rs index 23f17b296..d18cb25d8 100644 --- a/lambda-integration-tests/src/authorizer.rs +++ b/lambda-integration-tests/src/authorizer.rs @@ -12,7 +12,6 @@ use serde_json::json; #[serde(rename_all = "camelCase")] struct APIGatewayCustomAuthorizerRequest { authorization_token: String, - method_arn: String, } #[tokio::main] @@ -28,16 +27,19 @@ async fn func( ) -> Result { let expected_token = env::var("SECRET_TOKEN").expect("could not read the secret token"); if event.payload.authorization_token == expected_token { - return Ok(allow(&event.payload.method_arn)); + // The policy allows every route of the API, not only the called method, because API Gateway + // caches it by token. See ALLOWED_RESOURCE in template.yaml. + let allowed_resource = env::var("ALLOWED_RESOURCE").expect("could not read the allowed resource"); + return Ok(allow(&allowed_resource)); } panic!("token is not valid"); } -fn allow(method_arn: &str) -> ApiGatewayCustomAuthorizerResponse { +fn allow(resource: &str) -> ApiGatewayCustomAuthorizerResponse { let stmt = { let mut statement = IamPolicyStatement::default(); statement.action = vec!["execute-api:Invoke".to_string()]; - statement.resource = vec![method_arn.to_owned()]; + statement.resource = vec![resource.to_owned()]; statement.effect = aws_lambda_events::iam::IamPolicyEffect::Allow; statement.condition = None; #[cfg(feature = "catch-all-fields")] diff --git a/lambda-integration-tests/src/response_streaming.rs b/lambda-integration-tests/src/response_streaming.rs new file mode 100644 index 000000000..5907fcb82 --- /dev/null +++ b/lambda-integration-tests/src/response_streaming.rs @@ -0,0 +1,39 @@ +use aws_lambda_events::http::{header::CONTENT_TYPE, HeaderMap, StatusCode}; +use lambda_runtime::{ + service_fn, + streaming::{channel, Body}, + tracing, Error, LambdaEvent, MetadataPrelude, StreamResponse, +}; +use serde_json::Value; + +#[tokio::main] +async fn main() -> Result<(), Error> { + tracing::init_default_subscriber(); + lambda_runtime::run(service_fn(func)).await +} + +async fn func(_event: LambdaEvent) -> Result, Error> { + // A non-default status and a custom header prove that API Gateway applies the metadata prelude. + let mut headers = HeaderMap::new(); + headers.insert(CONTENT_TYPE, "text/plain".parse().unwrap()); + headers.insert("x-response-mode", "streaming".parse().unwrap()); + + let (mut tx, rx) = channel(); + tokio::spawn(async move { + for chunk in ["Hello", " from a", " streamed response"] { + if tx.send_data(chunk.into()).await.is_err() { + tracing::error!("response stream closed before all chunks were sent"); + return; + } + } + }); + + Ok(StreamResponse { + metadata_prelude: MetadataPrelude { + status_code: StatusCode::CREATED, + headers, + cookies: Vec::new(), + }, + stream: rx, + }) +} diff --git a/lambda-integration-tests/template.yaml b/lambda-integration-tests/template.yaml index 9ba694e32..755934367 100644 --- a/lambda-integration-tests/template.yaml +++ b/lambda-integration-tests/template.yaml @@ -53,6 +53,26 @@ Resources: Runtime: provided.al2023 Role: !Ref LambdaRole + ResponseStreamingFunction: + Type: AWS::Serverless::Function + Metadata: + BuildMethod: rust-cargolambda + BuildProperties: + Binary: response-streaming + Properties: + CodeUri: ./ + Handler: bootstrap + Runtime: provided.al2023 + Role: !Ref LambdaRole + Events: + Stream: + Type: Api + Properties: + RestApiId: !Ref API + Path: /stream + Method: get + ResponseTransferMode: RESPONSE_STREAM + AuthorizerFunction: Type: AWS::Serverless::Function Metadata: @@ -67,6 +87,12 @@ Resources: Environment: Variables: SECRET_TOKEN: !Ref SecretToken + # API Gateway caches the authorizer policy by token and uses it for every route of the API. + # Thus the policy must allow all routes. A policy for only the first route (for example, + # /hello) denies the next route (/stream) until the cache expires. + # The API ID is a wildcard. The API refers to this function, so a reference to the API + # makes a circular dependency. + ALLOWED_RESOURCE: !Sub "arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:*/integ-test/*/*" Outputs: HelloApiEndpoint: @@ -74,4 +100,7 @@ Outputs: Value: !Sub "https://${API}.execute-api.${AWS::Region}.amazonaws.com/integ-test/hello/" TenantIdTestFunction: Description: "Tenant ID test function name" - Value: !Ref TenantIdTestFunction \ No newline at end of file + Value: !Ref TenantIdTestFunction + StreamApiEndpoint: + Description: "API Gateway endpoint URL for the response streaming function" + Value: !Sub "https://${API}.execute-api.${AWS::Region}.amazonaws.com/integ-test/stream/" \ No newline at end of file diff --git a/lambda-integration-tests/tests/response_streaming_test.rs b/lambda-integration-tests/tests/response_streaming_test.rs new file mode 100644 index 000000000..d8add11ea --- /dev/null +++ b/lambda-integration-tests/tests/response_streaming_test.rs @@ -0,0 +1,20 @@ +#[test] +fn test_streamed_response_should_return_prelude_and_body() { + let test_endpoint = std::env::var("STREAM_TEST_ENDPOINT").expect("could not read STREAM_TEST_ENDPOINT"); + let secret_token = std::env::var("SECRET_TOKEN").expect("could not read SECRET_TOKEN"); + let client = reqwest::blocking::Client::new(); + let res = client + .get(test_endpoint) + .header("Authorization", secret_token) + .send() + .expect("could not send the request"); + let status = res.status(); + let headers = res.headers().clone(); + let body = res.text().expect("could not read the response body"); + + // The status code and headers come from the metadata prelude of the streamed response. + assert_eq!(status, 201, "unexpected status, body: {body}"); + assert_eq!(headers["content-type"], "text/plain"); + assert_eq!(headers["x-response-mode"], "streaming"); + assert_eq!(body, "Hello from a streamed response"); +} diff --git a/lambda-runtime-api-client/Cargo.toml b/lambda-runtime-api-client/Cargo.toml index d1fb622c9..146f12e0c 100644 --- a/lambda-runtime-api-client/Cargo.toml +++ b/lambda-runtime-api-client/Cargo.toml @@ -36,5 +36,8 @@ tower = { workspace = true, features = ["util"] } tracing = { version = "0.1", features = ["log"], optional = true } tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "json", "env-filter"], optional = true } +[dev-dependencies] +tokio = { version = "1.0", features = ["macros", "net", "rt"] } + [package.metadata.docs.rs] all-features = true diff --git a/lambda-runtime-api-client/src/lib.rs b/lambda-runtime-api-client/src/lib.rs index ead8abe75..98fc83991 100644 --- a/lambda-runtime-api-client/src/lib.rs +++ b/lambda-runtime-api-client/src/lib.rs @@ -167,6 +167,18 @@ fn build_hyper_client( builder.build(connector.clone()) } +/// Build the default HTTP connector for the Runtime API. +/// +/// `TCP_NODELAY` is enabled to turn off Nagle's algorithm. A streaming response is sent as +/// several small writes (request head, metadata prelude, delimiter, body chunks). With Nagle's +/// algorithm on, the kernel holds a small write until earlier data is acknowledged, and the +/// Runtime API can delay that ACK by 40 ms or more. +fn default_connector() -> HttpConnector { + let mut connector = HttpConnector::new(); + connector.set_nodelay(true); + connector +} + /// Rewrite a request's URI against the client's base (scheme/authority/base path). fn set_origin(base: &Uri, req: Request) -> Result, BoxError> { let (mut parts, body) = req.into_parts(); @@ -200,13 +212,16 @@ pub struct ClientBuilder { impl ClientBuilder { fn new() -> ClientBuilder { ClientBuilder { - connector: HttpConnector::new(), + connector: default_connector(), uri: None, pool_size: None, } } /// Create a new builder with a given HTTP connector. + /// + /// The connector is used as-is. The default connector enables `TCP_NODELAY`. + /// To keep that behavior, call `set_nodelay(true)` on the given connector. pub fn with_connector(self, connector: HttpConnector) -> ClientBuilder { ClientBuilder { connector, @@ -255,13 +270,16 @@ pub struct PooledClientBuilder { impl PooledClientBuilder { fn new() -> PooledClientBuilder { PooledClientBuilder { - connector: HttpConnector::new(), + connector: default_connector(), uri: None, pool_size: None, } } /// Use a given HTTP connector. + /// + /// The connector is used as-is. The default connector enables `TCP_NODELAY`. + /// To keep that behavior, call `set_nodelay(true)` on the given connector. pub fn with_connector(self, connector: HttpConnector) -> PooledClientBuilder { PooledClientBuilder { connector, ..self } } @@ -379,4 +397,36 @@ mod tests { client.reset_pool(); assert_eq!(client.base, base.parse::().unwrap()); } + + /// Open a TCP connection with the given connector and return whether `TCP_NODELAY` is set. + async fn connection_has_nodelay(connector: HttpConnector) -> bool { + use tower::ServiceExt; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let uri: Uri = format!("http://{}", listener.local_addr().unwrap()).parse().unwrap(); + let io = connector.oneshot(uri).await.unwrap(); + io.inner().nodelay().unwrap() + } + + #[tokio::test] + async fn default_connectors_enable_nodelay() { + assert!(connection_has_nodelay(ClientBuilder::new().connector).await); + + let client = PooledClient::builder() + .with_endpoint("http://localhost:9001".parse().unwrap()) + .build(); + assert!(connection_has_nodelay(client.connector).await); + } + + #[tokio::test] + async fn custom_connector_is_used_as_is() { + let mut connector = HttpConnector::new(); + connector.set_nodelay(false); + + let builder = ClientBuilder::new().with_connector(connector.clone()); + assert!(!connection_has_nodelay(builder.connector).await); + + let builder = PooledClient::builder().with_connector(connector); + assert!(!connection_has_nodelay(builder.connector).await); + } } From 748684e516fdc95d92bf432ba3101c949c8caeb5 Mon Sep 17 00:00:00 2001 From: Jad Chaar Date: Tue, 24 Nov 2026 06:08:35 +0000 Subject: [PATCH 2/2] test(lambda-integration-tests): build the authorizer policy from methodArn Allow every route in the stage of the calling API (//*/*) instead of reading a wildcard resource from ALLOWED_RESOURCE. This keeps the policy scoped to the calling API and removes the environment variable. --- lambda-integration-tests/src/authorizer.rs | 30 +++++++++++++++++++--- lambda-integration-tests/template.yaml | 6 ----- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/lambda-integration-tests/src/authorizer.rs b/lambda-integration-tests/src/authorizer.rs index d18cb25d8..71e76d00d 100644 --- a/lambda-integration-tests/src/authorizer.rs +++ b/lambda-integration-tests/src/authorizer.rs @@ -12,6 +12,7 @@ use serde_json::json; #[serde(rename_all = "camelCase")] struct APIGatewayCustomAuthorizerRequest { authorization_token: String, + method_arn: String, } #[tokio::main] @@ -27,14 +28,21 @@ async fn func( ) -> Result { let expected_token = env::var("SECRET_TOKEN").expect("could not read the secret token"); if event.payload.authorization_token == expected_token { - // The policy allows every route of the API, not only the called method, because API Gateway - // caches it by token. See ALLOWED_RESOURCE in template.yaml. - let allowed_resource = env::var("ALLOWED_RESOURCE").expect("could not read the allowed resource"); - return Ok(allow(&allowed_resource)); + // API Gateway caches the policy by token and uses it for every route of the API. + // Thus the policy allows every route in the stage, not only the called method. + let resource = stage_arn(&event.payload.method_arn).ok_or("unexpected method ARN")?; + return Ok(allow(&resource)); } panic!("token is not valid"); } +/// Returns the ARN for all methods in the stage of `method_arn`. A method ARN has the format +/// `arn::execute-api:::///`. +fn stage_arn(method_arn: &str) -> Option { + let mut parts = method_arn.splitn(3, '/'); + Some(format!("{}/{}/*/*", parts.next()?, parts.next()?)) +} + fn allow(resource: &str) -> ApiGatewayCustomAuthorizerResponse { let stmt = { let mut statement = IamPolicyStatement::default(); @@ -69,3 +77,17 @@ fn allow(resource: &str) -> ApiGatewayCustomAuthorizerResponse { } response } + +#[cfg(test)] +mod tests { + use super::stage_arn; + + #[test] + fn stage_arn_allows_all_methods_in_the_stage() { + assert_eq!( + stage_arn("arn:aws:execute-api:us-west-2:123456789012:abc123/integ-test/GET/hello").as_deref(), + Some("arn:aws:execute-api:us-west-2:123456789012:abc123/integ-test/*/*") + ); + assert_eq!(stage_arn("arn:aws:execute-api:us-west-2:123456789012:abc123"), None); + } +} diff --git a/lambda-integration-tests/template.yaml b/lambda-integration-tests/template.yaml index 755934367..ac11fc254 100644 --- a/lambda-integration-tests/template.yaml +++ b/lambda-integration-tests/template.yaml @@ -87,12 +87,6 @@ Resources: Environment: Variables: SECRET_TOKEN: !Ref SecretToken - # API Gateway caches the authorizer policy by token and uses it for every route of the API. - # Thus the policy must allow all routes. A policy for only the first route (for example, - # /hello) denies the next route (/stream) until the cache expires. - # The API ID is a wildcard. The API refers to this function, so a reference to the API - # makes a circular dependency. - ALLOWED_RESOURCE: !Sub "arn:${AWS::Partition}:execute-api:${AWS::Region}:${AWS::AccountId}:*/integ-test/*/*" Outputs: HelloApiEndpoint: