Skip to content

Commit

Permalink
Setup for deployment (#298)
Browse files Browse the repository at this point in the history
  • Loading branch information
terror authored Jun 21, 2023
1 parent 9f5835c commit 2a53433
Show file tree
Hide file tree
Showing 36 changed files with 223 additions and 121 deletions.
1 change: 1 addition & 0 deletions .env.example → .env.dev.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
MS_CLIENT_ID=
MS_CLIENT_SECRET=
MS_REDIRECT_URI=
RUST_LOG=
5 changes: 5 additions & 0 deletions .env.prod.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
MONGODB_URL=
MS_CLIENT_ID=
MS_CLIENT_SECRET=
MS_REDIRECT_URI=
RUST_LOG=
42 changes: 34 additions & 8 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ reqwest = { version = "0.11.17", features = ["blocking", "json"] }
serde = { version = "1.0.162", features = ["derive"] }
serde_json = "1.0.96"
tokio = { version = "1.28.0", features = ["rt-multi-thread", "macros"] }
tower-http = { version = "0.4.0", features = ["cors"] }
tower-http = { version = "0.4.0", features = ["cors", "fs"] }
url = "2.3.1"

[dev-dependencies]
Expand Down
23 changes: 23 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
FROM node:19-alpine AS client

WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build -- --mode production

FROM rust:1.68-buster as server

WORKDIR /usr/src/app
COPY . .
RUN cargo build --release

FROM debian:buster-slim

RUN apt-get update && apt-get install -y libssl1.1

COPY --from=client /app/client/dist assets
COPY --from=server /usr/src/app/seed seed
COPY --from=server /usr/src/app/target/release/server /usr/local/bin

CMD server --source seed serve --asset-dir assets --initialize --db-name mcgill-courses
File renamed without changes.
File renamed without changes
6 changes: 4 additions & 2 deletions client/src/components/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { Bars3Icon } from '@heroicons/react/24/outline';
import { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';

import birdImageUrl from '../assets/bird.png';
import { useAuth } from '../hooks/useAuth';
import { fetchClient } from '../lib/fetchClient';
import { SearchResults } from '../model/SearchResults';
import { CourseSearchBar } from './CourseSearchBar';
import { ProfileDropdown } from './ProfileDropdown';
import { SideNav } from './SideNav';
import { DarkModeToggle } from './DarkModeToggle';
import { getUrl } from '../lib/utils';

export const Navbar = () => {
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
Expand Down Expand Up @@ -48,7 +50,7 @@ export const Navbar = () => {
>
<div className='z-40 my-auto mr-auto flex lg:flex-1'>
<Link to='/' className='-m-1.5 p-1.5'>
<img className='h-12 w-auto' src='/bird.png' alt='bird' />
<img className='h-12 w-auto' src={birdImageUrl} alt='bird' />
</Link>
</div>
<div className='flex lg:hidden'>
Expand Down Expand Up @@ -78,7 +80,7 @@ export const Navbar = () => {
<ProfileDropdown />
) : (
<a
href={`${import.meta.env.VITE_API_URL}/auth/login?redirect=${
href={`${getUrl()}/api/auth/login?redirect=${
window.location.href
}`}
className='my-auto text-sm font-semibold leading-6 text-gray-900 dark:text-gray-200'
Expand Down
4 changes: 2 additions & 2 deletions client/src/components/ProfileDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Menu, Transition } from '@headlessui/react';
import { Fragment } from 'react';
import { User } from 'react-feather';

import { classNames } from '../lib/utils';
import { classNames, getUrl } from '../lib/utils';

export const ProfileDropdown = () => {
return (
Expand Down Expand Up @@ -41,7 +41,7 @@ export const ProfileDropdown = () => {
<Menu.Item>
{({ active }) => (
<a
href={`${import.meta.env.VITE_API_URL}/auth/logout?redirect=${
href={`${getUrl()}/api/auth/logout?redirect=${
window.location.origin
}`}
className={classNames(
Expand Down
17 changes: 9 additions & 8 deletions client/src/components/SideNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import { Fragment } from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router-dom';

import birdImageUrl from '../assets/bird.png';
import { useAuth } from '../hooks/useAuth';
import { useDarkMode } from '../hooks/useDarkMode';
import { classNames } from '../lib/utils';
import { classNames, getUrl } from '../lib/utils';
import { DarkModeToggle } from './DarkModeToggle';
import { navigationItems } from './Footer';

Expand Down Expand Up @@ -67,7 +68,7 @@ export const SideNav = ({ open, onClose }: SideNavProps) => {
<div className='mt-1 flex items-center justify-between'>
<div className='flex items-center'>
<Link to='/' className=''>
<img className='h-8 w-auto' src='/bird.png' alt='' />
<img className='h-8 w-auto' src={birdImageUrl} alt='bird' />
</Link>
<div className='ml-6'>
<DarkModeToggle />
Expand Down Expand Up @@ -105,19 +106,19 @@ export const SideNav = ({ open, onClose }: SideNavProps) => {
Profile
</Link>
<a
href={`${
import.meta.env.VITE_API_URL
}/auth/logout?redirect=${window.location.origin}`}
href={`${getUrl()}/api/auth/logout?redirect=${
window.location.origin
}`}
className='-mx-3 block rounded-lg px-3 py-2.5 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50 dark:text-gray-200 dark:hover:bg-neutral-700'
>
Log out
</a>
</>
) : (
<a
href={`${
import.meta.env.VITE_API_URL
}/auth/login?redirect=${window.location.href}`}
href={`${getUrl()}/api/auth/login?redirect=${
window.location.href
}`}
className='-mx-3 block rounded-lg px-3 py-2.5 text-base font-semibold leading-7 text-gray-900 hover:bg-gray-50 dark:text-gray-200 dark:hover:bg-neutral-700'
>
Log in
Expand Down
4 changes: 4 additions & 0 deletions client/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,7 @@ export const sortSchedulesByBlocks = (schedules: Schedule[]) => {
: order.indexOf(aType) - order.indexOf(bType);
});
};

export const getUrl = (): string => {
return import.meta.env.VITE_API_URL ?? '';
};
43 changes: 16 additions & 27 deletions crates/db/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@ impl Db {
const REVIEW_COLLECTION: &str = "reviews";

pub async fn connect(db_name: &str) -> Result<Self> {
let mut client_options =
ClientOptions::parse(format!("mongodb://localhost:27017/{}", db_name))
.await?;
let mut client_options = ClientOptions::parse(format!(
"{}/{}",
env::var("MONGODB_URL")
.unwrap_or_else(|_| "mongodb://localhost:27017".into()),
db_name
))
.await?;

client_options.app_name = Some(db_name.to_string());

Expand Down Expand Up @@ -104,25 +108,7 @@ impl Db {
self.find_course(doc! { "_id": id }).await
}

pub async fn add_review(&self, review: Review) -> Result<InsertOneResult> {
if self
.find_review(&review.course_id, &review.user_id)
.await?
.is_some()
{
Err(anyhow!("Cannot review this course twice"))
} else {
Ok(
self
.database
.collection::<Review>(Self::REVIEW_COLLECTION)
.insert_one(review, None)
.await?,
)
}
}

pub async fn update_review(&self, review: Review) -> Result<UpdateResult> {
pub async fn add_review(&self, review: Review) -> Result<UpdateResult> {
Ok(
self
.database
Expand All @@ -135,12 +121,13 @@ impl Db {
UpdateModifications::Document(doc! {
"$set": {
"content": &review.content,
"difficulty": review.difficulty,
"instructors": &review.instructors,
"rating": review.rating,
"timestamp": review.timestamp
},
}),
None,
UpdateOptions::builder().upsert(true).build(),
)
.await?,
)
Expand Down Expand Up @@ -1058,9 +1045,11 @@ mod tests {
..Default::default()
};

db.add_review(review.clone()).await.unwrap();
for _ in 0..10 {
db.add_review(review.clone()).await.unwrap();
}

assert!(db.add_review(review).await.is_err());
assert_eq!(db.reviews().await.unwrap().len(), 1);
}

#[tokio::test(flavor = "multi_thread")]
Expand All @@ -1082,7 +1071,7 @@ mod tests {
let timestamp = DateTime::from_chrono::<Utc>(Utc::now());

assert_eq!(
db.update_review(Review {
db.add_review(Review {
content: "bar".into(),
course_id: "MATH240".into(),
instructors: vec![String::from("foo")],
Expand All @@ -1098,7 +1087,7 @@ mod tests {
);

assert_eq!(
db.update_review(Review {
db.add_review(Review {
content: "bar".into(),
course_id: "MATH240".into(),
instructors: vec![String::from("foo")],
Expand Down
2 changes: 1 addition & 1 deletion crates/db/src/initializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ impl Initializer {
}

pub(crate) async fn run(&self) -> Result {
self.seed().await?;
self.index().await?;
self.seed().await?;
Ok(())
}

Expand Down
5 changes: 2 additions & 3 deletions crates/db/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use {
anyhow::anyhow,
bson::Bson,
futures::Future,
futures::{future::join_all, TryStreamExt},
Expand All @@ -13,11 +12,11 @@ use {
bson::{doc, Document},
options::UpdateModifications,
options::{ClientOptions, FindOptions, IndexOptions, UpdateOptions},
results::{CreateIndexResult, DeleteResult, InsertOneResult, UpdateResult},
results::{CreateIndexResult, DeleteResult, UpdateResult},
Client, Cursor, Database, IndexModel,
},
serde::{de::DeserializeOwned, Serialize},
std::{collections::HashSet, fs, hash::Hash, path::PathBuf},
std::{collections::HashSet, env, fs, hash::Hash, path::PathBuf},
{
crate::combine::Combine, initializer::Initializer, seed::Seed,
str_ext::StrExt,
Expand Down
Loading

0 comments on commit 2a53433

Please sign in to comment.