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..71e76d00d 100644 --- a/lambda-integration-tests/src/authorizer.rs +++ b/lambda-integration-tests/src/authorizer.rs @@ -28,16 +28,26 @@ 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)); + // 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"); } -fn allow(method_arn: &str) -> ApiGatewayCustomAuthorizerResponse { +/// 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(); 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")] @@ -67,3 +77,17 @@ fn allow(method_arn: &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/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..ac11fc254 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: @@ -74,4 +94,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); + } }