generated from amazon-archives/__template_Apache-2.0
    
        
        - 
                Notifications
    You must be signed in to change notification settings 
- Fork 221
          feat: support for server lambda_http::Request
          #1551
        
          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
          
     Merged
      
      
    
  
     Merged
                    Changes from 14 commits
      Commits
    
    
            Show all changes
          
          
            18 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      a967ce9
              
                feat: start support for lambda_http request
              
              
                hugobast c66e7b0
              
                deps: update lambda http to 0.6.0
              
              
                hugobast 5d79679
              
                feat: lambda_http run example to pokemon service
              
              
                hugobast 376f9da
              
                refactor: refer to lambda_http error
              
              
                hugobast d6ab123
              
                feat: lambda_http body support for byte stream
              
              
                hugobast f79ad5e
              
                feat: convert request event
              
              
                hugobast d6b13dd
              
                refactor: code review suggestions
              
              
                hugobast 10253e8
              
                refactor: replace false make service with handler
              
              
                hugobast f2de3c5
              
                chore: reword comment and remove unrelated ticket
              
              
                hugobast 0004afd
              
                feat: support for claim that we strip uri stage
              
              
                hugobast d720fa0
              
                chore: fix a few ci jobs
              
              
                hugobast 543a5a5
              
                fix: adjust lambda handler documentation
              
              
                hugobast 0a763ac
              
                fix: main bin was renamed to bootsrap
              
              
                hugobast f78c597
              
                Merge branch 'main' into main
              
              
                hugobast 6191b0d
              
                Update rust-runtime/aws-smithy-http-server/examples/pokemon-service/s…
              
              
                david-perez 466dbca
              
                Merge branch 'main' into main
              
              
                david-perez 47be7e1
              
                Update CHANGELOG.next.toml
              
              
                david-perez 9a8cae7
              
                Update CHANGELOG.next.toml
              
              
                david-perez 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 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
    
  
  
    
              
        
          
  
    
      
          
            52 changes: 52 additions & 0 deletions
          
          52 
        
  rust-runtime/aws-smithy-http-server/examples/pokemon-service/src/lambda.rs
  
  
      
      
   
        
      
      
    
  
    
      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,52 @@ | ||
| /* | ||
| * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|  | ||
| // This program is exported as a binary named `pokemon_service`. | ||
|         
                  david-perez marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| use std::sync::Arc; | ||
|  | ||
| use aws_smithy_http_server::{routing::LambdaHandler, AddExtensionLayer, Router}; | ||
| use pokemon_service::{ | ||
| capture_pokemon, empty_operation, get_pokemon_species, get_server_statistics, get_storage, health_check_operation, | ||
| setup_tracing, State, | ||
| }; | ||
| use pokemon_service_server_sdk::operation_registry::OperationRegistryBuilder; | ||
| use tower::ServiceBuilder; | ||
| use tower_http::trace::TraceLayer; | ||
|  | ||
| #[tokio::main] | ||
| pub async fn main() { | ||
| setup_tracing(); | ||
|  | ||
| let app: Router = OperationRegistryBuilder::default() | ||
| // Build a registry containing implementations to all the operations in the service. These | ||
| // are async functions or async closures that take as input the operation's input and | ||
| // return the operation's output. | ||
| .get_pokemon_species(get_pokemon_species) | ||
| .get_storage(get_storage) | ||
| .get_server_statistics(get_server_statistics) | ||
| .capture_pokemon_operation(capture_pokemon) | ||
| .empty_operation(empty_operation) | ||
| .health_check_operation(health_check_operation) | ||
| .build() | ||
| .expect("Unable to build operation registry") | ||
| // Convert it into a router that will route requests to the matching operation | ||
| // implementation. | ||
| .into(); | ||
|  | ||
| // Setup shared state and middlewares. | ||
| let shared_state = Arc::new(State::default()); | ||
| let app = app.layer( | ||
| ServiceBuilder::new() | ||
| .layer(TraceLayer::new_for_http()) | ||
| .layer(AddExtensionLayer::new(shared_state)), | ||
| ); | ||
|  | ||
| let handler = LambdaHandler::new(app); | ||
| let lambda = lambda_http::run(handler); | ||
|  | ||
| if let Err(err) = lambda.await { | ||
| eprintln!("lambda error: {}", err); | ||
| } | ||
| } | ||
        
          
  
    
      
          
            89 changes: 89 additions & 0 deletions
          
          89 
        
  ...aws-smithy-http-server/examples/pokemon-service/tests/fixtures/example-apigw-request.json
  
  
      
      
   
        
      
      
    
  
    
      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,89 @@ | ||
| { | ||
| "body": null, | ||
| "headers": { | ||
| "Accept": "application/json", | ||
| "Accept-Encoding": "gzip, deflate", | ||
| "cache-control": "no-cache", | ||
| "CloudFront-Forwarded-Proto": "https", | ||
| "CloudFront-Is-Desktop-Viewer": "true", | ||
| "CloudFront-Is-Mobile-Viewer": "false", | ||
| "CloudFront-Is-SmartTV-Viewer": "false", | ||
| "CloudFront-Is-Tablet-Viewer": "false", | ||
| "CloudFront-Viewer-Country": "US", | ||
| "Content-Type": "application/json", | ||
| "headerName": "headerValue", | ||
| "Host": "gy415nuibc.execute-api.us-east-1.amazonaws.com", | ||
| "Postman-Token": "9f583ef0-ed83-4a38-aef3-eb9ce3f7a57f", | ||
| "User-Agent": "PostmanRuntime/2.4.5", | ||
| "Via": "1.1 d98420743a69852491bbdea73f7680bd.cloudfront.net (CloudFront)", | ||
| "X-Amz-Cf-Id": "pn-PWIJc6thYnZm5P0NMgOUglL1DYtl0gdeJky8tqsg8iS_sgsKD1A==", | ||
| "X-Forwarded-For": "54.240.196.186, 54.182.214.83", | ||
| "X-Forwarded-Port": "443", | ||
| "X-Forwarded-Proto": "https" | ||
| }, | ||
| "httpMethod": "GET", | ||
| "isBase64Encoded": false, | ||
| "multiValueHeaders": { | ||
| "Accept": ["application/json"], | ||
| "Accept-Encoding": ["gzip, deflate"], | ||
| "cache-control": ["no-cache"], | ||
| "CloudFront-Forwarded-Proto": ["https"], | ||
| "CloudFront-Is-Desktop-Viewer": ["true"], | ||
| "CloudFront-Is-Mobile-Viewer": ["false"], | ||
| "CloudFront-Is-SmartTV-Viewer": ["false"], | ||
| "CloudFront-Is-Tablet-Viewer": ["false"], | ||
| "CloudFront-Viewer-Country": ["US"], | ||
| "Content-Type": ["application/json"], | ||
| "headerName": ["headerValue"], | ||
| "Host": ["gy415nuibc.execute-api.us-east-1.amazonaws.com"], | ||
| "Postman-Token": ["9f583ef0-ed83-4a38-aef3-eb9ce3f7a57f"], | ||
| "User-Agent": ["PostmanRuntime/2.4.5"], | ||
| "Via": ["1.1 d98420743a69852491bbdea73f7680bd.cloudfront.net (CloudFront)"], | ||
| "X-Amz-Cf-Id": ["pn-PWIJc6thYnZm5P0NMgOUglL1DYtl0gdeJky8tqsg8iS_sgsKD1A=="], | ||
| "X-Forwarded-For": ["54.240.196.186, 54.182.214.83"], | ||
| "X-Forwarded-Port": ["443"], | ||
| "X-Forwarded-Proto": ["https"] | ||
| }, | ||
| "multiValueQueryStringParameters": { | ||
| "key": ["value"] | ||
| }, | ||
| "path": "/stats", | ||
| "pathParameters": null, | ||
| "queryStringParameters": { | ||
| "key": "value" | ||
| }, | ||
| "requestContext": { | ||
| "accountId": "xxxxx", | ||
| "apiId": "xxxxx", | ||
| "domainName": "testPrefix.testDomainName", | ||
| "domainPrefix": "testPrefix", | ||
| "extendedRequestId": "NvWWKEZbliAFliA=", | ||
| "httpMethod": "GET", | ||
| "identity": { | ||
| "accessKey": "xxxxx", | ||
| "accountId": "xxxxx", | ||
| "apiKey": "test-invoke-api-key", | ||
| "apiKeyId": "test-invoke-api-key-id", | ||
| "caller": "xxxxx:xxxxx", | ||
| "cognitoAuthenticationProvider": null, | ||
| "cognitoAuthenticationType": null, | ||
| "cognitoIdentityId": null, | ||
| "cognitoIdentityPoolId": null, | ||
| "principalOrgId": null, | ||
| "sourceIp": "test-invoke-source-ip", | ||
| "user": "xxxxx:xxxxx", | ||
| "userAgent": "aws-internal/3 aws-sdk-java/1.12.154 Linux/5.4.156-94.273.amzn2int.x86_64 OpenJDK_64-Bit_Server_VM/25.322-b06 java/1.8.0_322 vendor/Oracle_Corporation cfg/retry-mode/standard", | ||
| "userArn": "arn:aws:sts::xxxxx:assumed-role/xxxxx/xxxxx" | ||
| }, | ||
| "path": "/stats", | ||
| "protocol": "HTTP/1.1", | ||
| "requestId": "e5488776-afe4-4e5e-92b1-37bd23f234d6", | ||
| "requestTime": "18/Feb/2022:13:23:12 +0000", | ||
| "requestTimeEpoch": 1645190592806, | ||
| "resourceId": "ddw8yd", | ||
| "resourcePath": "/stats", | ||
| "stage": "test-invoke-stage" | ||
| }, | ||
| "resource": "/stats", | ||
| "stageVariables": null | ||
| } | 
  
    
      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
    
  
  
    
              
        
          
  
    
      
          
            120 changes: 120 additions & 0 deletions
          
          120 
        
  rust-runtime/aws-smithy-http-server/src/routing/lambda_handler.rs
  
  
      
      
   
        
      
      
    
  
    
      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,120 @@ | ||
| /* | ||
| * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| * SPDX-License-Identifier: Apache-2.0 | ||
| */ | ||
|  | ||
| use http::uri; | ||
| use lambda_http::{Request, RequestExt}; | ||
| use std::{ | ||
| fmt::Debug, | ||
| task::{Context, Poll}, | ||
| }; | ||
| use tower::Service; | ||
|  | ||
| type HyperRequest = http::Request<hyper::Body>; | ||
|  | ||
| /// A [`Service`] that takes a `lambda_http::Request` and converts | ||
| /// it to `http::Request<hyper::Body>`. | ||
| /// | ||
| /// [`Service`]: tower::Service | ||
| #[derive(Debug, Clone)] | ||
| pub struct LambdaHandler<S> { | ||
| service: S, | ||
| } | ||
|  | ||
| impl<S> LambdaHandler<S> { | ||
| pub fn new(service: S) -> Self { | ||
| Self { service } | ||
| } | ||
| } | ||
|  | ||
| impl<S> Service<Request> for LambdaHandler<S> | ||
| where | ||
| S: Service<HyperRequest>, | ||
| { | ||
| type Error = S::Error; | ||
| type Response = S::Response; | ||
| type Future = S::Future; | ||
|  | ||
| #[inline] | ||
| fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { | ||
| self.service.poll_ready(cx) | ||
| } | ||
|  | ||
| fn call(&mut self, event: Request) -> Self::Future { | ||
| self.service.call(convert_event(event)) | ||
| } | ||
| } | ||
|  | ||
| /// Converts a `lambda_http::Request` into a `http::Request<hyper::Body>` | ||
| /// Issue: <https://github.com/awslabs/smithy-rs/issues/1125> | ||
| /// | ||
| /// While converting the event the [API Gateway Stage] portion of the URI | ||
| /// is removed from the uri that gets returned as a new `http::Request`. | ||
| /// | ||
| /// [API Gateway Stage]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-stages.html | ||
| fn convert_event(request: Request) -> HyperRequest { | ||
| let raw_path = request.raw_http_path(); | ||
| let (mut parts, body) = request.into_parts(); | ||
| let mut path = String::from(parts.uri.path()); | ||
|  | ||
| if !raw_path.is_empty() && raw_path != path { | ||
| path = raw_path; | ||
|  | ||
| let uri_parts: uri::Parts = parts.uri.into(); | ||
| let path_and_query = uri_parts | ||
| .path_and_query | ||
| .expect("request URI does not have `PathAndQuery`"); | ||
|  | ||
| if let Some(query) = path_and_query.query() { | ||
| path.push('?'); | ||
| path.push_str(query); | ||
| } | ||
|  | ||
| parts.uri = uri::Uri::builder() | ||
| .authority(uri_parts.authority.expect("request URI does not have authority set")) | ||
| .scheme(uri_parts.scheme.expect("request URI does not have scheme set")) | ||
| .path_and_query(path) | ||
| .build() | ||
| .expect("unable to construct new URI"); | ||
| } | ||
|  | ||
| let body = match body { | ||
| lambda_http::Body::Empty => hyper::Body::empty(), | ||
| lambda_http::Body::Text(s) => hyper::Body::from(s), | ||
| lambda_http::Body::Binary(v) => hyper::Body::from(v), | ||
| }; | ||
|  | ||
| http::Request::from_parts(parts, body) | ||
| } | ||
|  | ||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use lambda_http::RequestExt; | ||
|  | ||
| #[test] | ||
| fn traits() { | ||
| use crate::test_helpers::*; | ||
|  | ||
| assert_send::<LambdaHandler<()>>(); | ||
| assert_sync::<LambdaHandler<()>>(); | ||
| } | ||
|  | ||
| #[test] | ||
| fn raw_http_path() { | ||
| // lambda_http::Request doesn't have a fn `builder` | ||
| let event = http::Request::builder() | ||
| .uri("https://id.execute-api.us-east-1.amazonaws.com/prod/resources/1") | ||
| .body(()) | ||
| .expect("unable to build Request"); | ||
| let (parts, _) = event.into_parts(); | ||
|  | ||
| // the lambda event will have a raw path which is the path without stage name in it | ||
| let event = | ||
| lambda_http::Request::from_parts(parts, lambda_http::Body::Empty).with_raw_http_path("/resources/1"); | ||
| let request = convert_event(event); | ||
|  | ||
| assert_eq!(request.uri().path(), "/resources/1") | ||
| } | ||
| } | 
  
    
      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
    
  
  
    
              
  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.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.