Skip to content
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

Switch to uv #173

Merged
merged 2 commits into from
Dec 27, 2024
Merged
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
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ serde_with = "3.11.0"
thiserror = "2.0.3"
time = "0.3.37"
tokio = "1.41.0"
tower-http = "0.6.2"
tracing = "0.1"
tracing-subscriber = { version = "0.3", default-features = false }
url = "2.3.1"
Expand All @@ -68,3 +69,4 @@ tokio = { workspace = true }
bnacore = { workspace = true }
csv = { workspace = true }
itertools = { workspace = true }
time = { workspace = true, features = ["formatting"] }
12 changes: 10 additions & 2 deletions effortless/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,15 @@ impl Default for PaginationParameters {

impl PaginationParameters {
pub fn page_size(&self) -> u64 {
self.page_size.unwrap_or(DEFAULT_PAGE_SIZE)
// self.page_size.unwrap_or(DEFAULT_PAGE_SIZE)
match self.page_size {
Some(value) => match value {
0 => 1,
1..=MAX_PAGE_SIZE => value,
_ => MAX_PAGE_SIZE,
},
None => DEFAULT_PAGE_SIZE,
}
}
}

Expand All @@ -237,7 +245,7 @@ pub fn extract_pagination_parameters(
match page_size.parse::<u64>() {
Ok(page_size) => {
pagination.page_size = match page_size {
0..=MAX_PAGE_SIZE => Some(page_size),
1..=MAX_PAGE_SIZE => Some(page_size),
_ => Some(MAX_PAGE_SIZE),
}
}
Expand Down
7 changes: 4 additions & 3 deletions examples/seeder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use entity::{
use sea_orm::{prelude::Uuid, ActiveValue, Database, EntityTrait};
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use time::format_description::well_known;

const US_STATE_COUNT: usize = 51; // w/ Puerto Rico
const CHUNK_SIZE: usize = 1000;
Expand Down Expand Up @@ -82,11 +83,11 @@ async fn main() -> Result<(), Report> {
let version = Calver::try_from_ubuntu(&calver).unwrap();

// Get the records creation date.
let created_at = scorecard
let created_at_str = scorecard
.creation_date
.to_string()
.parse::<DateTime<FixedOffset>>()
.format(&well_known::Iso8601::DEFAULT)
.unwrap();
let created_at = created_at_str.parse::<DateTime<FixedOffset>>().unwrap();

// Get the City UUID.
let city_uuid = Uuid::parse_str(&scorecard.bna_id).unwrap();
Expand Down
8 changes: 8 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,11 @@ generate-client:
--interface builder \
--license-name MIT \
-v 1.0.0

# Start the Axum server locally in watch mode.
debug-axum:
BNA_API_LOG_LEVEL=debug \
BNA_API_STANDALONE=1 \
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres \
cargo watch -x \
'run -p lambdas --bin axumed'
1 change: 1 addition & 0 deletions lambdas/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ serde_json = { workspace = true }
serde_plain = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["macros"] }
tower-http = { workspace = true, features = ["trace"] }
tracing = { workspace = true, features = ["log"] }
tracing-subscriber = { workspace = true, features = ["fmt"] }
url = { workspace = true }
Expand Down
5 changes: 5 additions & 0 deletions lambdas/requests.rest
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
# Query the first page of the bnas.
GET {{host}}/ratings


###
# Query the first page of the bnas.
GET {{host}}/ratings?page_size=1257596201

###
# Query a specific bna run.
GET {{host}}/ratings/{{rating_id}}
Expand Down
13 changes: 11 additions & 2 deletions lambdas/src/bin/ratings/patch-ratings-analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ use dotenv::dotenv;
use effortless::{
api::{missing_parameter, parse_path_parameter, parse_request_body},
error::APIErrors,
fragment::BnaRequestExt,
};
use entity::wrappers::bna_pipeline::BNAPipelinePatch;
use lambda_http::{run, service_fn, Body, Error, IntoResponse, Request, Response};
use lambdas::core::resource::ratings::adaptor::patch_ratings_analysis_adaptor;
use lambdas::{core::resource::ratings::adaptor::patch_ratings_analysis_adaptor, Context};
use sea_orm::prelude::Uuid;
use tracing::info;

Expand All @@ -27,8 +28,16 @@ async fn function_handler(event: Request) -> Result<Response<Body>, Error> {
},
Err(e) => return Ok(e.into()),
};
let ctx = Context::new(
event.apigw_request_id(),
event
.uri()
.path_and_query()
.expect("to have a path and optional query parameters")
.to_string(),
);

match patch_ratings_analysis_adaptor(wrapper, analysis_id).await {
match patch_ratings_analysis_adaptor(wrapper, analysis_id, ctx).await {
Ok(v) => Ok(v.into_response().await),
Err(e) => Ok(APIErrors::from(e).into()),
}
Expand Down
20 changes: 18 additions & 2 deletions lambdas/src/core/resource/ratings/adaptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use entity::{
bna_pipeline::{BNAPipelinePatch, BNAPipelinePost},
},
};
use sea_orm::{ActiveModelTrait, ActiveValue, IntoActiveModel};
use sea_orm::{ActiveModelTrait, ActiveValue, DbErr, IntoActiveModel};
use serde_json::{json, Value};
use tracing::info;
use uuid::Uuid;
Expand Down Expand Up @@ -164,6 +164,7 @@ pub async fn post_ratings_analysis_adaptor(
pub async fn patch_ratings_analysis_adaptor(
bna_pipeline: BNAPipelinePatch,
analysis_id: Uuid,
ctx: Context,
) -> Result<Value, ExecutionError> {
// Set the database connection.
let db = database_connect(Some("DATABASE_URL_SECRET_ID")).await?;
Expand All @@ -173,7 +174,22 @@ pub async fn patch_ratings_analysis_adaptor(
active_model.state_machine_id = ActiveValue::Unchanged(analysis_id);

// Update the entry.
let model = active_model.update(&db).await?;
info!("Tartiflette!");
let model = match active_model.update(&db).await {
Ok(m) => m,
Err(db_err) => {
dbg!(&db_err);
match db_err {
DbErr::RecordNotUpdated => {
match get_ratings_analysis_adaptor(analysis_id, ctx).await {
Ok(_) => return Err(ExecutionError::DatabaseError(db_err)),
Err(exec_err) => return Err(exec_err),
}
}
_ => return Err(ExecutionError::DatabaseError(db_err)),
}
}
};
Ok(json!(model))
}

Expand Down
21 changes: 14 additions & 7 deletions lambdas/src/core/resource/ratings/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,20 @@ async fn patch_ratings_analysis(
Path(analysis_id): Path<Uuid>,
Json(bna_pipeline): Json<BNAPipelinePatch>,
) -> Result<Json<Value>, ExecutionError> {
patch_ratings_analysis_adaptor(bna_pipeline, analysis_id)
.await
.map_err(|e| {
debug!("{e}");
e
})
.map(Json)
patch_ratings_analysis_adaptor(
bna_pipeline,
analysis_id,
Context {
request_id: None,
source: format!("/ratings/analyses/{analysis_id}"),
},
)
.await
.map_err(|e| {
debug!("{e}");
e
})
.map(Json)
}

async fn post_ratings(
Expand Down
4 changes: 3 additions & 1 deletion lambdas/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use axum::Router;
use lambda_http::{run, tracing, Error};
use lambdas::core::resource::{cities, price, ratings};
use std::env::{self, set_var};
use tower_http::trace::TraceLayer;

#[tokio::main]
async fn main() -> Result<(), Error> {
Expand Down Expand Up @@ -37,7 +38,8 @@ async fn main() -> Result<(), Error> {
let app = Router::new()
.merge(cities::endpoint::routes())
.merge(price::endpoint::routes())
.merge(ratings::endpoint::routes());
.merge(ratings::endpoint::routes())
.layer(TraceLayer::new_for_http());

// Lookup for the standalone flag.
let standalone = env::var("BNA_API_STANDALONE")
Expand Down
1 change: 1 addition & 0 deletions lambdas/tests/.python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.13
Empty file added lambdas/tests/README.md
Empty file.
24 changes: 14 additions & 10 deletions lambdas/tests/justfile
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
set positional-arguments

# Define variables.
venv := ".venv"
venv_bin := venv / "bin"
activate := venv_bin / "activate"
top_dir := `git rev-parse --show-toplevel`

# Setup the project.
setup:
uv venv \
&& uv pip install --upgrade pip setuptools \
&& uv pip install -r requirements.txt
uv venv
uv pip install --upgrade pip setuptools
uv pip install -r requirements.txt
uv sync

# Export the OpenAPI specification.
openapi-export:
Expand All @@ -35,17 +33,23 @@ test-smoke-readonly *env:

# Run the schemathesis tests locally again the openapi schema.
test-localhost-schemathesis:
RUST_BACKTRACE=1 \
uv run st run \
{{top_dir}}/openapi.yaml \
--base-url http://localhost:3000/ \
--cassette-path cassette.yaml \
-vvv \
-x \
--show-trace \
--generation-allow-x00 false \
--exclude-method 'POST' \
--exclude-method 'PATCH \
--base-url http://localhost:3000/
--exclude-method 'PATCH' \
{{top_dir}}/openapi.yaml

# Run the schemathesis tests again the openapi schema.
test-staging-schemathesis:
uv run st run \
{{top_dir}}/openapi.yaml \
--exclude-method 'POST' \
--exclude-method 'PATCH \
--exclude-method 'PATCH' \
--base-url https://api.peopleforbikes.xyz/

7 changes: 7 additions & 0 deletions lambdas/tests/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[project]
name = "test"
version = "0.1.0"
description = "Integration tests for the BNA API"
readme = "README.md"
requires-python = ">=3.13"
dependencies = ["schemathesis==3.38.10"]
1 change: 0 additions & 1 deletion lambdas/tests/requirements.txt

This file was deleted.

Loading
Loading