Skip to content
This repository has been archived by the owner on Sep 30, 2024. It is now read-only.

Commit

Permalink
Some fixes & tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
jming422 committed Jun 18, 2022
1 parent 4fad156 commit d669b9d
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 32 deletions.
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ tokio = { version = "1", features = ["full"] }
tokio-stream = "0.1"
tokio-tar = "0.3"
tokio-util = "0.7"
tower-http = { version = "0.3", features = ["fs"] }
tower-http = { version = "0.3", features = ["fs", "trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

[dev-dependencies]
hyper = "0.14"
Expand Down
4 changes: 2 additions & 2 deletions js/src/components/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@ const App: FunctionalComponent = () => {
useEffect(() => {
if (outingId) {
window.sessionStorage.setItem('outingId', outingId);
route(`/outings/${outingId}`);
route(`/details`);
return;
}

const maybeOutingId = window.sessionStorage.getItem('outingId');
if (maybeOutingId && /^[A-Z0-9]+$/.test(maybeOutingId)) {
setOutingId(maybeOutingId);
route(`/outings/${outingId}`);
route(`/details`);
} else {
route(`/`);
}
Expand Down
8 changes: 3 additions & 5 deletions js/src/components/outingHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
*/
import { route } from 'preact-router';
import { type FunctionalComponent, h } from 'preact';
import { useContext } from 'preact/hooks';

import { Button, Callout, Title } from './common';
import { GlobalContext } from '../context';
import { formatUsd } from '../utils';
import { type Outing, type Balance } from '../models/outing';
import { useContext } from 'preact/hooks';
import { GlobalContext } from 'src/context';

export interface OutingHeaderProps {
outing: Outing;
Expand Down Expand Up @@ -43,9 +43,7 @@ const OutingHeader: FunctionalComponent<OutingHeaderProps> = ({
</div>
<Button onClick={exitOuting}>Exit to Home</Button>
{showButton && (
<Button onClick={() => route(`/outings/${outing.outingId}/finish`)}>
Finish Outing
</Button>
<Button onClick={() => route(`/finish`)}>Finish Outing</Button>
)}
</h3>
<Callout>Join code: {outing.outingId}</Callout>
Expand Down
16 changes: 8 additions & 8 deletions js/src/routes/outings/details.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,22 @@
* For information about warranty and licensing, see the disclaimer in
* src/lib.rs as well as the LICENSE file.
*/
import { DateTime } from 'luxon';
import { type FunctionalComponent, Fragment, h } from 'preact';
import { useContext, useState } from 'preact/hooks';
import { DateTime } from 'luxon';

import OutingHeader from '../../components/outingHeader';
import { Callout, Container, Label, Button } from '../../components/common';
import { GlobalContext } from '../../context';
import { formatUsd } from '../../utils';
import { useCreateExpense, type Expense } from '../../models/expense';
import {
type Balance,
type OutingDetails,
useOuting,
useOutingBalance,
useOutingExpenses,
type Balance,
type OutingDetails,
} from '../../models/outing';
import { useCreateExpense, type Expense } from '../../models/expense';
import { formatUsd } from '../../utils';
import OutingHeader from '../../components/outingHeader';
import { Callout, Container, Label, Button } from '../../components/common';
import { GlobalContext } from 'src/context';

interface CreateExpenseProps {
refresh: () => void;
Expand Down
19 changes: 12 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ use sync_wrapper::SyncWrapper;
use tokio_stream::StreamExt;
use tokio_tar::Archive;
use tokio_util::io::StreamReader;
use tower_http::services::{ServeDir, ServeFile};
use tower_http::{
services::{ServeDir, ServeFile},
trace::TraceLayer,
};
use tracing::{error, info};

pub mod models;
use models::*;
Expand Down Expand Up @@ -243,7 +247,7 @@ async fn finish_outing(

if people_debts.is_empty() {
if most_indebted.diff_from_avg > Decimal::new(1, 2) {
eprintln!(
error!(
"Somebody was left over with an oustanding balance greater than 1 cent, telling them to... pay themselves lol: {:?}",
most_indebted
);
Expand Down Expand Up @@ -273,13 +277,13 @@ async fn finish_outing(
}

pub async fn migrate(pool: &PgPool) -> Result<(), sqlx::Error> {
println!("Updating database schema");
info!("Updating database schema");
pool.execute(include_str!("../schema.sql")).await?;
Ok(())
}

pub async fn app(pool: PgPool, js_build_dir: &str) -> Result<Router, shuttle_service::Error> {
println!("Building router");
info!("Building router");
let outing_routes = Router::new()
.route("/", get(list_outings).post(create_outing))
.route("/:id", get(retrieve_outing))
Expand All @@ -306,17 +310,18 @@ pub async fn app(pool: PgPool, js_build_dir: &str) -> Result<Router, shuttle_ser
(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong...")
}),
)
.layer(Extension(pool));
.layer(Extension(pool))
.layer(TraceLayer::new_for_http());

Ok(router)
}

pub async fn unpack_frontend(pool: &PgPool) -> Result<(), shuttle_service::Error> {
println!("Downloading frontend bundle from S3");
info!("Downloading frontend bundle from S3");
let bucket = pool.get_secret("DEPLOY_BUCKET").await?;
let s3_result = s3::download_object(pool, bucket, "birdie-js.tar.gz").await?;

println!("Unpacking frontend bundle");
info!("Unpacking frontend bundle");
let gz = StreamReader::new(
s3_result
.body
Expand Down
14 changes: 12 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,22 @@ use std::net::SocketAddr;

use axum::Server;
use sqlx::postgres::PgPoolOptions;
use tracing::info;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

use birdie::{app, migrate};

#[tokio::main]
async fn main() {
println!("to Connecting Postgres");
tracing_subscriber::registry()
.with(tracing_subscriber::EnvFilter::new(
std::env::var("RUST_LOG")
.unwrap_or_else(|_| "birdie=debug,tower_http=debug".into()),
))
.with(tracing_subscriber::fmt::layer())
.init();

info!("Connecting to Postgres");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect("postgres://localhost/birdie")
Expand All @@ -31,7 +41,7 @@ async fn main() {
let router = app(pool, "./js/build").await.unwrap();

let addr = SocketAddr::from(([127, 0, 0, 1], 5000));
println!("Listening on {}", addr);
info!("Listening on {}", addr);
Server::bind(&addr)
.serve(router.into_make_service())
.await
Expand Down
9 changes: 2 additions & 7 deletions tests/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,12 @@ use tower::ServiceExt; // for `app.oneshot()`

async fn setup_test_db(schema_suffix: &str) -> PgPool {
// Modeled after example in https://docs.rs/sqlx/latest/sqlx/pool/struct.PoolOptions.html#method.after_connect
println!("Connecting");
// This makes all queries in tests hit their own `testing` schema
let why_rust_whyyy = format!("SET search_path TO testing_{};", schema_suffix);
let pool = PgPoolOptions::new()
.after_connect(move |conn| {
let why_rust_whyyy = why_rust_whyyy.clone();
Box::pin(async move {
println!("Setting search path");
conn.execute(why_rust_whyyy.as_str()).await?;
Ok(())
})
Expand All @@ -38,20 +36,17 @@ async fn setup_test_db(schema_suffix: &str) -> PgPool {
.await
.unwrap();

println!("Dropping testing schema");
// And dropping/recreating clears the schema before each test run
pool.execute(format!("DROP SCHEMA IF EXISTS testing_{} CASCADE;", schema_suffix).as_str())
.await
.unwrap();
println!("Creating testing schema");

pool.execute(format!("CREATE SCHEMA testing_{};", schema_suffix).as_str())
.await
.unwrap();

println!("Migrating");
birdie::migrate(&pool).await.unwrap();

println!("Done");
pool
}

Expand Down Expand Up @@ -160,7 +155,7 @@ async fn outings() {

let dec_outing_id = birdie::models::HARSH
.decode(&outing_id)
.expect(format!("outing_id wasn't a valid hashid, it was {}", &outing_id).as_str())
.unwrap_or_else(|_| panic!("outing_id wasn't a valid hashid, it was {}", &outing_id))
.pop()
.unwrap();

Expand Down

0 comments on commit d669b9d

Please sign in to comment.