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

[DO NOT MERGE] rust: Use SSE for notification endpoints #755

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
13 changes: 13 additions & 0 deletions webapp/rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions webapp/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ anyhow = { version = "1", features = ["backtrace"] }
axum = "0.7"
axum-extra = { version = "0.9", features = ["cookie"] }
chrono = "0.4"
futures-util = "0.3"
hex = "0.4"
listenfd = "1"
num-traits = "0.2"
Expand Down
168 changes: 88 additions & 80 deletions webapp/rust/src/app_handlers.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum_extra::extract::CookieJar;
use futures_util::Stream;
use ulid::Ulid;

use crate::models::{Chair, ChairLocation, Coupon, Owner, PaymentToken, Ride, RideStatus, User};
Expand Down Expand Up @@ -540,12 +541,6 @@ async fn app_post_ride_evaluation(
}))
}

#[derive(Debug, serde::Serialize)]
struct AppGetNotificationResponse {
data: Option<AppGetNotificationResponseData>,
retry_after_ms: Option<i32>,
}

#[derive(Debug, serde::Serialize)]
struct AppGetNotificationResponseData {
ride_id: String,
Expand Down Expand Up @@ -576,91 +571,104 @@ struct AppGetNotificationResponseChairStats {
async fn app_get_notification(
State(AppState { pool, .. }): State<AppState>,
axum::Extension(user): axum::Extension<User>,
) -> Result<axum::Json<AppGetNotificationResponse>, Error> {
let mut tx = pool.begin().await?;

let Some(ride): Option<Ride> =
sqlx::query_as("SELECT * FROM rides WHERE user_id = ? ORDER BY created_at DESC LIMIT 1")
.bind(&user.id)
.fetch_optional(&mut *tx)
.await?
else {
return Ok(axum::Json(AppGetNotificationResponse {
data: None,
retry_after_ms: Some(30),
}));
};
) -> axum::response::Sse<impl Stream<Item = Result<axum::response::sse::Event, Error>>> {
async fn f(
pool: &sqlx::MySqlPool,
user_id: &str,
last_ride_id: &mut String,
last_ride_status: &mut String,
) -> Result<Option<AppGetNotificationResponseData>, Error> {
let mut tx = pool.begin().await?;

let yet_sent_ride_status: Option<RideStatus> = sqlx::query_as("SELECT * FROM ride_statuses WHERE ride_id = ? AND app_sent_at IS NULL ORDER BY created_at ASC LIMIT 1")
.bind(&ride.id)
.fetch_optional(&mut *tx)
.await?;
let (ride_status_id, status) = if let Some(yet_sent_ride_status) = yet_sent_ride_status {
(Some(yet_sent_ride_status.id), yet_sent_ride_status.status)
} else {
(
None,
crate::get_latest_ride_status(&mut *tx, &ride.id).await?,
let Some(ride): Option<Ride> = sqlx::query_as(
"SELECT * FROM rides WHERE user_id = ? ORDER BY created_at DESC LIMIT 1",
)
};
.bind(user_id)
.fetch_optional(pool)
.await?
else {
return Ok(None);
};

let fare = calculate_discounted_fare(
&mut tx,
&user.id,
Some(&ride),
ride.pickup_latitude,
ride.pickup_longitude,
ride.destination_latitude,
ride.destination_longitude,
)
.await?;
let status = crate::get_latest_ride_status(&mut *tx, &ride.id).await?;
if ride.id == *last_ride_id && status == *last_ride_status {
return Ok(None);
}

let mut data = AppGetNotificationResponseData {
ride_id: ride.id,
pickup_coordinate: Coordinate {
latitude: ride.pickup_latitude,
longitude: ride.pickup_longitude,
},
destination_coordinate: Coordinate {
latitude: ride.destination_latitude,
longitude: ride.destination_longitude,
},
fare,
status,
chair: None,
created_at: ride.created_at.timestamp_millis(),
updated_at: ride.updated_at.timestamp_millis(),
};
let fare = calculate_discounted_fare(
&mut tx,
user_id,
Some(&ride),
ride.pickup_latitude,
ride.pickup_longitude,
ride.destination_latitude,
ride.destination_longitude,
)
.await?;

if let Some(chair_id) = ride.chair_id {
let chair: Chair = sqlx::query_as("SELECT * FROM chairs WHERE id = ?")
.bind(chair_id)
.fetch_one(&mut *tx)
.await?;
let mut data = AppGetNotificationResponseData {
ride_id: ride.id.clone(),
pickup_coordinate: Coordinate {
latitude: ride.pickup_latitude,
longitude: ride.pickup_longitude,
},
destination_coordinate: Coordinate {
latitude: ride.destination_latitude,
longitude: ride.destination_longitude,
},
fare,
status: status.clone(),
chair: None,
created_at: ride.created_at.timestamp_millis(),
updated_at: ride.updated_at.timestamp_millis(),
};

let stats = get_chair_stats(&mut tx, &chair.id).await?;
if let Some(chair_id) = ride.chair_id {
let chair: Chair = sqlx::query_as("SELECT * FROM chairs WHERE id = ?")
.bind(chair_id)
.fetch_one(&mut *tx)
.await?;

data.chair = Some(AppGetNotificationResponseChair {
id: chair.id,
name: chair.name,
model: chair.model,
stats,
});
}
let stats = get_chair_stats(&mut tx, &chair.id).await?;

if let Some(ride_status_id) = ride_status_id {
sqlx::query("UPDATE ride_statuses SET app_sent_at = CURRENT_TIMESTAMP(6) WHERE id = ?")
.bind(ride_status_id)
.execute(&mut *tx)
.await?;
data.chair = Some(AppGetNotificationResponseChair {
id: chair.id,
name: chair.name,
model: chair.model,
stats,
});
}

*last_ride_id = ride.id;
*last_ride_status = status;
Ok(Some(data))
}

tx.commit().await?;
let stream = futures_util::stream::try_unfold(
("".to_owned(), "".to_owned()),
move |(mut last_ride_id, mut last_ride_status)| {
let pool = pool.clone();
let user_id = user.id.clone();
async move {
loop {
if let Some(data) =
f(&pool, &user_id, &mut last_ride_id, &mut last_ride_status).await?
{
return Ok(Some((
axum::response::sse::Event::default()
.json_data(data)
.unwrap(),
(last_ride_id, last_ride_status),
)));
} else {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
},
);

Ok(axum::Json(AppGetNotificationResponse {
data: Some(data),
retry_after_ms: Some(30),
}))
axum::response::Sse::new(stream)
}

async fn get_chair_stats(
Expand Down
113 changes: 60 additions & 53 deletions webapp/rust/src/chair_handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum_extra::extract::cookie::Cookie;
use axum_extra::extract::CookieJar;
use futures_util::Stream;
use ulid::Ulid;

use crate::models::{Chair, ChairLocation, Owner, Ride, RideStatus, User};
use crate::models::{Chair, ChairLocation, Owner, Ride, User};
use crate::{AppState, Coordinate, Error};

pub fn chair_routes(app_state: AppState) -> axum::Router<AppState> {
Expand Down Expand Up @@ -184,12 +185,6 @@ struct SimpleUser {
name: String,
}

#[derive(Debug, serde::Serialize)]
struct ChairGetNotificationResponse {
data: Option<ChairGetNotificationResponseData>,
retry_after_ms: Option<i32>,
}

#[derive(Debug, serde::Serialize)]
struct ChairGetNotificationResponseData {
ride_id: String,
Expand All @@ -202,53 +197,37 @@ struct ChairGetNotificationResponseData {
async fn chair_get_notification(
State(AppState { pool, .. }): State<AppState>,
axum::Extension(chair): axum::Extension<Chair>,
) -> Result<axum::Json<ChairGetNotificationResponse>, Error> {
let mut tx = pool.begin().await?;

let Some(ride): Option<Ride> =
sqlx::query_as("SELECT * FROM rides WHERE chair_id = ? ORDER BY updated_at DESC LIMIT 1")
.bind(&chair.id)
.fetch_optional(&mut *tx)
.await?
else {
return Ok(axum::Json(ChairGetNotificationResponse {
data: None,
retry_after_ms: Some(30),
}));
};

let yet_sent_ride_status: Option<RideStatus> =
sqlx::query_as("SELECT * FROM ride_statuses WHERE ride_id = ? AND chair_sent_at IS NULL ORDER BY created_at ASC LIMIT 1")
.bind(&ride.id)
.fetch_optional(&mut *tx)
.await?;
let (yet_sent_ride_status_id, status) = if let Some(yet_sent_ride_status) = yet_sent_ride_status
{
(Some(yet_sent_ride_status.id), yet_sent_ride_status.status)
} else {
(
None,
crate::get_latest_ride_status(&mut *tx, &ride.id).await?,
) -> axum::response::Sse<impl Stream<Item = Result<axum::response::sse::Event, Error>>> {
async fn f(
pool: &sqlx::MySqlPool,
chair_id: &str,
last_ride_id: &mut String,
last_ride_status: &mut String,
) -> Result<Option<ChairGetNotificationResponseData>, Error> {
let mut tx = pool.begin().await?;

let Some(ride): Option<Ride> = sqlx::query_as(
"SELECT * FROM rides WHERE chair_id = ? ORDER BY updated_at DESC LIMIT 1",
)
};
.bind(chair_id)
.fetch_optional(&mut *tx)
.await?
else {
return Ok(None);
};

let user: User = sqlx::query_as("SELECT * FROM users WHERE id = ? FOR SHARE")
.bind(ride.user_id)
.fetch_one(&mut *tx)
.await?;
let status = crate::get_latest_ride_status(&mut *tx, &ride.id).await?;
if ride.id == *last_ride_id && status == *last_ride_status {
return Ok(None);
}

if let Some(yet_sent_ride_status_id) = yet_sent_ride_status_id {
sqlx::query("UPDATE ride_statuses SET chair_sent_at = CURRENT_TIMESTAMP(6) WHERE id = ?")
.bind(yet_sent_ride_status_id)
.execute(&mut *tx)
let user: User = sqlx::query_as("SELECT * FROM users WHERE id = ? FOR SHARE")
.bind(ride.user_id)
.fetch_one(&mut *tx)
.await?;
}

tx.commit().await?;

Ok(axum::Json(ChairGetNotificationResponse {
data: Some(ChairGetNotificationResponseData {
ride_id: ride.id,
let data = ChairGetNotificationResponseData {
ride_id: ride.id.clone(),
user: SimpleUser {
id: user.id,
name: format!("{} {}", user.firstname, user.lastname),
Expand All @@ -261,10 +240,38 @@ async fn chair_get_notification(
latitude: ride.destination_latitude,
longitude: ride.destination_longitude,
},
status,
}),
retry_after_ms: Some(30),
}))
status: status.clone(),
};
*last_ride_id = ride.id;
*last_ride_status = status;
Ok(Some(data))
}

let stream = futures_util::stream::try_unfold(
("".to_owned(), "".to_owned()),
move |(mut last_ride_id, mut last_ride_status)| {
let pool = pool.clone();
let chair_id = chair.id.clone();
async move {
loop {
if let Some(data) =
f(&pool, &chair_id, &mut last_ride_id, &mut last_ride_status).await?
{
return Ok(Some((
axum::response::sse::Event::default()
.json_data(data)
.unwrap(),
(last_ride_id, last_ride_status),
)));
} else {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
}
},
);

axum::response::Sse::new(stream)
}

#[derive(Debug, serde::Deserialize)]
Expand Down
Loading
Loading