Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/run-integration-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions lambda-integration-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
30 changes: 27 additions & 3 deletions lambda-integration-tests/src/authorizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,26 @@ async fn func(
) -> Result<ApiGatewayCustomAuthorizerResponse, Error> {
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:<partition>:execute-api:<region>:<account>:<api-id>/<stage>/<verb>/<path>`.
fn stage_arn(method_arn: &str) -> Option<String> {
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")]
Expand Down Expand Up @@ -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);
}
}
39 changes: 39 additions & 0 deletions lambda-integration-tests/src/response_streaming.rs
Original file line number Diff line number Diff line change
@@ -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<Value>) -> Result<StreamResponse<Body>, 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,
})
}
25 changes: 24 additions & 1 deletion lambda-integration-tests/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
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/"
20 changes: 20 additions & 0 deletions lambda-integration-tests/tests/response_streaming_test.rs
Original file line number Diff line number Diff line change
@@ -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");
}
3 changes: 3 additions & 0 deletions lambda-runtime-api-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
54 changes: 52 additions & 2 deletions lambda-runtime-api-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<B>(base: &Uri, req: Request<B>) -> Result<Request<B>, BoxError> {
let (mut parts, body) = req.into_parts();
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 }
}
Expand Down Expand Up @@ -379,4 +397,36 @@ mod tests {
client.reset_pool();
assert_eq!(client.base, base.parse::<Uri>().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);
}
}
Loading