-
Notifications
You must be signed in to change notification settings - Fork 20
Add a dedicated lambda bin
#218
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 12 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
723ddb6
Factor out build app core logic to lib
rustworthy f7e6d9b
Ty clippy
rustworthy b2d43e8
Update deploy docs
rustworthy 2e82b3d
Add --bin lambda to CI jobs
rustworthy 95c5c49
Allow Backend::local unused
rustworthy cc89d6f
Add default run to Cargo.toml
rustworthy 3f5a33f
Use IndexedRandom trait
rustworthy f296fc4
Rename build_app -> new
rustworthy 6103bce
Add CargoLambda.toml config file
rustworthy 3d49629
Add binary name to deploy in CargoLambda.toml
rustworthy 0f94f9b
Restore wewerewondering_api=trace in README notes
rustworthy 9004d86
Upd docs in infra/lambda.tf
rustworthy 2f17ca4
Avoid free-standing new at callsites
jonhoo 4515fdd
Merge branch 'main' into release-not-special
jonhoo bffa993
Maybe make plan work
jonhoo dcf76c2
apparently not
jonhoo 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| # https://www.cargo-lambda.info/guide/configuration.html#global-configuration-files | ||
| # | ||
| # This allows us to offload the `cargo build` command, so we can run | ||
| # `cargo lambda build --release --arm64` on CI only specifying profile and | ||
| # architecture. If we decide to change the binary's name, we will be no need to | ||
| # go and adjust configuration neither on the CI workflows, nor in the SAM's | ||
| # `template.yaml` that we are using to run a local instance of API Gateway | ||
| # for testing purposes. | ||
| # | ||
| # NB! IF we decide to add more build parameters here, let's not forget to check | ||
| # that sam local is still building and running ok with: | ||
| # ```console | ||
| # $ sam build | ||
| # S sam local start-api | ||
| # ``` | ||
| [build] | ||
| bin = ["lambda"] | ||
|
|
||
| [deploy] | ||
| binary_name = "lambda" | ||
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,87 @@ | ||
| use axum::response::IntoResponse; | ||
| use http_body_util::BodyExt; | ||
| use lambda_http::Error; | ||
| use std::{future::Future, pin::Pin}; | ||
| use tower::Layer; | ||
| use tower_http::trace::TraceLayer; | ||
| use tower_service::Service; | ||
| use tracing_subscriber::EnvFilter; | ||
| use wewerewondering_api::new; | ||
|
|
||
| #[tokio::main] | ||
| async fn main() -> Result<(), Error> { | ||
| tracing_subscriber::fmt() | ||
| .with_env_filter(EnvFilter::from_default_env()) | ||
| .without_time(/* cloudwatch does that */) | ||
| .init(); | ||
|
|
||
| let app = new().await; | ||
| // To run with AWS Lambda runtime, wrap in our `LambdaLayer` | ||
| let app = tower::ServiceBuilder::new() | ||
| .layer(TraceLayer::new_for_http()) | ||
| .layer(LambdaLayer) | ||
| .service(app); | ||
|
|
||
| lambda_http::run(app).await | ||
| } | ||
|
|
||
| #[derive(Clone, Copy)] | ||
| pub struct LambdaLayer; | ||
|
|
||
| impl<S> Layer<S> for LambdaLayer { | ||
| type Service = LambdaService<S>; | ||
|
|
||
| fn layer(&self, inner: S) -> Self::Service { | ||
| LambdaService { inner } | ||
| } | ||
| } | ||
|
|
||
| pub struct LambdaService<S> { | ||
| inner: S, | ||
| } | ||
|
|
||
| impl<S> Service<lambda_http::Request> for LambdaService<S> | ||
| where | ||
| S: Service<axum::http::Request<axum::body::Body>>, | ||
| S::Response: axum::response::IntoResponse + Send + 'static, | ||
| S::Error: std::error::Error + Send + Sync + 'static, | ||
| S::Future: Send + 'static, | ||
| { | ||
| type Response = lambda_http::Response<lambda_http::Body>; | ||
| type Error = lambda_http::Error; | ||
| type Future = | ||
| Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>; | ||
|
|
||
| fn poll_ready( | ||
| &mut self, | ||
| cx: &mut std::task::Context<'_>, | ||
| ) -> std::task::Poll<Result<(), Self::Error>> { | ||
| self.inner.poll_ready(cx).map_err(Into::into) | ||
| } | ||
|
|
||
| fn call(&mut self, req: lambda_http::Request) -> Self::Future { | ||
| let (parts, body) = req.into_parts(); | ||
| let body = match body { | ||
| lambda_http::Body::Empty => axum::body::Body::default(), | ||
| lambda_http::Body::Text(t) => t.into(), | ||
| lambda_http::Body::Binary(v) => v.into(), | ||
| }; | ||
|
|
||
| let request = axum::http::Request::from_parts(parts, body); | ||
|
|
||
| let fut = self.inner.call(request); | ||
| let fut = async move { | ||
| let resp = fut.await?; | ||
| let (parts, body) = resp.into_response().into_parts(); | ||
| let bytes = body.collect().await?.to_bytes(); | ||
| let bytes: &[u8] = &bytes; | ||
| let resp: hyper::Response<lambda_http::Body> = match std::str::from_utf8(bytes) { | ||
| Ok(s) => hyper::Response::from_parts(parts, s.into()), | ||
| Err(_) => hyper::Response::from_parts(parts, bytes.into()), | ||
| }; | ||
| Ok(resp) | ||
| }; | ||
|
|
||
| Box::pin(fut) | ||
| } | ||
| } |
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,154 @@ | ||
| use aws_sdk_dynamodb::types::AttributeValue; | ||
| use axum::routing::{get, post}; | ||
| use axum::Router; | ||
| use std::collections::HashMap; | ||
| use std::sync::{Arc, Mutex}; | ||
| use std::time::Duration; | ||
| use tower_http::limit::RequestBodyLimitLayer; | ||
| use ulid::Ulid; | ||
|
|
||
| mod ask; | ||
| mod event; | ||
| mod list; | ||
| mod new; | ||
| mod questions; | ||
| mod toggle; | ||
| mod utils; | ||
| mod vote; | ||
|
|
||
| pub use ask::Question; | ||
| pub use utils::to_dynamo_timestamp; | ||
| pub use vote::UpDown; | ||
|
|
||
| #[cfg(debug_assertions)] | ||
| const SEED: &str = include_str!("test.json"); | ||
|
|
||
| const QUESTIONS_EXPIRE_AFTER_DAYS: u64 = 30; | ||
| const QUESTIONS_TTL: Duration = Duration::from_secs(QUESTIONS_EXPIRE_AFTER_DAYS * 24 * 60 * 60); | ||
|
|
||
| const EVENTS_EXPIRE_AFTER_DAYS: u64 = 60; | ||
| const EVENTS_TTL: Duration = Duration::from_secs(EVENTS_EXPIRE_AFTER_DAYS * 24 * 60 * 60); | ||
|
|
||
| #[derive(Clone, Debug, Default)] | ||
| pub struct Local { | ||
| pub events: HashMap<Ulid, String>, | ||
| pub questions: HashMap<Ulid, HashMap<&'static str, AttributeValue>>, | ||
| pub questions_by_eid: HashMap<Ulid, Vec<Ulid>>, | ||
| } | ||
|
|
||
| #[derive(Clone, Debug)] | ||
| pub enum Backend { | ||
| Dynamo(aws_sdk_dynamodb::Client), | ||
| Local(Arc<Mutex<Local>>), | ||
| } | ||
|
|
||
| impl Backend { | ||
| #[allow(unused)] | ||
| async fn local() -> Self { | ||
| Backend::Local(Arc::new(Mutex::new(Local::default()))) | ||
| } | ||
|
|
||
| /// Instantiate a DynamoDB backend. | ||
| /// | ||
| /// If `USE_DYNAMODB` is set to "local", the `AWS_ENDPOINT_URL` will be taken | ||
| /// from the environment with the "http://localhost:8000" fallback , the `AWS_DEFAULT_REGION` | ||
| /// will be pulled from the environment as well and will default to "us-east-1", | ||
| /// as for the credentials - the [test credentials](https://docs.rs/aws-config/latest/aws_config/struct.ConfigLoader.html#method.test_credentials) | ||
| /// will be used to sign requests. | ||
| /// | ||
| /// This spares setting those environment variables (including `AWS_ACCESS_KEY_ID` | ||
| /// and `AWS_SECRET_ACCESS_KEY`) via the command line or configuration files, | ||
| /// and allows to run the application against a local dynamodb instance with just: | ||
| /// ```sh | ||
| /// USE_DYNAMODB=local cargo run | ||
| /// ``` | ||
| /// While the entire test suite can be run with: | ||
| /// ```sh | ||
| /// USE_DYNAMODB=local cargo t -- --include-ignored | ||
| /// ``` | ||
| /// | ||
| /// This also allows us to use the local instance of DynamoDB which is running | ||
| /// in a container on the same network, in which case the database will be accessible | ||
| /// under `http://<dynamodb_container_name>:<port>`. This facilitates the setup of | ||
| /// local API Gateway with SAM, since the `sam local start-api` command will launch our | ||
| /// back-end app in a docker container. | ||
| /// | ||
| /// If more customization is needed (say, you want to set some specific credentials | ||
| /// rather than rely on those test creds generated by the `aws_config` crate), | ||
| /// set `USE_DYNAMODB` to e.g. "custom", and set the environment variables to whatever | ||
| /// values you need or let them be picked up from your `~/.aws` files | ||
| /// (see [`aws_config::load_from_env`](https://docs.rs/aws-config/latest/aws_config/fn.load_from_env.html)) | ||
| pub async fn dynamo() -> Self { | ||
| let config = if std::env::var("USE_DYNAMODB") | ||
| .ok() | ||
| .is_some_and(|v| v == "local") | ||
| { | ||
| aws_config::from_env() | ||
| .endpoint_url( | ||
| std::env::var("AWS_ENDPOINT_URL") | ||
| .ok() | ||
| .unwrap_or("http://localhost:8000".into()), | ||
| ) | ||
| .region(aws_config::Region::new( | ||
| std::env::var("AWS_DEFAULT_REGION") | ||
| .ok() | ||
| .unwrap_or("us-east-1".into()), | ||
| )) | ||
| .test_credentials() | ||
| .load() | ||
| .await | ||
| } else { | ||
| aws_config::load_from_env().await | ||
| }; | ||
| Backend::Dynamo(aws_sdk_dynamodb::Client::new(&config)) | ||
| } | ||
| } | ||
|
|
||
| pub async fn new() -> Router { | ||
| #[cfg(not(debug_assertions))] | ||
| let backend = Backend::dynamo().await; | ||
|
|
||
| #[cfg(debug_assertions)] | ||
| let backend = { | ||
| use rand::prelude::IndexedRandom; | ||
|
|
||
| let mut backend = if std::env::var_os("USE_DYNAMODB").is_some() { | ||
| Backend::dynamo().await | ||
| } else { | ||
| Backend::local().await | ||
| }; | ||
|
|
||
| // to aid in development, seed the backend with a test event and related | ||
| // questions, and auto-generate user votes over time | ||
| let qids = crate::utils::seed(&mut backend).await; | ||
| let cheat = backend.clone(); | ||
| tokio::spawn(async move { | ||
| let mut interval = tokio::time::interval(Duration::from_secs(1)); | ||
| interval.tick().await; | ||
| loop { | ||
| interval.tick().await; | ||
| let qid = qids | ||
| .choose(&mut rand::rng()) | ||
| .expect("there _are_ some questions for our test event"); | ||
| let _ = cheat.vote(qid, vote::UpDown::Up).await; | ||
| } | ||
| }); | ||
|
|
||
| backend | ||
| }; | ||
|
|
||
| Router::new() | ||
| .route("/api/event", post(new::new)) | ||
| .route("/api/event/{eid}", post(ask::ask)) | ||
| .route("/api/event/{eid}", get(event::event)) | ||
| .route("/api/event/{eid}/questions", get(list::list)) | ||
| .route("/api/event/{eid}/questions/{secret}", get(list::list_all)) | ||
| .route( | ||
| "/api/event/{eid}/questions/{secret}/{qid}/toggle/{property}", | ||
| post(toggle::toggle), | ||
| ) | ||
| .route("/api/vote/{qid}/{updown}", post(vote::vote)) | ||
| .route("/api/questions/{qids}", get(questions::questions)) | ||
| .layer(RequestBodyLimitLayer::new(1024)) | ||
| .with_state(backend) | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.