├── .env ├── .gitignore ├── .project ├── Cargo.toml ├── LICENSE ├── README.md ├── client ├── Cargo.toml ├── README.md ├── index.html ├── src │ ├── main.rs │ ├── models.rs │ ├── pages │ │ ├── about.rs │ │ ├── game.rs │ │ ├── game_state_worker.rs │ │ ├── mod.rs │ │ ├── page_not_found.rs │ │ └── register.rs │ └── rest_helper.rs └── styles.scss ├── connect5.db ├── connect5.db-shm ├── connect5.db-wal ├── diesel.toml ├── img.png └── server ├── Cargo.toml ├── connect5.db ├── connect5.db-shm ├── diesel.toml ├── migrations ├── .gitkeep └── 2020-06-19-114229_create_db │ ├── down.sql │ └── up.sql ├── src ├── api.rs ├── db.rs ├── game.rs ├── lib.rs ├── main.rs ├── models.rs ├── schema.rs └── utils.rs └── tests └── test_server.rs /.env: -------------------------------------------------------------------------------- 1 | DATABASE_URL=file:connect5.db 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | #/server/static/package.json 13 | #/server/static/wasm.d.ts 14 | #/server/static/wasm.js 15 | #/server/static/wasm_bg.d.ts 16 | #/server/static/wasm_bg.wasm 17 | /server/static 18 | client/dist 19 | .idea 20 | server/connect5.db-wal 21 | .vscode 22 | connect5.code-workspace 23 | 24 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | connect5-rust 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 2 | 3 | [workspace] 4 | members = ["client", "server"] 5 | #exclude = ["crates/foo", "path/to/other"] 6 | 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Full-stack Rust with WebAssembly 2 | 3 | # Look Ma, No JavaScript !!! 4 | 5 | ![img.png](img.png) 6 | 7 | My very first Rust project (implementation of the "Connect 5" game), I used as a learning tool. 8 | 9 | My goal was to create some sort of a "reference implementation" of a Fullstack Rust application. Hopefully you will find it useful :). 10 | Here you can find how to: 11 | ### Client: 12 | - build Web client in Rust, without a single line of JavaScript, using [Yew](https://github.com/yewstack/yew) WebAssembly framework 13 | - use [yew-router](https://github.com/yewstack/yew/tree/master/packages/yew-router) for navigation between pages 14 | - use multithreading components, communicating by "message passing" with Yew Agents 15 | - use Yew StorageService to keep session data 16 | - utilise a CSS framework ([Bulma](https://bulma.io)) 17 | 18 | ### Server: 19 | - Use [Actix Web](https://github.com/actix/actix-web) web framework to implement REST API 20 | - [Diesel](https://diesel.rs) ORM with SQLite as default DB 21 | - Session cookies 22 | - Integration testing for the REST API 23 | - Mocking functions (db calls) in unit tests 24 | 25 | 26 | #### Usage: 27 | 28 | Install trunk and build the client: 29 | ``` 30 | cd client 31 | cargo install trunk wasm-bindgen-cli 32 | trunk build -d ../server/static/ 33 | ``` 34 | 35 | Start the server: 36 | ``` bash 37 | cd server 38 | cargo run --package connect5-rust --bin connect5-rust 39 | ``` 40 | Open http://127.0.0.1:8088/ in your browser. Open a second session in another browser for player #2. 41 | 42 | 43 | There are still few things that need to be improved/fixed, but the project served it's purpose (for me, at least) and is useful as it is, so I'll probably won't be fixing them. Feel free, however, to do so and may be create some PR(s) :) 44 | -------------------------------------------------------------------------------- /client/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "client" 3 | version = "0.1.0" 4 | authors = ["Vasco "] 5 | edition = "2018" 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | #[lib] 9 | #crate-type = ["cdylib", "rlib"] 10 | 11 | [dependencies] 12 | # client deps 13 | instant = { version = "0.1", features = ["wasm-bindgen"] } 14 | getrandom = { version = "0.2", features = ["js"] } 15 | rand = { version = "0.8.4", features = ["small_rng"] } 16 | wasm-logger = "0.2" 17 | 18 | #yew = { git = "https://github.com/yewstack/yew.git", branch = "master" } 19 | yew = "0.18.0" 20 | yew-macro = "0.18.0" 21 | yew-router = "0.15.0" 22 | yew-router-macro = "0.15.0" 23 | 24 | yewtil = "0.4.0" 25 | wasm-bindgen-futures = "0.4.23" 26 | wasm-bindgen = { version = "0.2.76", features = ["serde-serialize"] } 27 | 28 | serde = "1.0.111" 29 | serde_json = "1.0.53" 30 | serde_derive = "1.0.59" 31 | log = "0.4.11" 32 | anyhow = "1.0.40" 33 | 34 | [dependencies.web-sys] 35 | version = "0.3" 36 | features = [ 37 | "Headers", 38 | 'HtmlLinkElement', 39 | 'Location', 40 | 'MouseEvent', 41 | 'PopStateEvent', 42 | "Request", 43 | "RequestInit", 44 | "RequestMode", 45 | "ResponseInit", 46 | "Response", 47 | "Window",] -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | Install `wasm-pack`, as described here: [https://yew.rs/docs/getting-started/project-setup/using-wasm-pack](https://yew.rs/docs/getting-started/project-setup/using-wasm-pack). 2 | 3 | Build from within the `client` directory: 4 | 5 | ```shell script 6 | wasm-pack build --target web --out-name wasm --out-dir ../server/static 7 | ``` 8 | 9 | or 10 | 11 | ``` shell 12 | trunk build -d ../server/static/ 13 | ``` 14 | Wasm package will be published in `server/static` directory. 15 | 16 | -------------------------------------------------------------------------------- /client/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 11 | Connect5 Client 12 | 13 | -------------------------------------------------------------------------------- /client/src/main.rs: -------------------------------------------------------------------------------- 1 | #![recursion_limit = "512"] 2 | 3 | use yew::prelude::*; 4 | use yew::{html, Component, ComponentLink, Html, ShouldRender}; 5 | use yew_router::{components::RouterAnchor, prelude::*, switch::Permissive}; 6 | 7 | use pages::{about::About, game::Game, page_not_found::PageNotFound, register::Register}; 8 | 9 | mod models; 10 | mod pages; 11 | mod rest_helper; 12 | 13 | #[derive(Clone, Debug, Switch)] 14 | pub enum AppRoute { 15 | #[to = "/about/"] 16 | About, 17 | #[to = "/game/"] 18 | Game, 19 | #[to = "/page-not-found"] 20 | PageNotFound(Permissive), 21 | #[to = "/"] 22 | Register, 23 | } 24 | pub type AppRouter = Router; 25 | pub type AppAnchor = RouterAnchor; 26 | 27 | enum Msg { 28 | ToggleNavbar, 29 | } 30 | 31 | struct Model { 32 | link: ComponentLink, 33 | navbar_active: bool, 34 | } 35 | 36 | impl Component for Model { 37 | type Message = Msg; 38 | type Properties = (); 39 | 40 | fn create(_: Self::Properties, link: ComponentLink) -> Self { 41 | Self { 42 | link, 43 | navbar_active: false, 44 | } 45 | } 46 | 47 | fn update(&mut self, msg: Self::Message) -> ShouldRender { 48 | match msg { 49 | Msg::ToggleNavbar => { 50 | self.navbar_active = !self.navbar_active; 51 | true 52 | } 53 | } 54 | } 55 | 56 | fn change(&mut self, _props: Self::Properties) -> ShouldRender { 57 | false 58 | } 59 | 60 | fn view(&self) -> Html { 61 | html! { 62 | <> 63 | { self.view_nav() } 64 | 65 |
66 | 67 | render = Router::render(Self::switch) 68 | /> 69 |
70 | 80 | 81 | } 82 | } 83 | } 84 | impl Model { 85 | fn view_nav(&self) -> Html { 86 | let Self { 87 | ref link, 88 | navbar_active, 89 | .. 90 | } = *self; 91 | let active_class = if navbar_active { "is-active" } else { "" }; 92 | html! { 93 | 121 | } 122 | } 123 | fn switch(route: AppRoute) -> Html { 124 | match route { 125 | AppRoute::About => { 126 | html! { } 127 | } 128 | AppRoute::Register => { 129 | html! { } 130 | } 131 | AppRoute::Game => { 132 | html! { } 133 | } 134 | AppRoute::PageNotFound(Permissive(route)) => { 135 | html! { } 136 | } 137 | } 138 | } 139 | } 140 | 141 | fn main() { 142 | wasm_logger::init(wasm_logger::Config::new(log::Level::Trace)); 143 | yew::start_app::(); 144 | } 145 | -------------------------------------------------------------------------------- /client/src/models.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | 3 | #[derive(Serialize, Deserialize, Debug, Clone)] 4 | pub struct GameState { 5 | pub id: String, 6 | pub board: Option, 7 | pub user_1: Option, 8 | pub user_2: Option, 9 | pub winner: bool, 10 | pub last_user_id: Option, 11 | pub last_user_color: Option, 12 | pub ended: bool, 13 | } 14 | 15 | #[derive(Serialize, Deserialize, Debug, Clone)] 16 | pub struct User { 17 | pub id: String, 18 | pub user_name: String, 19 | pub user_color: String, 20 | } 21 | 22 | pub enum ClientState { 23 | WaitingForThisUserTurn, 24 | WaitingForOtherUserTurn, 25 | GameOver(String), 26 | } 27 | 28 | pub const USER_INFO_KEY: &str = "user_info"; 29 | -------------------------------------------------------------------------------- /client/src/pages/about.rs: -------------------------------------------------------------------------------- 1 | use yew::prelude::*; 2 | 3 | pub struct About; 4 | impl Component for About { 5 | type Message = (); 6 | type Properties = (); 7 | 8 | fn create(_props: Self::Properties, _link: ComponentLink) -> Self { 9 | Self 10 | } 11 | 12 | fn update(&mut self, _msg: Self::Message) -> ShouldRender { 13 | unimplemented!() 14 | } 15 | 16 | fn change(&mut self, _props: Self::Properties) -> ShouldRender { 17 | false 18 | } 19 | 20 | fn view(&self) -> Html { 21 | html! { 22 |
23 |
24 |
25 |

{ "About" }

26 |

{ "Full-stack Rust with WebAssembly implementation of the Connect5 game" }

27 |
28 |
29 |
30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /client/src/pages/game.rs: -------------------------------------------------------------------------------- 1 | use crate::models::{ClientState, GameState, User, USER_INFO_KEY}; 2 | use crate::pages::game_state_worker::{ClientRequest, GameWorker, ServerResponse}; 3 | use std::cmp; 4 | use yew::format::Json; 5 | use yew::prelude::*; 6 | use yew::services::storage::Area; 7 | use yew::services::{ConsoleService, DialogService, StorageService}; 8 | 9 | // const ROWS: u32 = 6; //TODO: make these parameters 10 | const COLUMNS: u32 = 9; 11 | 12 | pub struct Game { 13 | link: ComponentLink, 14 | selected_column: Option, 15 | hover_column: Option, 16 | game_state: Option, 17 | game_state_worker: Box>, 18 | client_state: ClientState, 19 | this_user: User, 20 | } 21 | 22 | pub enum Msg { 23 | Initialize, 24 | SelectColumn(u32), 25 | MouseOver(u32), 26 | MouseOut(u32), 27 | DataReceived(ServerResponse), 28 | MakeMoveClick, 29 | } 30 | 31 | impl Component for Game { 32 | type Message = Msg; 33 | type Properties = (); 34 | 35 | fn create(_: Self::Properties, link: ComponentLink) -> Self { 36 | let callback = link.callback(Msg::DataReceived); 37 | let storage = StorageService::new(Area::Session).expect("storage was disabled by the user"); 38 | let this_user = get_user_info(&storage).expect("User not registered"); //this must have value, after user registration, panic otherwise 39 | let game_state_worker = GameWorker::bridge(callback); 40 | link.send_message(Msg::Initialize); 41 | Self { 42 | link, 43 | selected_column: None, 44 | hover_column: None, 45 | game_state: None, 46 | game_state_worker, 47 | client_state: ClientState::WaitingForThisUserTurn, 48 | this_user, 49 | } 50 | } 51 | 52 | fn update(&mut self, msg: Self::Message) -> ShouldRender { 53 | match msg { 54 | Msg::Initialize => { 55 | self.game_state_worker.send(ClientRequest::InitializeBoard); 56 | true 57 | } 58 | Msg::SelectColumn(column) => { 59 | self.selected_column = Some(column); 60 | true 61 | } 62 | Msg::MouseOver(column) => { 63 | self.hover_column = Some(column); 64 | true 65 | } 66 | Msg::MouseOut(_column) => { 67 | self.hover_column = None; 68 | true 69 | } 70 | Msg::DataReceived(data) => { 71 | ConsoleService::info("===============> Msg::DataReceived: "); 72 | self.process_response_data(data); 73 | true 74 | } 75 | Msg::MakeMoveClick => { 76 | match &self.client_state { 77 | ClientState::WaitingForThisUserTurn => { 78 | self.game_state_worker.send(ClientRequest::MakeMoveRequest( 79 | self.selected_column.unwrap(), 80 | )); 81 | } 82 | ClientState::WaitingForOtherUserTurn => { 83 | DialogService::alert("Please, wait for the other user turn to finish!"); 84 | } 85 | ClientState::GameOver(winner) => { 86 | DialogService::alert(&format!("GameOver! User {} won.", winner)); 87 | } 88 | } 89 | self.selected_column = None; 90 | true 91 | } 92 | } 93 | } 94 | 95 | fn change(&mut self, _props: Self::Properties) -> ShouldRender { 96 | false 97 | } 98 | 99 | fn view(&self) -> Html { 100 | html! { 101 |
102 |
103 |

{["Status: ", self.get_status_msg().as_str()].concat() }

104 |
105 |
106 | 107 | { (0..6).map(|row| self.view_row(row)).collect::() } 108 |
109 |
110 |
{format!("Selected column:{}", Game::print_selected_column(self.selected_column)) }
111 | 112 |
113 | } 114 | } 115 | } 116 | 117 | impl Game { 118 | fn get_status_msg(&self) -> String { 119 | if let ClientState::GameOver(winner) = &self.client_state { 120 | return format!("GameOver. User {} won,", winner); 121 | } 122 | match &self.game_state { 123 | Some(game_state) => match &game_state.last_user_id { 124 | Some(last_user_id) => { 125 | if last_user_id == &self.this_user.id { 126 | "Other user turn".to_string() 127 | } else { 128 | "Your turn".to_string() 129 | } 130 | } 131 | None => "Un-initialized".to_string(), 132 | }, 133 | None => "Un-initialized".to_string(), 134 | } 135 | } 136 | 137 | fn get_square_class(&self, row: u32, column: u32) -> &'static str { 138 | let mut board = "------------------------------------------------------"; //....I know, needs refactoring.....TODO 139 | if let Some(game_state) = self.game_state.as_ref() { 140 | board = game_state.board.as_ref().unwrap(); 141 | } 142 | 143 | match self.selected_column { 144 | Some(x) if x == column => "square_red", 145 | _ => match self.hover_column { 146 | Some(x) if x == column => "col_grey", 147 | _ => { 148 | let idx = (cmp::max(0, row) * COLUMNS + column) as usize; 149 | match &board[idx..idx + 1] { 150 | "X" => "X", 151 | "O" => "O", 152 | _ => "square_blue", 153 | } 154 | } 155 | }, 156 | } 157 | } 158 | 159 | fn view_square(&self, row: u32, column: u32) -> Html { 160 | html! { 161 | 165 | 166 | } 167 | } 168 | 169 | fn view_row(&self, row: u32) -> Html { 170 | html! { 171 | 172 | {for (0..9).map(|column| { 173 | self.view_square(row, column) 174 | })} 175 | 176 | } 177 | } 178 | 179 | fn print_selected_column(colum: Option) -> String { 180 | match colum { 181 | Some(x) => (x + 1).to_string(), 182 | None => "".to_owned(), 183 | } 184 | } 185 | 186 | pub(crate) fn process_response_data(&mut self, data: ServerResponse) { 187 | match data { 188 | ServerResponse::DataFetched(event_data) => { 189 | ConsoleService::info(&format!( 190 | "process_response_data DataFetched:{:#?}", 191 | event_data 192 | )); 193 | } 194 | ServerResponse::MakeMoveResponse(event_data) => { 195 | match event_data { 196 | Ok(game_state) => { 197 | self.game_state = Some(game_state); 198 | self.update_client_state(); 199 | } 200 | Err(err) => DialogService::alert(&err.err), 201 | }; 202 | } 203 | ServerResponse::GetGameStateResponse(event_data) => match event_data { 204 | Ok(game_state) => { 205 | self.game_state = Some(game_state); 206 | self.update_client_state(); 207 | } 208 | Err(err) => DialogService::alert(&err.err), 209 | }, 210 | ServerResponse::GameOver(winner) => { 211 | self.client_state = ClientState::GameOver(winner); 212 | } 213 | } 214 | } 215 | 216 | fn update_client_state(&mut self) { 217 | if self.game_state.as_ref().unwrap().winner { 218 | self.client_state = ClientState::GameOver( 219 | self.game_state 220 | .as_ref() 221 | .unwrap() 222 | .last_user_id 223 | .as_ref() 224 | .unwrap() 225 | .to_owned(), 226 | ); 227 | } else { 228 | match &self.game_state { 229 | Some(game_state) => match &game_state.last_user_id { 230 | Some(last_user_id) => { 231 | if last_user_id == &self.this_user.id { 232 | self.client_state = ClientState::WaitingForOtherUserTurn; 233 | } else { 234 | self.client_state = ClientState::WaitingForThisUserTurn; 235 | } 236 | } 237 | None => { 238 | self.client_state = ClientState::WaitingForThisUserTurn; 239 | } 240 | }, 241 | None => { 242 | self.client_state = ClientState::WaitingForThisUserTurn; 243 | } 244 | } 245 | } 246 | } 247 | } 248 | 249 | fn get_user_info(storage: &StorageService) -> Option { 250 | let Json(user_info): Json> = storage.restore(USER_INFO_KEY); 251 | match user_info { 252 | Ok(user) => Some(user), 253 | _ => None, 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /client/src/pages/game_state_worker.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | use std::{ 3 | error::Error, 4 | fmt::{self, Debug, Display, Formatter}, 5 | }; 6 | 7 | use serde::{Deserialize, Serialize}; 8 | use yew::agent::{Agent, AgentLink, HandlerId, Job}; 9 | use yew::format::Json; 10 | use yew::services::storage::Area; 11 | use yew::services::{IntervalService, StorageService, Task}; 12 | 13 | use crate::models::{ClientState, GameState, User, USER_INFO_KEY}; 14 | use crate::rest_helper; 15 | 16 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 17 | pub struct ServerError { 18 | pub err: String, 19 | } 20 | 21 | impl Display for ServerError { 22 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 23 | Debug::fmt(&self.err, f) 24 | } 25 | } 26 | 27 | impl Error for ServerError {} 28 | 29 | #[derive(Serialize, Deserialize, Debug)] 30 | pub enum ClientRequest { 31 | InitializeBoard, 32 | MakeMoveRequest(u32), 33 | } 34 | 35 | #[derive(Serialize, Deserialize, Debug)] 36 | pub enum ServerResponse { 37 | DataFetched(String), 38 | MakeMoveResponse(Result), 39 | GetGameStateResponse(Result), 40 | GameOver(String), 41 | } 42 | 43 | pub enum Msg { 44 | InitializeWorker, 45 | Updating, 46 | MakeMoveResponse(HandlerId, Result), 47 | GetGameStateResponse(HandlerId, Result), 48 | } 49 | 50 | pub struct GameWorker { 51 | this_user_id: Option, 52 | link: AgentLink, 53 | _task: Box, 54 | input_handler: Option, 55 | client_state: ClientState, 56 | storage: StorageService, 57 | } 58 | 59 | impl GameWorker { 60 | pub fn set_user_id(&mut self) { 61 | let Json(user_info): Json> = 62 | self.storage.restore(USER_INFO_KEY); 63 | if let Ok(user) = user_info { 64 | self.this_user_id = Some(user.id); 65 | } 66 | } 67 | 68 | fn get_game_state(&self) { 69 | let link = self.link.clone(); 70 | let input_handler = self.input_handler.unwrap(); 71 | let future = async move { 72 | let rest_response = rest_helper::get_game_state().await; 73 | link.send_message(Msg::GetGameStateResponse(input_handler, rest_response)); 74 | }; 75 | wasm_bindgen_futures::spawn_local(future); 76 | } 77 | } 78 | 79 | impl Agent for GameWorker { 80 | type Reach = Job; 81 | type Message = Msg; 82 | type Input = ClientRequest; 83 | type Output = ServerResponse; 84 | 85 | fn create(link: AgentLink) -> Self { 86 | let duration = Duration::from_secs(3); 87 | let state_update_callback = link.callback(|_| Msg::Updating); 88 | let state_update_task = IntervalService::spawn(duration, state_update_callback); 89 | let storage = StorageService::new(Area::Session).expect("storage was disabled by the user"); 90 | 91 | link.send_message(Msg::InitializeWorker); 92 | 93 | Self { 94 | this_user_id: None, 95 | link, 96 | _task: Box::new(state_update_task), 97 | input_handler: None, 98 | client_state: ClientState::WaitingForThisUserTurn, 99 | storage, 100 | } 101 | } 102 | 103 | fn update(&mut self, msg: Self::Message) { 104 | match msg { 105 | Msg::InitializeWorker => { 106 | self.set_user_id(); 107 | yew::services::ConsoleService::info("Game State Initialized!"); 108 | } 109 | Msg::Updating => { 110 | yew::services::ConsoleService::info("Updating Game State..."); 111 | 112 | if let Some(_input_handler) = self.input_handler { 113 | self.get_game_state(); 114 | } 115 | } 116 | Msg::MakeMoveResponse(who, fetched_response) => { 117 | let msg = match fetched_response { 118 | Ok(game_state) => { 119 | yew::services::ConsoleService::info( 120 | format!("update::Msg::MakeMoveResponse called: {:#?}", game_state) 121 | .as_str(), 122 | ); 123 | self.client_state = ClientState::WaitingForOtherUserTurn; 124 | ServerResponse::MakeMoveResponse(Ok(game_state)) 125 | } 126 | Err(err) => ServerResponse::MakeMoveResponse(Err(ServerError { err: err.err })), 127 | }; 128 | self.link.respond(who, msg); 129 | } 130 | Msg::GetGameStateResponse(who, fetched_response) => { 131 | match fetched_response { 132 | Ok(game_state) => { 133 | yew::services::ConsoleService::info( 134 | format!("update::Msg::UpdateBoardResponse called: {:#?}", game_state) 135 | .as_str(), 136 | ); 137 | if game_state.winner { 138 | let winer = game_state.last_user_id.clone(); 139 | self.client_state = ClientState::GameOver(winer.unwrap()) 140 | } 141 | 142 | match &self.client_state { 143 | ClientState::WaitingForThisUserTurn => { 144 | if game_state.last_user_id == self.this_user_id { 145 | // start waiting for the other user turn 146 | self.client_state = ClientState::WaitingForOtherUserTurn 147 | } 148 | } 149 | ClientState::WaitingForOtherUserTurn => { 150 | if game_state.last_user_id != self.this_user_id { 151 | // start waiting for this user turn 152 | self.client_state = ClientState::WaitingForThisUserTurn 153 | } 154 | } 155 | ClientState::GameOver(winner) => { 156 | let msg = ServerResponse::GameOver(winner.to_string()); 157 | self.link.respond(who, msg); 158 | } 159 | } 160 | let msg = ServerResponse::GetGameStateResponse(Ok(game_state)); 161 | self.link.respond(who, msg); 162 | } 163 | Err(err) => { 164 | yew::services::DialogService::alert(&err.err); 165 | } 166 | }; 167 | } 168 | } 169 | } 170 | 171 | fn handle_input(&mut self, msg: Self::Input, who: HandlerId) { 172 | yew::services::ConsoleService::info(&format!("Request: {:?}", msg)); 173 | self.input_handler = Some(who); 174 | let link = self.link.clone(); 175 | let future = async move { 176 | match msg { 177 | ClientRequest::InitializeBoard => { 178 | let rest_response = rest_helper::get_game_state().await; 179 | link.send_message(Msg::GetGameStateResponse(who, rest_response)); 180 | } 181 | ClientRequest::MakeMoveRequest(column) => { 182 | let rest_response = rest_helper::make_move(column).await; 183 | link.send_message(Msg::MakeMoveResponse(who, rest_response)); 184 | } 185 | }; 186 | }; 187 | wasm_bindgen_futures::spawn_local(future); 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /client/src/pages/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod about; 2 | pub mod game; 3 | mod game_state_worker; 4 | pub mod page_not_found; 5 | pub mod register; 6 | -------------------------------------------------------------------------------- /client/src/pages/page_not_found.rs: -------------------------------------------------------------------------------- 1 | use yew::prelude::*; 2 | use yewtil::NeqAssign; 3 | 4 | #[derive(Clone, Debug, Eq, PartialEq, Properties)] 5 | pub struct Props { 6 | pub route: Option, 7 | } 8 | 9 | pub struct PageNotFound { 10 | props: Props, 11 | } 12 | impl Component for PageNotFound { 13 | type Message = (); 14 | type Properties = Props; 15 | 16 | fn create(props: Self::Properties, _link: ComponentLink) -> Self { 17 | Self { props } 18 | } 19 | 20 | fn update(&mut self, _msg: Self::Message) -> ShouldRender { 21 | unimplemented!() 22 | } 23 | 24 | fn change(&mut self, props: Self::Properties) -> ShouldRender { 25 | self.props.neq_assign(props) 26 | } 27 | 28 | fn view(&self) -> Html { 29 | html! { 30 |
31 |
32 |
33 |

34 | { "Page not found" } 35 |

36 |

37 | { "This page does not seem to exist" } 38 |

39 |
40 |
41 |
42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /client/src/pages/register.rs: -------------------------------------------------------------------------------- 1 | use yew::format::Json; 2 | use yew::prelude::*; 3 | use yew_router::agent::{RouteAgentDispatcher, RouteRequest}; 4 | use yew_router::prelude::*; 5 | use yew::services::storage::Area; 6 | use yew::services::{ConsoleService, DialogService, StorageService}; 7 | 8 | use crate::models::{User, USER_INFO_KEY}; 9 | use crate::rest_helper; 10 | use crate::AppRoute; 11 | 12 | pub enum Msg { 13 | RegisterUser, 14 | UpdateNameInputText(String), 15 | UpdateColorInputText(String), 16 | RegisterUserResponse(Result), 17 | FindGameResponse(Result), 18 | JoinGameResponse(Result), 19 | NewGameResponse(Result), 20 | } 21 | 22 | pub struct Register { 23 | link: ComponentLink, 24 | user_name: Option, 25 | user_color: Option, 26 | user: Option, 27 | router: RouteAgentDispatcher, 28 | storage: StorageService, 29 | } 30 | 31 | impl Component for Register { 32 | type Message = Msg; 33 | type Properties = (); 34 | 35 | fn create(_props: Self::Properties, link: ComponentLink) -> Self { 36 | Self { 37 | link, 38 | user_name: None, 39 | user_color: None, 40 | user: None, 41 | router: RouteAgentDispatcher::new(), 42 | storage: StorageService::new(Area::Session).expect("storage was disabled by the user"), 43 | } 44 | } 45 | 46 | fn update(&mut self, msg: Self::Message) -> ShouldRender { 47 | match msg { 48 | Msg::RegisterUser => { 49 | ConsoleService::info("===============> ON_SUBMIT: <==================="); 50 | ConsoleService::info(&format!( 51 | "===============> DATA: {:?}, {:#?} <===================", 52 | self.user_name, self.user_color 53 | )); 54 | self.register_user(); 55 | true 56 | } 57 | Msg::UpdateNameInputText(val) => { 58 | println!("Name Input: {}", val); 59 | self.user_name = Some(val); 60 | true 61 | } 62 | Msg::UpdateColorInputText(val) => { 63 | println!("Color Input: {}", val); 64 | self.user_color = Some(val); 65 | true 66 | } 67 | Msg::RegisterUserResponse(fetched_response) => match fetched_response { 68 | Ok(result) => { 69 | ConsoleService::info( 70 | format!( 71 | "register::update::Msg::RegisterUserResponse called: {:#?}", 72 | result 73 | ) 74 | .as_str(), 75 | ); 76 | self.user = Some(result); 77 | self.store_user_info(); 78 | self.find_game(); 79 | true 80 | } 81 | Err(err) => { 82 | DialogService::alert(&err.err); 83 | true 84 | } 85 | }, 86 | Msg::FindGameResponse(fetched_response) => match fetched_response { 87 | Ok(game_session_id) => { 88 | ConsoleService::info( 89 | format!( 90 | "register::update::Msg::FindGameResponse called: {}", 91 | game_session_id 92 | ) 93 | .as_str(), 94 | ); 95 | if game_session_id == "No existing session found" { 96 | self.new_game(); 97 | } else { 98 | self.join_game(game_session_id); 99 | } 100 | true 101 | } 102 | Err(err) => { 103 | DialogService::alert(&err.err); 104 | self.new_game(); 105 | true 106 | } 107 | }, 108 | Msg::JoinGameResponse(fetched_response) => { 109 | match fetched_response { 110 | Ok(_result) => { 111 | ConsoleService::info( 112 | format!( 113 | "register::update::Msg::JoinGameResponse called: {}", 114 | _result 115 | ) 116 | .as_str(), 117 | ); 118 | // Navigate to the "Game" page 119 | self.goto_game_page(); 120 | false 121 | } 122 | Err(err) => { 123 | DialogService::alert(&err.err); 124 | self.new_game(); 125 | true 126 | } 127 | } 128 | } 129 | Msg::NewGameResponse(fetched_response) => { 130 | match fetched_response { 131 | Ok(game_session_id) => { 132 | ConsoleService::info( 133 | format!( 134 | "register::update::Msg::NewGameResponse called: {}", 135 | game_session_id 136 | ) 137 | .as_str(), 138 | ); 139 | // Navigate to the "Game" page 140 | self.goto_game_page(); 141 | false 142 | } 143 | Err(err) => { 144 | DialogService::alert(&err.err); 145 | true 146 | } 147 | } 148 | } 149 | } 150 | } 151 | 152 | fn change(&mut self, _props: Self::Properties) -> ShouldRender { 153 | false 154 | } 155 | 156 | fn view(&self) -> Html { 157 | html! { 158 |
159 |
160 |
161 |

{ "New Game user registration" }

162 |
163 | 164 | 167 | 168 | 171 | 174 |
175 |
176 |
177 |
178 | } 179 | } 180 | } 181 | 182 | impl Register { 183 | fn goto_game_page(&mut self) { 184 | let route = Route::from(AppRoute::Game); 185 | self.router.send(RouteRequest::ChangeRoute(route)); 186 | } 187 | 188 | fn register_user(&mut self) { 189 | let link = self.link.clone(); 190 | let user_name = self.user_name.clone(); 191 | let user_color = self.user_color.clone(); 192 | let future = async move { 193 | let rest_response = 194 | rest_helper::register_user(&user_name.unwrap(), &user_color.unwrap()).await; 195 | link.send_message(Msg::RegisterUserResponse(rest_response)); 196 | }; 197 | wasm_bindgen_futures::spawn_local(future); 198 | } 199 | 200 | fn find_game(&mut self) { 201 | let link = self.link.clone(); 202 | let future = async move { 203 | let rest_response = rest_helper::find_game().await; 204 | link.send_message(Msg::FindGameResponse(rest_response)); 205 | }; 206 | wasm_bindgen_futures::spawn_local(future); 207 | } 208 | 209 | fn join_game(&mut self, game_session_id: String) { 210 | let link = self.link.clone(); 211 | let future = async move { 212 | let rest_response = rest_helper::join_game(&game_session_id).await; 213 | link.send_message(Msg::JoinGameResponse(rest_response)); 214 | }; 215 | wasm_bindgen_futures::spawn_local(future); 216 | } 217 | 218 | fn new_game(&mut self) { 219 | let link = self.link.clone(); 220 | let future = async move { 221 | let rest_response = rest_helper::new_game().await; 222 | link.send_message(Msg::NewGameResponse(rest_response)); 223 | }; 224 | wasm_bindgen_futures::spawn_local(future); 225 | } 226 | 227 | fn store_user_info(&mut self) { 228 | self.storage.store(USER_INFO_KEY, Json(&self.user.clone())); 229 | } 230 | } 231 | -------------------------------------------------------------------------------- /client/src/rest_helper.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use std::{ 3 | error::Error, 4 | fmt::{self, Debug, Display, Formatter}, 5 | str, 6 | }; 7 | use wasm_bindgen::JsCast; 8 | use wasm_bindgen::JsValue; 9 | use wasm_bindgen_futures::JsFuture; 10 | use web_sys::{Request, RequestInit, RequestMode, Response}; 11 | 12 | use crate::models; 13 | 14 | #[derive(Debug, Clone, PartialEq)] 15 | pub struct FetchError { 16 | pub err: JsValue, 17 | } 18 | 19 | impl Display for FetchError { 20 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 21 | Debug::fmt(&self.err, f) 22 | } 23 | } 24 | 25 | impl Error for FetchError {} 26 | 27 | impl From for FetchError { 28 | fn from(value: JsValue) -> Self { 29 | Self { err: value } 30 | } 31 | } 32 | 33 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] 34 | pub struct RestError { 35 | pub err: String, 36 | } 37 | 38 | impl Display for RestError { 39 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 40 | Debug::fmt(&self.err, f) 41 | } 42 | } 43 | 44 | impl Error for RestError {} 45 | 46 | pub async fn do_post(url: &str) -> Result { 47 | send_request("POST", url).await 48 | } 49 | 50 | pub async fn do_get(url: &str) -> Result { 51 | send_request("GET", url).await 52 | } 53 | 54 | //TODO use the new Yew FetchService 55 | pub async fn send_request<'a>(method: &'a str, url: &'a str) -> Result { 56 | let mut opts = RequestInit::new(); 57 | opts.method(method); 58 | opts.mode(RequestMode::Cors); 59 | 60 | let request = Request::new_with_str_and_init(url, &opts)?; 61 | 62 | let window = yew::utils::window(); 63 | 64 | let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?; 65 | let resp: Response = resp_value.dyn_into().unwrap(); 66 | 67 | let resp_text: JsValue = JsFuture::from(resp.text()?).await?; 68 | 69 | Ok(resp_text) 70 | } 71 | 72 | fn get_base_url() -> String { 73 | let origin = yew::utils::origin().expect("Can't get the origin of the current window!"); 74 | let base_url = format!("{}/api", origin); 75 | base_url 76 | } 77 | 78 | fn return_string(resp_text: Result) -> Result { 79 | Ok(resp_text.unwrap().as_string().unwrap()) 80 | } 81 | 82 | fn return_game_state( 83 | resp_text: Result, 84 | ) -> Result { 85 | let result = 86 | serde_json::from_str::(&resp_text.unwrap().as_string().unwrap()); 87 | match result { 88 | Ok(game_state) => Ok(game_state), 89 | Err(err) => Err(RestError { 90 | err: err.to_string(), 91 | }), 92 | } 93 | } 94 | 95 | fn return_user(resp_text: Result) -> Result { 96 | let result = serde_json::from_str::(&resp_text.unwrap().as_string().unwrap()); 97 | match result { 98 | Ok(user) => Ok(user), 99 | Err(err) => Err(RestError { 100 | err: err.to_string(), 101 | }), 102 | } 103 | } 104 | 105 | pub async fn register_user(user_name: &str, user_color: &str) -> Result { 106 | let base_url = get_base_url(); 107 | let url = format!("{}/{}/{}/{}", base_url, "register", user_name, user_color); 108 | let result = do_post(&url).await; 109 | return_user(result) 110 | } 111 | 112 | pub async fn new_game() -> Result { 113 | let base_url = get_base_url(); 114 | let url = format!("{}/{}", base_url, "new"); 115 | let result = do_get(&url).await; 116 | return_string(result) 117 | } 118 | 119 | pub async fn find_game() -> Result { 120 | let url = format!("{}/{}", get_base_url(), "find"); 121 | let result = do_get(&url).await; 122 | return_string(result) 123 | } 124 | 125 | pub async fn join_game(game_session_id: &str) -> Result { 126 | let url = format!("{}/{}/{}", get_base_url(), "join", game_session_id); 127 | let result = do_post(&url).await; 128 | return_string(result) 129 | } 130 | 131 | pub async fn get_game_state() -> Result { 132 | let url = format!("{}/{}", get_base_url(), "game-state"); 133 | let result = do_get(&url).await; 134 | return_game_state(result) 135 | } 136 | 137 | pub async fn make_move(column: u32) -> Result { 138 | let url = format!("{}/{}/{}", get_base_url(), "make-move", column + 1); 139 | let result = do_post(&url).await; 140 | return_game_state(result) 141 | } 142 | -------------------------------------------------------------------------------- /client/styles.scss: -------------------------------------------------------------------------------- 1 | html, 2 | body { 3 | margin: 0; 4 | /*padding: 20px;*/ 5 | text-align: center; 6 | padding-left: 100px; 7 | padding-top: 20px; 8 | } 9 | 10 | body { 11 | width: 1000px; 12 | height: 1000px; 13 | } 14 | 15 | .table { 16 | tr { 17 | height: 100px; 18 | } 19 | 20 | td { 21 | width: 100px; 22 | } 23 | .square_blue { 24 | background-color: #7777d9 25 | } 26 | 27 | .square_red{ 28 | background-color: #aa5555 29 | } 30 | 31 | .col_grey{ 32 | background-color: #4e4d4d 33 | } 34 | 35 | .X { 36 | background-color: green; 37 | } 38 | 39 | .O { 40 | background-color: red; 41 | } 42 | } 43 | 44 | .hero { 45 | &.has-background { 46 | position: relative; 47 | overflow: hidden; 48 | } 49 | 50 | &-background { 51 | position: absolute; 52 | object-fit: cover; 53 | object-position: bottom; 54 | width: 100%; 55 | height: 100%; 56 | 57 | &.is-transparent { 58 | opacity: 0.3; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /connect5.db: -------------------------------------------------------------------------------- 1 | SQLite format 3@ .4  -------------------------------------------------------------------------------- /connect5.db-shm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vascokk/fullstack-rust/970755df5ec8a5c0a6d7338a43a360cd5f62bf00/connect5.db-shm -------------------------------------------------------------------------------- /connect5.db-wal: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vascokk/fullstack-rust/970755df5ec8a5c0a6d7338a43a360cd5f62bf00/connect5.db-wal -------------------------------------------------------------------------------- /diesel.toml: -------------------------------------------------------------------------------- 1 | # For documentation on how to configure this file, 2 | # see diesel.rs/guides/configuring-diesel-cli 3 | 4 | [print_schema] 5 | file = "src/schema.rs" 6 | -------------------------------------------------------------------------------- /img.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vascokk/fullstack-rust/970755df5ec8a5c0a6d7338a43a360cd5f62bf00/img.png -------------------------------------------------------------------------------- /server/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "connect5-rust" 3 | version = "0.1.0" 4 | authors = ["Vasco "] 5 | edition = "2018" 6 | include = ["src/**/*", "static/**/*"] 7 | 8 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 9 | 10 | [dependencies] 11 | serde = "1.0.126" 12 | serde_json = "1.0.64" 13 | actix = "0.11.0" 14 | actix-web = "3.3.2" 15 | actix-rt = "1.1.1" 16 | actix-files = "0.5.0" 17 | actix-session = "0.4.1" 18 | bytes = "1.0.1" 19 | itertools = "0.10.0" 20 | diesel = { version = "1.4.6", features = ["sqlite", "uuidv07", "r2d2"] } 21 | dotenv = "0.15.0" 22 | uuid = { version = "0.8.2", features = ["serde", "v4"] } 23 | log = "0.4.11" 24 | 25 | [dev-dependencies] 26 | mocktopus = "0.7.0" -------------------------------------------------------------------------------- /server/connect5.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vascokk/fullstack-rust/970755df5ec8a5c0a6d7338a43a360cd5f62bf00/server/connect5.db -------------------------------------------------------------------------------- /server/connect5.db-shm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vascokk/fullstack-rust/970755df5ec8a5c0a6d7338a43a360cd5f62bf00/server/connect5.db-shm -------------------------------------------------------------------------------- /server/diesel.toml: -------------------------------------------------------------------------------- 1 | # For documentation on how to configure this file, 2 | # see diesel.rs/guides/configuring-diesel-cli 3 | 4 | [print_schema] 5 | file = "src/schema.rs" 6 | -------------------------------------------------------------------------------- /server/migrations/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vascokk/fullstack-rust/970755df5ec8a5c0a6d7338a43a360cd5f62bf00/server/migrations/.gitkeep -------------------------------------------------------------------------------- /server/migrations/2020-06-19-114229_create_db/down.sql: -------------------------------------------------------------------------------- 1 | -- This file should undo anything in `up.sql` 2 | DROP TABLE game_state; 3 | DROP TABLE user; -------------------------------------------------------------------------------- /server/migrations/2020-06-19-114229_create_db/up.sql: -------------------------------------------------------------------------------- 1 | -- Your SQL goes here 2 | CREATE TABLE game_state ( 3 | id TEXT PRIMARY KEY NOT NULL , 4 | board TEXT, 5 | user_1 TEXT, 6 | user_2 TEXT, 7 | winner BOOLEAN NOT NULL DEFAULT 'f', 8 | last_user_id TEXT, 9 | last_user_color TEXT(1), 10 | ended BOOLEAN NOT NULL DEFAULT 'f' 11 | ); 12 | 13 | CREATE TABLE user ( 14 | id TEXT PRIMARY KEY NOT NULL , 15 | user_name TEXT NOT NULL , 16 | user_color TEXT(1) NOT NULL 17 | ); 18 | 19 | INSERT INTO user VALUES ('1', 'user1', 'X'); 20 | INSERT INTO user VALUES ('2', 'user2', 'O'); -------------------------------------------------------------------------------- /server/src/api.rs: -------------------------------------------------------------------------------- 1 | use actix_session::Session; 2 | use actix_web::{web, Error, HttpRequest, HttpResponse}; 3 | 4 | use serde_json::json; 5 | use std::result::Result; 6 | 7 | pub use crate::db; 8 | pub use crate::game; 9 | pub use crate::models; 10 | pub use crate::schema; 11 | use diesel::r2d2::{ConnectionManager, Pool, PooledConnection}; 12 | use diesel::SqliteConnection; 13 | use std::ops::Deref; 14 | use uuid::Uuid; 15 | 16 | const SESSION_ID_KEY: &str = "session_id"; 17 | const USER_ID_KEY: &str = "user_id"; 18 | const USER_COLOR_KEY: &str = "user_color"; 19 | 20 | fn get_db_connection( 21 | req: HttpRequest, 22 | ) -> Result>, Error> { 23 | if let Some(pool) = req.app_data::>>() { 24 | match pool.get() { 25 | Ok(conn) => Ok(conn), 26 | Err(error) => Err(Error::from( 27 | HttpResponse::BadGateway().body(error.to_string()), 28 | )), 29 | } 30 | } else { 31 | Err(Error::from(HttpResponse::BadGateway().body( 32 | "[api][get_db_connection] Can't get db connection".to_string(), 33 | ))) 34 | } 35 | } 36 | 37 | pub async fn register( 38 | web::Path((user_name, user_color)): web::Path<(String, String)>, 39 | session: Session, 40 | req: HttpRequest, 41 | ) -> Result { 42 | println!("REQ: {:?}", req); 43 | println!("User Name: {:?}", user_name); 44 | println!("User Color: {:?}", user_color); 45 | 46 | let conn = get_db_connection(req)?; 47 | let color = user_color; 48 | let name = user_name; 49 | match db::create_new_user(&name, &color, conn.deref()) { 50 | Ok(user_id) => { 51 | session.set(USER_ID_KEY, user_id.to_string())?; 52 | session.set(USER_COLOR_KEY, color.clone())?; 53 | let user = models::User { 54 | id: user_id.to_string(), 55 | user_name: name, 56 | user_color: color, 57 | }; 58 | Ok(HttpResponse::Ok().body(json!(user))) 59 | } 60 | Err(error) => { 61 | return Err(Error::from( 62 | HttpResponse::BadGateway().body(format!("Cant register new user: {}", error)), 63 | )) 64 | } 65 | } 66 | } 67 | 68 | pub async fn new_game(session: Session, req: HttpRequest) -> Result { 69 | println!("NEW GAME REQ: {:?}", req); 70 | 71 | let conn = get_db_connection(req)?; 72 | 73 | if let Some(user_id) = session.get::(USER_ID_KEY)? { 74 | match db::create_new_session(&user_id, conn.deref()) { 75 | Ok(session_id) => { 76 | session.set(SESSION_ID_KEY, session_id.to_string())?; 77 | Ok(HttpResponse::Ok().body(json!({ SESSION_ID_KEY: session_id.to_string() }))) 78 | } 79 | Err(error) => { 80 | return Err(Error::from( 81 | HttpResponse::BadGateway().body(format!("Cant create new session: {}", error)), 82 | )) 83 | } 84 | } 85 | } else { 86 | Err(Error::from( 87 | HttpResponse::BadGateway().body("Can't find the current user ID in session object"), 88 | )) 89 | } 90 | } 91 | 92 | pub async fn find(session: Session, req: HttpRequest) -> Result { 93 | println!("REQ: {:?}", req); 94 | let conn = get_db_connection(req)?; 95 | match db::find_existing_game_session(conn.deref()) { 96 | Some(game_state) => { 97 | session.set(SESSION_ID_KEY, game_state.id.to_owned())?; 98 | Ok(HttpResponse::Ok().body(game_state.id)) 99 | } 100 | None => Err(Error::from( 101 | HttpResponse::NotFound().body("No existing session found"), 102 | )), 103 | } 104 | } 105 | 106 | pub async fn join( 107 | game_session_id: web::Path, 108 | session: Session, 109 | req: HttpRequest, 110 | ) -> Result { 111 | println!("REQ: {:?}", req); 112 | let conn = get_db_connection(req)?; 113 | let game_id = game_session_id.into_inner(); 114 | if let Some(user_2_id) = session.get::(USER_ID_KEY)? { 115 | match db::join_game_session(&game_id, &user_2_id, conn.deref()) { 116 | Ok(0) => Err(Error::from( 117 | HttpResponse::NotFound().body(format!("No waiting sessions with id {}", &game_id)), 118 | )), 119 | Ok(1) => Ok(HttpResponse::Ok().body("OK")), 120 | Ok(_) => Err(Error::from( 121 | HttpResponse::BadGateway().body("Multiple sessions updated"), 122 | )), 123 | Err(error) => Err(Error::from( 124 | HttpResponse::BadGateway().body(format!("Cant join session: {}", error)), 125 | )), 126 | } 127 | } else { 128 | Err(Error::from( 129 | HttpResponse::BadGateway().body("Can't find the current user ID in session object"), 130 | )) 131 | } 132 | } 133 | 134 | #[deprecated] 135 | pub async fn board(session: Session, req: HttpRequest) -> Result { 136 | println!("REQ: {:?}", req); 137 | let conn = get_db_connection(req)?; 138 | if let Some(session_id) = session.get::(SESSION_ID_KEY)? { 139 | println!("API: board, session_id: {:?}", session_id); 140 | session.set(SESSION_ID_KEY, session_id)?; 141 | 142 | let res = db::get_board(&session_id, conn.deref()); 143 | match res { 144 | Ok(board_str) => Ok(HttpResponse::Ok().body(board_str)), 145 | _ => Err(Error::from( 146 | HttpResponse::InternalServerError() 147 | .body(format!("Can't find game with session id {}", session_id)), 148 | )), 149 | } 150 | } else { 151 | Err(Error::from( 152 | HttpResponse::InternalServerError().body("[board] Can't find game session!"), 153 | )) 154 | } 155 | } 156 | 157 | pub async fn game_state(session: Session, req: HttpRequest) -> Result { 158 | println!("REQ: {:?}", req); 159 | let conn = get_db_connection(req)?; 160 | if let Some(session_id) = session.get::(SESSION_ID_KEY)? { 161 | println!("API: board, session_id: {:?}", session_id); 162 | session.set(SESSION_ID_KEY, session_id)?; 163 | 164 | // let id = session_id.into_inner(); 165 | let res = db::get_game_state(&session_id, conn.deref()); 166 | match res { 167 | Ok(game_state) => Ok(HttpResponse::Ok().body(json!(game_state))), 168 | _ => Err(Error::from( 169 | HttpResponse::InternalServerError() 170 | .body(format!("Can't find game with session id {}", session_id)), 171 | )), 172 | } 173 | } else { 174 | Err(Error::from( 175 | HttpResponse::InternalServerError().body("[board] Can't find game session!"), 176 | )) 177 | } 178 | } 179 | 180 | pub async fn make_move( 181 | web::Path(column): web::Path, 182 | session: Session, 183 | req: HttpRequest, 184 | ) -> Result { 185 | println!("REQ: {:?}", req); 186 | let conn = get_db_connection(req)?; 187 | if let (Some(session_id), Some(user_id)) = ( 188 | session.get::(SESSION_ID_KEY)?, 189 | session.get::(USER_ID_KEY)?, 190 | ) { 191 | let res = game::user_move(session_id, user_id, column as usize, conn.deref()); 192 | match res { 193 | Ok(game_state) => { 194 | println!("API make_move returns: {:?}", game_state); 195 | Ok(HttpResponse::Ok().json(game_state)) 196 | } 197 | Err(msg) => Err(Error::from(HttpResponse::InternalServerError().body(msg))), 198 | } 199 | } else { 200 | Err(Error::from( 201 | HttpResponse::InternalServerError().body("[user_move] No session info!"), 202 | )) 203 | } 204 | } 205 | 206 | #[cfg(test)] 207 | pub mod tests { 208 | use super::*; 209 | use actix_session::UserSession; 210 | use actix_web::body::Body; 211 | use actix_web::http; 212 | use actix_web::http::Method; 213 | use actix_web::test::TestRequest; 214 | use mocktopus::mocking::*; 215 | use std::panic; 216 | 217 | use crate::utils; 218 | use db::create_conn_pool; 219 | use uuid::Uuid; 220 | 221 | fn get_body_str(response_body: &Body) -> String { 222 | match response_body { 223 | Body::Bytes(ref body_bytes) => { 224 | let body_str = std::str::from_utf8(body_bytes).unwrap(); 225 | body_str.to_owned() 226 | } 227 | _ => panic!("Response body is empty"), 228 | } 229 | } 230 | 231 | fn mock_db_create_new_session(test_session_id: Uuid) { 232 | db::create_new_session 233 | .mock_safe(move |_user, _conn| MockResult::Return(Result::Ok(test_session_id))); 234 | } 235 | 236 | fn mock_db_find_existing_game_session(test_session_id: Uuid, user_1_id: Uuid) { 237 | db::find_existing_game_session.mock_safe(move |_conn| { 238 | let game_state = models::GameState { 239 | id: test_session_id.to_string(), 240 | board: Some("------------------------------------------------------".to_owned()), 241 | user_1: Some(user_1_id.to_string()), 242 | user_2: None, 243 | winner: false, 244 | last_user_id: Some(user_1_id.to_string()), 245 | last_user_color: Some("X".to_string()), 246 | ended: false, 247 | }; 248 | MockResult::Return(Some(game_state)) 249 | }); 250 | } 251 | 252 | fn mock_db_create_new_user(user_id: Uuid) { 253 | db::create_new_user 254 | .mock_safe(move |_name, _color, _conn| MockResult::Return(Result::Ok(user_id))); 255 | } 256 | 257 | fn mock_db_get_board(board: &'static str) { 258 | db::get_board 259 | .mock_safe(move |_sess, _conn| MockResult::Return(Result::Ok(board.to_owned()))); 260 | } 261 | 262 | fn mock_db_get_game_state( 263 | test_session_id: Uuid, 264 | user_1_id: Uuid, 265 | user_2_id: Uuid, 266 | target_board: &'static str, 267 | ) { 268 | db::get_game_state.mock_safe(move |_sess, _conn| { 269 | let game_state = models::GameState { 270 | id: test_session_id.to_string(), 271 | board: Some(target_board.to_owned()), 272 | user_1: Some(user_1_id.to_string()), 273 | user_2: Some(user_2_id.to_string()), 274 | winner: false, 275 | last_user_id: Some(user_1_id.to_string()), 276 | last_user_color: Some("X".to_string()), 277 | ended: false, 278 | }; 279 | MockResult::Return(Result::Ok(game_state)) 280 | }); 281 | } 282 | 283 | fn mock_db_join_game_session() { 284 | db::join_game_session 285 | .mock_safe(move |_sess, _user, _conn| MockResult::Return(Result::Ok(1))); 286 | } 287 | 288 | fn mock_game_user_move(test_session_id: Uuid, user_1_id: Uuid, board: String) { 289 | game::user_move.mock_safe(move |_sess, _user_id, _col_num, _conn| { 290 | let game_state = models::GameState { 291 | id: test_session_id.to_string(), 292 | board: Some(board.to_owned()), 293 | user_1: Some(user_1_id.to_string()), 294 | user_2: None, 295 | winner: false, 296 | last_user_id: Some(user_1_id.to_string()), 297 | last_user_color: Some("X".to_string()), 298 | ended: false, 299 | }; 300 | MockResult::Return(Result::Ok(game_state)) 301 | }); 302 | } 303 | 304 | fn create_user_session(test_session_id: Uuid, test_user_id: Uuid) -> Session { 305 | let mut srv_req = TestRequest::post().to_srv_request(); 306 | Session::set_session( 307 | vec![ 308 | ( 309 | SESSION_ID_KEY.to_string(), 310 | serde_json::to_string(&test_session_id).unwrap(), 311 | ), 312 | ( 313 | USER_ID_KEY.to_string(), 314 | serde_json::to_string(&test_user_id).unwrap(), 315 | ), 316 | ( 317 | USER_COLOR_KEY.to_string(), 318 | serde_json::to_string("X").unwrap(), 319 | ), 320 | ] 321 | .into_iter(), 322 | &mut srv_req, 323 | ); 324 | 325 | srv_req.get_session() 326 | } 327 | 328 | #[actix_rt::test] 329 | async fn test_register_user_post() { 330 | let pool = create_conn_pool(); 331 | let req = TestRequest::with_header("content-type", "application/json") 332 | .method(Method::POST) 333 | .app_data(pool) 334 | .to_http_request(); 335 | 336 | let user_name = "test_user_name".to_string(); 337 | let user_color = "X".to_string(); 338 | 339 | let test_session_id = Uuid::new_v4(); 340 | let user_1 = Uuid::new_v4(); 341 | mock_db_create_new_session(test_session_id); 342 | mock_db_create_new_user(user_1); 343 | 344 | let session = create_user_session(test_session_id, user_1); 345 | 346 | let response = register( 347 | web::Path::from((user_name.clone(), user_color.clone())), 348 | session, 349 | req, 350 | ) 351 | .await 352 | .unwrap(); 353 | 354 | assert!(response.status().is_success()); 355 | println!("response: {:#?}", response); 356 | let response_body = &response.body().as_ref().unwrap(); 357 | match response_body { 358 | Body::Bytes(ref body_bytes) => { 359 | let user: models::User = serde_json::from_slice(body_bytes).unwrap(); 360 | assert_eq!(user.user_name, user_name); 361 | assert_eq!(user.user_color, user_color); 362 | assert_eq!(user.id, user_1.to_string()); 363 | } 364 | _ => panic!("Response body is empty"), 365 | } 366 | } 367 | 368 | #[actix_rt::test] 369 | async fn test_new_post() { 370 | let pool = create_conn_pool(); 371 | let req = TestRequest::with_header("content-type", "application/json") 372 | .method(Method::POST) 373 | .app_data(pool) 374 | .to_http_request(); 375 | 376 | let test_session_id = Uuid::new_v4(); 377 | mock_db_create_new_session(test_session_id); 378 | let user_1 = Uuid::new_v4(); 379 | let session = create_user_session(test_session_id, user_1); 380 | 381 | let response = new_game(session, req).await.unwrap(); 382 | assert!(response.status().is_success()); 383 | 384 | // read response 385 | let body = response.body().as_ref().unwrap(); 386 | match body { 387 | Body::Bytes(ref body_bytes) => { 388 | let body_json: serde_json::Value = 389 | serde_json::from_slice(body_bytes.as_ref()).unwrap(); 390 | println!("response body: {:#?}", body_json); 391 | assert_eq!(body_json[SESSION_ID_KEY], test_session_id.to_string()); 392 | } 393 | _ => panic!("Response body is empty"), 394 | } 395 | } 396 | 397 | #[actix_rt::test] 398 | async fn test_find_get() { 399 | let pool = create_conn_pool(); 400 | let req = TestRequest::with_header("content-type", "application/json") 401 | .method(Method::GET) 402 | .app_data(pool.clone()) 403 | .to_http_request(); 404 | 405 | let user_1 = Uuid::new_v4(); 406 | let new_session_id = Uuid::new_v4(); 407 | mock_db_create_new_session(new_session_id); 408 | mock_db_find_existing_game_session(new_session_id, user_1); 409 | 410 | let session = create_user_session(new_session_id, user_1); 411 | 412 | let response = find(session, req).await.unwrap(); 413 | assert!(response.status().is_success()); 414 | println!("response: {:?}", response); 415 | 416 | assert_eq!( 417 | get_body_str(&response.body().as_ref().unwrap()), 418 | new_session_id.to_string() 419 | ); 420 | } 421 | 422 | #[actix_rt::test] 423 | async fn test_join_post() { 424 | let pool = create_conn_pool(); 425 | let req = TestRequest::with_header("content-type", "application/json") 426 | .method(Method::POST) 427 | .app_data(pool.clone()) 428 | .to_http_request(); 429 | 430 | let test_session_id = Uuid::new_v4(); 431 | mock_db_create_new_session(test_session_id); 432 | mock_db_join_game_session(); 433 | 434 | let user_2 = Uuid::new_v4(); 435 | let session = create_user_session(test_session_id, user_2); 436 | 437 | let resp = join(web::Path::from(user_2), session, req).await; 438 | println!("response: {:?}", resp); 439 | assert_eq!(resp.unwrap().status(), http::StatusCode::OK); 440 | } 441 | 442 | #[actix_rt::test] 443 | async fn test_board_get() { 444 | let pool = create_conn_pool(); 445 | let req = TestRequest::with_header("content-type", "application/json") 446 | .method(Method::GET) 447 | .app_data(pool.clone()) 448 | .to_http_request(); 449 | 450 | let user_1 = Uuid::new_v4(); 451 | let new_session_id = Uuid::new_v4(); 452 | let target_board = "------------------------------------------------------"; 453 | mock_db_create_new_session(new_session_id); 454 | mock_db_get_board(target_board); 455 | 456 | let session = create_user_session(new_session_id, user_1); 457 | 458 | let response = board(session, req).await.unwrap(); 459 | 460 | assert!(response.status().is_success()); 461 | println!("response: {:?}", response); 462 | assert_eq!( 463 | get_body_str(&response.body().as_ref().unwrap()), 464 | target_board 465 | ); 466 | } 467 | 468 | #[actix_rt::test] 469 | async fn test_game_state() { 470 | let pool = create_conn_pool(); 471 | let req = TestRequest::with_header("content-type", "application/json") 472 | .method(Method::GET) 473 | .app_data(pool.clone()) 474 | .to_http_request(); 475 | 476 | let user_1 = Uuid::new_v4(); 477 | let user_2 = Uuid::new_v4(); 478 | let new_session_id = Uuid::new_v4(); 479 | let target_board = "----------------------------------------------------OXX"; 480 | mock_db_create_new_session(new_session_id); 481 | mock_db_get_game_state(new_session_id, user_1, user_2, target_board); 482 | 483 | let session = create_user_session(new_session_id, user_1); 484 | 485 | let response = game_state(session, req).await.unwrap(); 486 | 487 | assert!(response.status().is_success()); 488 | println!("response: {:?}", response); 489 | let response_body = &response.body().as_ref().unwrap(); 490 | match response_body { 491 | Body::Bytes(ref body_bytes) => { 492 | let game_state: models::GameState = serde_json::from_slice(body_bytes).unwrap(); 493 | assert_eq!(game_state.board.unwrap(), target_board); 494 | } 495 | _ => panic!("Response body is empty"), 496 | } 497 | } 498 | 499 | #[actix_rt::test] 500 | async fn test_make_move() { 501 | let pool = create_conn_pool(); 502 | let req = TestRequest::with_header("content-type", "application/json") 503 | .method(Method::POST) 504 | .app_data(pool.clone()) 505 | .to_http_request(); 506 | 507 | let test_session_id = Uuid::new_v4(); 508 | let user_1 = Uuid::new_v4(); 509 | let column = 5; 510 | 511 | let board = vec![ 512 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 513 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 514 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 515 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 516 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 517 | vec!['-', '-', '-', 'X', 'X', 'X', '-', '-', '-'], 518 | ]; 519 | 520 | mock_db_create_new_session(test_session_id); 521 | mock_db_join_game_session(); 522 | mock_game_user_move(test_session_id, user_1, utils::arr_to_str(&board)); 523 | 524 | let session = create_user_session(test_session_id, user_1); 525 | 526 | let response = make_move(web::Path::from(column), session, req) 527 | .await 528 | .unwrap(); 529 | 530 | assert!(response.status().is_success()); 531 | println!("response: {:?}", response); 532 | 533 | let body = response.body().as_ref().unwrap(); 534 | match body { 535 | Body::Bytes(ref body_bytes) => { 536 | let game_state: models::GameState = serde_json::from_slice(body_bytes).unwrap(); 537 | assert_eq!(game_state.id, test_session_id.to_string()); 538 | assert_eq!(game_state.board.unwrap(), utils::arr_to_str(&board)); 539 | } 540 | _ => panic!("Response body is empty"), 541 | } 542 | } 543 | } 544 | -------------------------------------------------------------------------------- /server/src/db.rs: -------------------------------------------------------------------------------- 1 | use diesel::connection::SimpleConnection; 2 | use diesel::prelude::*; 3 | use diesel::r2d2::{ConnectionManager, Pool}; 4 | use diesel::result::QueryResult; 5 | use diesel::SqliteConnection; 6 | use dotenv::dotenv; 7 | use std::env; 8 | use std::result::Result; 9 | use std::time::Duration; 10 | use uuid::Uuid; 11 | 12 | pub use crate::models; 13 | use crate::models::{GameState, NewGameState, User}; 14 | pub use crate::schema; 15 | pub use crate::utils; 16 | 17 | #[cfg(test)] 18 | use mocktopus::macros::*; 19 | 20 | #[derive(Debug)] 21 | pub struct ConnectionOptions { 22 | pub enable_wal: bool, 23 | pub enable_foreign_keys: bool, 24 | pub busy_timeout: Option, 25 | } 26 | 27 | impl diesel::r2d2::CustomizeConnection 28 | for ConnectionOptions 29 | { 30 | fn on_acquire(&self, conn: &mut SqliteConnection) -> Result<(), diesel::r2d2::Error> { 31 | (|| { 32 | if self.enable_wal { 33 | conn.batch_execute("PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;")?; 34 | } 35 | if self.enable_foreign_keys { 36 | conn.batch_execute("PRAGMA foreign_keys = ON;")?; 37 | } 38 | if let Some(d) = self.busy_timeout { 39 | conn.batch_execute(&format!("PRAGMA busy_timeout = {};", d.as_millis()))?; 40 | } 41 | Ok(()) 42 | })() 43 | .map_err(diesel::r2d2::Error::QueryError) 44 | } 45 | } 46 | 47 | pub fn create_conn_pool() -> Pool> { 48 | dotenv().ok(); 49 | let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); 50 | Pool::builder() 51 | .max_size(16) 52 | .connection_customizer(Box::new(ConnectionOptions { 53 | enable_wal: true, 54 | enable_foreign_keys: true, 55 | busy_timeout: Some(Duration::from_secs(30)), 56 | })) 57 | .build(ConnectionManager::::new(db_url)) 58 | .unwrap() 59 | } 60 | 61 | pub fn establish_connection() -> SqliteConnection { 62 | dotenv().ok(); 63 | 64 | let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); 65 | SqliteConnection::establish(&database_url) 66 | .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)) 67 | } 68 | 69 | #[cfg_attr(test, mockable)] 70 | pub fn create_new_user(name: &str, color: &str, conn: &SqliteConnection) -> Result { 71 | use super::schema::user::dsl::*; 72 | 73 | let new_user_id = Uuid::new_v4(); 74 | 75 | let new_user = User { 76 | id: new_user_id.to_string(), 77 | user_name: name.to_owned(), 78 | user_color: color.to_owned(), 79 | }; 80 | 81 | let result = diesel::insert_into(user).values(&new_user).execute(conn); 82 | 83 | match result { 84 | Ok(_) => Ok(new_user_id), 85 | Err(e) => Err(format!("Can't create a new user: {:?}", e)), 86 | } 87 | } 88 | 89 | #[cfg_attr(test, mockable)] 90 | pub fn create_new_session(user: &Uuid, conn: &SqliteConnection) -> Result { 91 | use super::schema::game_state::dsl::*; 92 | 93 | let new_session_id = Uuid::new_v4(); 94 | 95 | let new_game = NewGameState { 96 | id: new_session_id.to_string(), 97 | board: Some("------------------------------------------------------".to_string()), //TODO generate the string given board h&w 98 | user_1: Some(user.to_string()), 99 | }; 100 | 101 | let result = diesel::insert_into(game_state) 102 | .values(&new_game) 103 | .execute(conn); 104 | 105 | match result { 106 | Ok(_) => Ok(new_session_id), 107 | Err(e) => Err(format!("Can't create a new session: {:?}", e)), 108 | } 109 | } 110 | 111 | #[cfg_attr(test, mockable)] 112 | pub fn find_existing_game_session(conn: &SqliteConnection) -> Option { 113 | use super::schema::game_state::dsl::*; 114 | 115 | let results = game_state 116 | .filter(user_2.is_null()) 117 | .load::(conn) 118 | .expect("Error loading posts"); 119 | 120 | if !results.is_empty() { 121 | let session = results.into_iter().rev().collect::>()[0].clone(); 122 | Some(session) 123 | } else { 124 | None 125 | } 126 | } 127 | 128 | #[cfg_attr(test, mockable)] 129 | pub fn join_game_session( 130 | session_id: &Uuid, 131 | user2_id: &Uuid, 132 | conn: &SqliteConnection, 133 | ) -> QueryResult { 134 | use super::schema::game_state::dsl::*; 135 | diesel::update(game_state) 136 | .set(user_2.eq(user2_id.to_string())) 137 | .filter(id.eq(session_id.to_string())) 138 | .execute(conn) 139 | } 140 | 141 | #[cfg_attr(test, mockable)] 142 | pub fn get_board(session_id: &Uuid, conn: &SqliteConnection) -> Result { 143 | use super::schema::game_state::dsl::*; 144 | 145 | let results = game_state 146 | .filter(id.eq(session_id.to_string())) 147 | .limit(1) 148 | .load::(conn) 149 | .expect("Error loading game state"); 150 | 151 | let b = results[0].board.as_ref().unwrap(); 152 | Result::Ok(b.to_string()) 153 | } 154 | 155 | #[cfg_attr(test, mockable)] 156 | pub fn update_game_state( 157 | session_id: &Uuid, 158 | user_id: &Uuid, 159 | board_str: &str, 160 | is_winner: bool, 161 | game_over: bool, 162 | conn: &SqliteConnection, 163 | ) -> QueryResult { 164 | use super::schema::game_state::dsl::*; 165 | diesel::update(game_state) 166 | .filter(id.eq(session_id.to_string())) 167 | .set(( 168 | last_user_id.eq(user_id.to_string()), 169 | board.eq(board_str), 170 | winner.eq(is_winner), 171 | ended.eq(game_over), 172 | )) 173 | .execute(conn) 174 | } 175 | 176 | #[cfg_attr(test, mockable)] 177 | pub fn get_user_color(user_id: &Uuid, conn: &SqliteConnection) -> QueryResult { 178 | use super::schema::user::dsl::*; 179 | let res = user 180 | .select(user_color) 181 | .filter(id.eq(user_id.to_string())) 182 | .limit(1) 183 | .load::(conn) 184 | .into_iter() 185 | .collect::>()[0] 186 | .clone(); 187 | Ok(res[0].chars().collect::>()[0]) 188 | } 189 | 190 | #[cfg_attr(test, mockable)] 191 | pub fn get_game_state( 192 | session_id: &Uuid, 193 | conn: &SqliteConnection, 194 | ) -> QueryResult { 195 | use super::schema::game_state::dsl::*; 196 | 197 | let res = game_state 198 | .filter(id.eq(session_id.to_string())) 199 | .limit(1) 200 | .load::(conn) 201 | .expect("Error loading game state"); 202 | Ok(res[0].clone()) 203 | } 204 | 205 | pub fn clean_db(conn: &SqliteConnection) { 206 | use super::schema::game_state::dsl::*; 207 | // use super::schema::user::dsl::*; 208 | diesel::delete(game_state).execute(conn).unwrap(); 209 | // diesel::delete(user) 210 | // .execute(&conn) 211 | // .unwrap(); 212 | } 213 | 214 | #[cfg(test)] 215 | pub mod tests { 216 | use crate::db::{ 217 | create_conn_pool, create_new_session, create_new_user, find_existing_game_session, 218 | get_board, get_game_state, get_user_color, join_game_session, update_game_state, 219 | }; 220 | use std::ops::Deref; 221 | use uuid::Uuid; 222 | 223 | #[test] 224 | pub fn test_get_board() { 225 | let target_board = "------------------------------------------------------".to_owned(); 226 | let conn = create_conn_pool().get().unwrap(); 227 | let session_id = create_new_session(&Uuid::new_v4(), conn.deref()).unwrap(); 228 | let board = get_board(&session_id, conn.deref()).unwrap(); 229 | // println!("{:?}", board.unwrap()); 230 | assert_eq!(board, target_board); 231 | } 232 | 233 | #[test] 234 | pub fn test_find_existing_game_session() { 235 | //clean_db(); 236 | let conn = create_conn_pool().get().unwrap(); 237 | let session_id = create_new_session(&Uuid::new_v4(), conn.deref()).unwrap(); 238 | let gs = find_existing_game_session(conn.deref()).unwrap(); 239 | assert_eq!(session_id.to_string(), gs.id) 240 | } 241 | 242 | #[test] 243 | pub fn test_create_new_session() { 244 | let user = Uuid::new_v4(); 245 | let conn = create_conn_pool().get().unwrap(); 246 | let result = create_new_session(&user, conn.deref()); 247 | match result { 248 | Ok(session_id) => println!("created new session with id: {}", session_id), 249 | Err(error) => { 250 | assert!(false, "{:?}", error); 251 | } 252 | } 253 | } 254 | 255 | #[test] 256 | pub fn test_join_game_session() { 257 | let user = Uuid::new_v4(); 258 | let conn = create_conn_pool().get().unwrap(); 259 | let session_id = create_new_session(&Uuid::new_v4(), conn.deref()).unwrap(); 260 | let updated_records = join_game_session(&session_id, &user, conn.deref()); 261 | assert_eq!(updated_records.unwrap(), 1); 262 | // let _board = get_board(&session_id, conn.deref()); 263 | } 264 | 265 | #[test] 266 | pub fn test_update_game_state() { 267 | let user_id = Uuid::new_v4(); 268 | let conn = create_conn_pool().get().unwrap(); 269 | let session_id = create_new_session(&user_id, conn.deref()).unwrap(); 270 | let new_board = "-X----------------------------------------------------".to_owned(); 271 | let updated_records = update_game_state( 272 | &session_id, 273 | &user_id, 274 | &new_board, 275 | false, 276 | false, 277 | conn.deref(), 278 | ); 279 | assert_eq!(updated_records.unwrap(), 1); 280 | // let board = get_board(&session_id, conn.deref()); 281 | let board = get_game_state(&session_id, conn.deref()).unwrap().board; 282 | assert_eq!(board.unwrap(), new_board); 283 | 284 | let new_board = "-X--X-------------------------------------------------".to_owned(); 285 | let updated_records = update_game_state( 286 | &session_id, 287 | &user_id, 288 | &new_board, 289 | false, 290 | false, 291 | conn.deref(), 292 | ); 293 | assert_eq!(updated_records.unwrap(), 1); 294 | let board = get_game_state(&session_id, conn.deref()).unwrap().board; 295 | assert_eq!(board.unwrap(), new_board); 296 | } 297 | 298 | #[test] 299 | pub fn test_get_user_color() { 300 | let conn = create_conn_pool().get().unwrap(); 301 | 302 | let new_user_id = create_new_user("test-user", "X", conn.deref()).unwrap(); 303 | let color = get_user_color(&new_user_id, conn.deref()).unwrap(); 304 | assert_eq!(color, 'X'); 305 | } 306 | 307 | #[test] 308 | pub fn test_get_game_state() { 309 | let user = Uuid::new_v4(); 310 | let conn = create_conn_pool().get().unwrap(); 311 | let result = create_new_session(&user, conn.deref()); 312 | match result { 313 | Ok(session_id) => { 314 | let gs = get_game_state(&session_id, conn.deref()).unwrap(); 315 | assert_eq!(gs.id, session_id.to_string()); 316 | assert_eq!(gs.user_1.unwrap(), user.to_string()); 317 | assert_eq!(gs.user_2, None); 318 | } 319 | Err(error) => panic!("{}", error.as_str()), 320 | } 321 | } 322 | } 323 | -------------------------------------------------------------------------------- /server/src/game.rs: -------------------------------------------------------------------------------- 1 | pub use crate::db; 2 | pub use crate::models; 3 | pub use crate::utils; 4 | use diesel::SqliteConnection; 5 | use itertools::Itertools; 6 | use uuid::Uuid; 7 | 8 | #[cfg(test)] 9 | use mocktopus::macros::*; 10 | 11 | //---------- Gameplay functions--------------------------------------------------------------------- 12 | pub fn is_winner(board: &[Vec]) -> bool { 13 | let winning_seq_len = 5; 14 | let rows = board; 15 | let cols: &Vec> = &get_columns(board); 16 | let diags_left = &get_diagonals_left(board); 17 | let diags_right = &get_diagonals_right(board); 18 | let lines = vec![rows, cols, diags_left, diags_right]; 19 | let lines_flatten = lines.iter().flat_map(|it| it.iter()); 20 | for line in lines_flatten { 21 | for (color, group) in &line.iter().group_by(|elt| **elt) { 22 | let gr: Vec<&char> = group.collect(); 23 | // println!("{}, {:?}", color, gr); 24 | if color != '-' && gr.len() >= winning_seq_len { 25 | return true; 26 | } 27 | } 28 | } 29 | false 30 | } 31 | 32 | fn get_columns(board: &[Vec]) -> Vec> { 33 | let mut cols: Vec> = vec![vec![' '; board.len()]; board[0].len()]; 34 | for (row_idx, row) in board.iter().enumerate() { 35 | for (col_idx, x) in row.iter().enumerate() { 36 | cols[col_idx][row_idx] = *x; 37 | } 38 | } 39 | cols 40 | } 41 | 42 | fn get_diagonals_left(board: &[Vec]) -> Vec> { 43 | let h = board.len(); 44 | let w = board[0].len(); 45 | let mut diags: Vec> = Vec::new(); 46 | for p in 0..(h + w - 1) { 47 | let mut d: Vec = Vec::new(); 48 | let lower_bound = (p as i8 - h as i8 + 1).max(0) as usize; 49 | let higher_bound = (p as i8 + 1).min(w as i8) as usize; 50 | for col in lower_bound..higher_bound { 51 | let row = (h as i8 - p as i8 + col as i8 - 1) as usize; 52 | d.push(board[row][col]) 53 | } 54 | diags.push(d); 55 | } 56 | diags 57 | } 58 | 59 | fn get_diagonals_right(board: &[Vec]) -> Vec> { 60 | let h = board.len(); 61 | let w = board[0].len(); 62 | let mut diags: Vec> = Vec::new(); 63 | for p in 0..(h + w - 1) { 64 | let mut d: Vec = Vec::new(); 65 | let lower_bound = (p as i8 - h as i8 + 1).max(0) as usize; 66 | let higher_bound = (p as i8 + 1).min(w as i8) as usize; 67 | for col in lower_bound..higher_bound { 68 | let row = (p as i8 - col as i8) as usize; 69 | d.push(board[row][col]) 70 | } 71 | diags.push(d); 72 | } 73 | diags 74 | } 75 | 76 | #[cfg_attr(test, mockable)] 77 | pub fn user_move( 78 | ses_id: Uuid, 79 | user_id: Uuid, 80 | col_num: usize, 81 | conn: &SqliteConnection, 82 | ) -> Result { 83 | //TODO: needs refactoring. should not do db calls 84 | db::get_board(&ses_id, conn).and_then(|s| { 85 | let board = utils::str_to_arr(&s); 86 | do_move(user_id, col_num, &board, conn).and_then(|new_board| { 87 | let board_arr = utils::arr_to_str(&new_board); 88 | let is_winner = is_winner(&new_board); 89 | let game_over = is_winner; 90 | db::update_game_state(&ses_id, &user_id, &board_arr, is_winner, game_over, conn) 91 | .map_err(|err| err.to_string()) 92 | .map(|_| { 93 | //return the updated game state 94 | db::get_game_state(&ses_id, conn).unwrap() 95 | }) 96 | }) 97 | }) 98 | } 99 | 100 | fn do_move( 101 | user_id: Uuid, 102 | col_num: usize, 103 | board: &[Vec], 104 | conn: &SqliteConnection, 105 | ) -> Result>, String> { 106 | if col_num < 1 || col_num > board[0].len() { 107 | return Err(format!( 108 | "There is no column with this number. Max column is: {}", 109 | board[0].len() 110 | )); 111 | } 112 | 113 | let y_curr = board 114 | .iter() 115 | .enumerate() 116 | .filter(|(_, row)| row[col_num - 1] == '-') 117 | .map(|(y, _)| y) 118 | .max(); 119 | match y_curr { 120 | Some(row_num) => { 121 | let color: char = db::get_user_color(&user_id, conn).unwrap(); 122 | let mut new_board = board.to_owned(); 123 | new_board[row_num][col_num - 1] = color; 124 | Ok(new_board) 125 | } 126 | None => Err("This column is full. Please, try another move".to_owned()), 127 | } 128 | } 129 | 130 | #[cfg(test)] 131 | pub mod tests { 132 | use crate::db; 133 | use crate::game::{do_move, get_diagonals_left, get_diagonals_right, is_winner, user_move}; 134 | use crate::utils; 135 | use db::create_conn_pool; 136 | use itertools::Itertools; 137 | use mocktopus::mocking::*; 138 | use std::ops::Deref; 139 | use uuid::Uuid; 140 | 141 | #[test] 142 | pub fn test_is_winner() { 143 | let mut board = vec![ 144 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 145 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 146 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 147 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 148 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 149 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 150 | ]; 151 | assert!(!is_winner(&board)); 152 | 153 | board = vec![ 154 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 155 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 156 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 157 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 158 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 159 | vec!['-', '-', '-', 'X', 'X', 'X', '-', '-', '-'], 160 | ]; 161 | assert!(!is_winner(&board)); 162 | 163 | board = vec![ 164 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 165 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 166 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 167 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 168 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 169 | vec!['-', '-', '-', 'X', 'X', 'X', '-', '-', '-'], 170 | ]; 171 | assert!(is_winner(&board)); 172 | 173 | board = vec![ 174 | vec!['-', '-', '-', '-', '-', 'O', '-', '-', '-'], 175 | vec!['-', '-', '-', '-', '-', 'O', '-', 'X', '-'], 176 | vec!['-', '-', '-', '-', '-', 'O', 'X', '-', '-'], 177 | vec!['-', '-', '-', '-', '-', 'X', '-', '-', '-'], 178 | vec!['-', '-', '-', '-', 'X', 'O', '-', '-', '-'], 179 | vec!['-', '-', '-', 'X', 'X', 'X', '-', '-', '-'], 180 | ]; 181 | assert!(is_winner(&board)); 182 | 183 | board = vec![ 184 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 185 | vec!['-', 'X', '-', '-', '-', 'O', '-', '-', '-'], 186 | vec!['-', '-', 'X', '-', '-', 'O', '-', '-', '-'], 187 | vec!['-', '-', '-', 'X', '-', 'O', '-', '-', '-'], 188 | vec!['-', '-', '-', '-', 'X', 'O', '-', '-', '-'], 189 | vec!['-', '-', '-', 'X', 'X', 'X', '-', '-', '-'], 190 | ]; 191 | assert!(is_winner(&board)); 192 | 193 | board = vec![ 194 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 195 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 196 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 197 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 198 | vec!['-', 'X', 'X', 'X', 'X', 'X', 'X', '-', '-'], 199 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 200 | ]; 201 | assert!(is_winner(&board)); 202 | 203 | board = vec![ 204 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 205 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 206 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 207 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 208 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 209 | vec!['X', 'X', '-', 'X', 'X', 'X', '-', 'X', 'X'], 210 | ]; 211 | assert!(!is_winner(&board)); 212 | 213 | let target_board = vec![ 214 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 215 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 216 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 217 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 218 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 219 | vec!['-', 'X', 'X', '-', '-', '-', '-', '-', '-'], 220 | ]; 221 | 222 | assert!(!is_winner(&target_board)); 223 | } 224 | 225 | #[test] 226 | pub fn test_get_diagonals_left() { 227 | let board = vec![ 228 | vec!['1', '2', '3', '4'], 229 | vec!['A', 'B', 'C', '4'], 230 | vec!['W', 'X', 'Y', 'Z'], 231 | vec!['9', '8', '7', '6'], 232 | ]; 233 | 234 | let target = vec![ 235 | vec!['9'], 236 | vec!['W', '8'], 237 | vec!['A', 'X', '7'], 238 | vec!['1', 'B', 'Y', '6'], 239 | vec!['2', 'C', 'Z'], 240 | vec!['3', '4'], 241 | vec!['4'], 242 | ]; 243 | 244 | let res = get_diagonals_left(&board); 245 | 246 | assert_eq!(res, target) 247 | } 248 | 249 | #[test] 250 | pub fn test_get_diagonals_right() { 251 | let board = vec![ 252 | vec!['1', '2', '3', '4'], 253 | vec!['A', 'B', 'C', '4'], 254 | vec!['W', 'X', 'Y', 'Z'], 255 | vec!['9', '8', '7', '6'], 256 | ]; 257 | 258 | let target = vec![ 259 | vec!['1'], 260 | vec!['A', '2'], 261 | vec!['W', 'B', '3'], 262 | vec!['9', 'X', 'C', '4'], 263 | vec!['8', 'Y', '4'], 264 | vec!['7', 'Z'], 265 | vec!['6'], 266 | ]; 267 | 268 | let res = get_diagonals_right(&board); 269 | 270 | assert_eq!(res, target) 271 | } 272 | 273 | #[test] 274 | pub fn test_group_by() { 275 | let data = vec![1, 3, -2, -2, 1, 0, 1, 2]; 276 | for (key, group) in &data.into_iter().group_by(|elt| *elt >= 0) { 277 | let g = group.collect::>(); 278 | println!("{}, {:?}", key, g); 279 | } 280 | } 281 | 282 | #[test] 283 | pub fn test_do_move() { 284 | let user_id = Uuid::new_v4(); 285 | let conn = create_conn_pool().get().unwrap(); 286 | let board = vec![ 287 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 288 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 289 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 290 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 291 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 292 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 293 | ]; 294 | 295 | let target_board = vec![ 296 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 297 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 298 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 299 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 300 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 301 | vec!['-', '-', '-', '-', '-', '-', 'X', '-', '-'], 302 | ]; 303 | 304 | db::get_user_color.mock_safe(move |_x, _conn| MockResult::Return(Result::Ok('X'))); 305 | let new_board = do_move(user_id, 7, &board, conn.deref()).unwrap(); 306 | assert_eq!(new_board, target_board); 307 | } 308 | 309 | #[test] 310 | pub fn test_do_move_adjacent() { 311 | let user_id = Uuid::new_v4(); 312 | let conn = create_conn_pool().get().unwrap(); 313 | // let user_id = db::create_new_user("test-user".to_string(), "X".to_string(), conn.deref()).unwrap(); 314 | let board = vec![ 315 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 316 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 317 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 318 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 319 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 320 | vec!['-', '-', 'X', '-', '-', '-', '-', '-', '-'], 321 | ]; 322 | 323 | let target_board = vec![ 324 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 325 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 326 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 327 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 328 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 329 | vec!['-', 'X', 'X', '-', '-', '-', '-', '-', '-'], 330 | ]; 331 | 332 | db::get_user_color.mock_safe(move |_x, _conn| MockResult::Return(Result::Ok('X'))); 333 | 334 | let new_board = do_move(user_id, 2, &board, conn.deref()).unwrap(); 335 | assert_eq!(new_board, target_board); 336 | } 337 | 338 | #[test] 339 | pub fn test_do_move_full() { 340 | let user_id = Uuid::new_v4(); 341 | let conn = create_conn_pool().get().unwrap(); 342 | let board = vec![ 343 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 344 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 345 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 346 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 347 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 348 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 349 | ]; 350 | 351 | db::get_user_color.mock_safe(move |_x, _conn| MockResult::Return(Result::Ok('X'))); 352 | 353 | let new_board = do_move(user_id, 2, &board, conn.deref()); 354 | // log:debug!("{:?}", new_board); 355 | assert_eq!( 356 | new_board, 357 | Err("This column is full. Please, try another move".to_string()) 358 | ); 359 | } 360 | 361 | #[test] 362 | pub fn test_user_move() { 363 | let conn = create_conn_pool().get().unwrap(); 364 | let user_id = db::create_new_user("test-user", "X", conn.deref()).unwrap(); 365 | let new_session_id = db::create_new_session(&user_id, conn.deref()).unwrap(); 366 | 367 | let board = vec![ 368 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 369 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 370 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 371 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 372 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 373 | vec!['-', '-', 'X', '-', '-', '-', '-', '-', '-'], 374 | ]; 375 | 376 | let res = db::update_game_state( 377 | &new_session_id, 378 | &user_id, 379 | &utils::arr_to_str(&board), 380 | false, 381 | false, 382 | conn.deref(), 383 | ); 384 | 385 | assert_eq!(res.unwrap(), 1); 386 | 387 | let tmp_board = db::get_board(&new_session_id, conn.deref()).unwrap(); 388 | assert_eq!(tmp_board, utils::arr_to_str(&board)); 389 | 390 | let target_board = vec![ 391 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 392 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 393 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 394 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 395 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 396 | vec!['-', 'X', 'X', '-', '-', '-', '-', '-', '-'], 397 | ]; 398 | 399 | let new_state = user_move(new_session_id, user_id, 2, conn.deref()).unwrap(); 400 | assert_eq!(new_state.board.unwrap(), utils::arr_to_str(&target_board)); 401 | assert_eq!(new_state.last_user_id.unwrap(), user_id.to_string()); 402 | assert_eq!(new_state.winner, false); 403 | } 404 | 405 | #[test] 406 | pub fn test_user_move_win_column() { 407 | let conn = create_conn_pool().get().unwrap(); 408 | let user_id = db::create_new_user("test-user", "X", conn.deref()).unwrap(); 409 | let new_session_id = db::create_new_session(&user_id, conn.deref()).unwrap(); 410 | let board = vec![ 411 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 412 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 413 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 414 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 415 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 416 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 417 | ]; 418 | let board_str = utils::arr_to_str(&board); 419 | let _ = db::update_game_state( 420 | &new_session_id, 421 | &user_id, 422 | &board_str, 423 | false, 424 | false, 425 | conn.deref(), 426 | ); 427 | let target_board = vec![ 428 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 429 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 430 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 431 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 432 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 433 | vec!['-', 'X', '-', '-', '-', '-', '-', '-', '-'], 434 | ]; 435 | 436 | let new_state = user_move(new_session_id, user_id, 2, conn.deref()).unwrap(); 437 | assert_eq!(new_state.board.unwrap(), utils::arr_to_str(&target_board)); 438 | assert_eq!(new_state.last_user_id.unwrap(), user_id.to_string()); 439 | assert_eq!(new_state.winner, true); 440 | assert_eq!(new_state.ended, true); 441 | } 442 | } 443 | -------------------------------------------------------------------------------- /server/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(test, feature(proc_macro_hygiene))] 2 | #[macro_use] 3 | extern crate diesel; 4 | extern crate dotenv; 5 | 6 | use actix_files as fs; 7 | use actix_session::CookieSession; 8 | use actix_web::{web, App, HttpServer}; 9 | 10 | pub mod api; 11 | pub mod db; 12 | pub mod game; 13 | pub mod models; 14 | pub mod schema; 15 | pub mod utils; 16 | 17 | #[actix_web::main] 18 | pub async fn start_server() -> std::io::Result<()> { 19 | HttpServer::new(|| { 20 | App::new() 21 | .app_data(db::create_conn_pool()) 22 | .wrap(CookieSession::signed(&[0; 32]).secure(false)) 23 | .service( 24 | web::scope("/api") 25 | .service( 26 | web::resource("/register/{user_name}/{user_color}") 27 | .route(web::post().to(api::register)), 28 | ) 29 | .service(web::resource("/new").route(web::get().to(api::new_game))) 30 | .service(web::resource("/find").route(web::get().to(api::find))) 31 | .service( 32 | web::resource("/join/{game_session_id}").route(web::post().to(api::join)), 33 | ) 34 | .service(web::resource("/game-state").route(web::get().to(api::game_state))) 35 | .service( 36 | web::resource("/make-move/{column}").route(web::post().to(api::make_move)), 37 | ), 38 | ) 39 | .service(fs::Files::new("/", "./static").index_file("index.html")) 40 | }) 41 | .bind("127.0.0.1:8088")? 42 | .run() 43 | .await 44 | } 45 | -------------------------------------------------------------------------------- /server/src/main.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | // main function logic moved to the lib.rs so that we can have integration tests in /tests/* 3 | let _result = connect5_rust::start_server(); 4 | } 5 | -------------------------------------------------------------------------------- /server/src/models.rs: -------------------------------------------------------------------------------- 1 | use super::schema::game_state; 2 | use super::schema::user; 3 | use serde::{Deserialize, Serialize}; 4 | 5 | #[derive(Serialize, Deserialize, Default, Queryable, Insertable, Debug, Clone)] 6 | #[table_name = "user"] 7 | pub struct User { 8 | pub id: String, 9 | pub user_name: String, 10 | pub user_color: String, 11 | } 12 | 13 | #[derive(Serialize, Deserialize, Queryable, Debug, Clone)] 14 | pub struct GameState { 15 | pub id: String, 16 | pub board: Option, 17 | pub user_1: Option, 18 | pub user_2: Option, 19 | pub winner: bool, 20 | pub last_user_id: Option, 21 | pub last_user_color: Option, 22 | pub ended: bool, 23 | } 24 | 25 | #[derive(Deserialize, Serialize, Insertable)] 26 | #[table_name = "game_state"] 27 | pub struct NewGameState { 28 | pub id: String, 29 | pub board: Option, 30 | pub user_1: Option, 31 | } 32 | -------------------------------------------------------------------------------- /server/src/schema.rs: -------------------------------------------------------------------------------- 1 | table! { 2 | game_state (id) { 3 | id -> Text, 4 | board -> Nullable, 5 | user_1 -> Nullable, 6 | user_2 -> Nullable, 7 | winner -> Bool, 8 | last_user_id -> Nullable, 9 | last_user_color -> Nullable, 10 | ended -> Bool, 11 | } 12 | } 13 | 14 | table! { 15 | user (id) { 16 | id -> Text, 17 | user_name -> Text, 18 | user_color -> Text, 19 | } 20 | } 21 | 22 | allow_tables_to_appear_in_same_query!(game_state, user,); 23 | -------------------------------------------------------------------------------- /server/src/utils.rs: -------------------------------------------------------------------------------- 1 | pub fn str_to_arr(board_str: &str) -> Vec> { 2 | const ROWS: usize = 6; //TODO: make them parameters 3 | const COLUMNS: usize = 9; 4 | 5 | let mut board_arr: Vec> = Vec::new(); 6 | 7 | for y in 0..ROWS { 8 | let first_idx = y * COLUMNS; 9 | let row = board_str[first_idx..(first_idx + COLUMNS)] 10 | .chars() 11 | .collect::>(); 12 | board_arr.push(row); 13 | } 14 | board_arr 15 | } 16 | 17 | pub fn arr_to_str(board: &[Vec]) -> String { 18 | board.iter().flatten().collect::() 19 | } 20 | 21 | #[cfg(test)] 22 | pub mod tests { 23 | use super::*; 24 | 25 | #[test] 26 | pub fn test_str_to_arr() { 27 | let s = String::from("-----------------------------------------------X------"); 28 | let arr = str_to_arr(s.as_str()); 29 | 30 | let target = vec![ 31 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 32 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 33 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 34 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 35 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 36 | vec!['-', '-', 'X', '-', '-', '-', '-', '-', '-'], 37 | ]; 38 | assert_eq!(arr, target) 39 | } 40 | 41 | #[test] 42 | pub fn test_str_to_arr_2() { 43 | let s = String::from("---------------------------------------------X--------"); 44 | let arr = str_to_arr(s.as_str()); 45 | 46 | let target = vec![ 47 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 48 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 49 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 50 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 51 | vec!['-', '-', '-', '-', '-', '-', '-', '-', '-'], 52 | vec!['X', '-', '-', '-', '-', '-', '-', '-', '-'], 53 | ]; 54 | assert_eq!(arr, target) 55 | } 56 | 57 | #[test] 58 | pub fn test_arr_to_str() { 59 | let s = String::from("123456789123456789123456789123456789123456789123456789"); 60 | assert_eq!(arr_to_str(&str_to_arr(&s)), s); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /server/tests/test_server.rs: -------------------------------------------------------------------------------- 1 | #[cfg(test)] 2 | pub mod tests { 3 | use actix_session::CookieSession; 4 | use actix_web::{test, web, App, HttpMessage, ResponseError}; 5 | use connect5_rust::models::{GameState, User}; 6 | use connect5_rust::{api, db}; 7 | use serde_json::Value; 8 | 9 | const USER_ID_KEY: &str = "user_id"; 10 | const USER_NAME_KEY: &str = "user_name"; 11 | const SESSION_ID_KEY: &str = "session_id"; 12 | 13 | #[actix_rt::test] 14 | async fn test_register_user_api() { 15 | let srv = test::start(|| { 16 | App::new() 17 | .app_data(db::create_conn_pool()) 18 | .wrap(CookieSession::signed(&[0; 32]).secure(false)) 19 | .service( 20 | web::scope("/api").service( 21 | web::resource("/register/{user_name}/{user_color}") 22 | .route(web::post().to(api::register)), 23 | ), 24 | ) 25 | }); 26 | 27 | let mut response = srv 28 | .post("/api/register/test_user_name/X") 29 | .send() 30 | .await 31 | .unwrap(); 32 | println!("response: {:#?}", response); 33 | assert!(response.status().is_success()); 34 | 35 | // read response 36 | let body_bytes = response.body().await.unwrap(); 37 | let body_json: serde_json::Value = serde_json::from_slice(body_bytes.as_ref()).unwrap(); 38 | println!("response body: {:#?}", body_json); 39 | assert_eq!(body_json[USER_NAME_KEY], "test_user_name"); 40 | assert_ne!(body_json[USER_ID_KEY].to_string(), "Null"); 41 | } 42 | 43 | #[actix_rt::test] 44 | async fn test_game_state_api() { 45 | let srv = test::start(|| { 46 | App::new() 47 | .app_data(db::create_conn_pool()) 48 | .wrap(CookieSession::signed(&[0; 32]).path("/").secure(false)) 49 | .service( 50 | web::scope("/api") 51 | .service( 52 | web::resource("/register/{user_name}/{user_color}") 53 | .route(web::post().to(api::register)), 54 | ) 55 | .service(web::resource("/new").route(web::get().to(api::new_game))) 56 | .service( 57 | web::resource("/game-state").route(web::get().to(api::game_state)), 58 | ), 59 | ) 60 | }); 61 | 62 | let mut response = srv 63 | .post("/api/register/test_user_name/X") 64 | .send() 65 | .await 66 | .unwrap(); 67 | println!("response: {:#?}", response); 68 | assert!(response.status().is_success()); 69 | // read response 70 | let body_bytes = response.body().await.unwrap(); 71 | let user_1: User = serde_json::from_slice(body_bytes.as_ref()).unwrap(); 72 | 73 | //get the session cookie returned in the response 74 | let mut cookie = response.cookie("actix-session").unwrap(); 75 | 76 | response = srv.get("/api/new").cookie(cookie).send().await.unwrap(); 77 | 78 | println!("response: {:#?}", response); 79 | assert!(response.status().is_success()); 80 | 81 | let body_bytes = response.body().await.unwrap(); 82 | let session_id_json: Value = serde_json::from_slice(body_bytes.as_ref()).unwrap(); 83 | 84 | cookie = response.cookie("actix-session").unwrap(); 85 | response = srv 86 | .get("/api/game-state") 87 | .cookie(cookie) 88 | .send() 89 | .await 90 | .unwrap(); 91 | println!("response: {:#?}", response); 92 | assert!(response.status().is_success()); 93 | 94 | // read response 95 | let body_bytes = response.body().await.unwrap(); 96 | let game_state: GameState = serde_json::from_slice(body_bytes.as_ref()).unwrap(); 97 | println!("response body: {:#?}", game_state); 98 | assert_eq!(game_state.user_1.unwrap(), user_1.id); 99 | assert_eq!( 100 | game_state.board.unwrap(), 101 | "------------------------------------------------------".to_string() 102 | ); 103 | assert_eq!(game_state.id, session_id_json[SESSION_ID_KEY]); 104 | } 105 | 106 | #[actix_rt::test] 107 | async fn test_new_api() { 108 | todo!() 109 | } 110 | 111 | #[actix_rt::test] 112 | async fn test_find_api() { 113 | todo!() 114 | } 115 | 116 | #[actix_rt::test] 117 | async fn test_join_api() { 118 | todo!() 119 | } 120 | 121 | #[actix_rt::test] 122 | async fn test_make_move_api() { 123 | let srv = test::start(|| { 124 | App::new() 125 | .app_data(db::create_conn_pool()) 126 | .wrap(CookieSession::signed(&[0; 32]).path("/").secure(false)) 127 | .service( 128 | web::scope("/api") 129 | .service( 130 | web::resource("/register/{user_name}/{user_color}") 131 | .route(web::post().to(api::register)), 132 | ) 133 | .service(web::resource("/new").route(web::get().to(api::new_game))) 134 | .service(web::resource("/game-state").route(web::get().to(api::game_state))) 135 | .service( 136 | web::resource("/make-move/{column}") 137 | .route(web::post().to(api::make_move)), 138 | ), 139 | ) 140 | }); 141 | 142 | let mut response = srv 143 | .post("/api/register/test_user_name/X") 144 | .send() 145 | .await 146 | .unwrap(); 147 | println!("response: {:#?}", response); 148 | assert!(response.status().is_success()); 149 | // read response 150 | let body_bytes = response.body().await.unwrap(); 151 | let user_1: User = serde_json::from_slice(body_bytes.as_ref()).unwrap(); 152 | 153 | //get the session cookie returned in the response 154 | let mut cookie = response.cookie("actix-session").unwrap(); 155 | 156 | response = srv.get("/api/new").cookie(cookie).send().await.unwrap(); 157 | 158 | println!("response: {:#?}", response); 159 | assert!(response.status().is_success()); 160 | 161 | let body_bytes = response.body().await.unwrap(); 162 | let session_id_json: Value = serde_json::from_slice(body_bytes.as_ref()).unwrap(); 163 | 164 | cookie = response.cookie("actix-session").unwrap(); 165 | response = srv 166 | .get("/api/game-state") 167 | .cookie(cookie.clone()) 168 | .send() 169 | .await 170 | .unwrap(); 171 | println!("response: {:#?}", response); 172 | assert!(response.status().is_success()); 173 | 174 | // read response 175 | let body_bytes = response.body().await.unwrap(); 176 | let game_state: GameState = serde_json::from_slice(body_bytes.as_ref()).unwrap(); 177 | println!("response body: {:#?}", game_state); 178 | assert_eq!(game_state.user_1.unwrap(), user_1.id); 179 | assert_eq!( 180 | game_state.board.unwrap(), 181 | "------------------------------------------------------".to_string() 182 | ); 183 | assert_eq!(game_state.id, session_id_json[SESSION_ID_KEY]); 184 | 185 | response = srv 186 | .post("/api/make-move/7") 187 | .cookie(cookie) 188 | .send() 189 | .await 190 | .unwrap(); 191 | println!("response: {:#?}", response); 192 | let body_bytes = response.body().await; 193 | 194 | match &body_bytes { 195 | Ok(bytes) => { 196 | println!("response content: {:#?}", bytes); 197 | } 198 | Err(err) => { 199 | println!("response Error: {:#?}", err.error_response()); 200 | } 201 | } 202 | 203 | assert!(response.status().is_success()); 204 | let game_state: GameState = serde_json::from_slice(body_bytes.unwrap().as_ref()).unwrap(); 205 | assert_eq!( 206 | game_state.board.unwrap(), 207 | "---------------------------------------------------X--".to_string() 208 | ); 209 | } 210 | 211 | #[actix_rt::test] 212 | async fn test_board_api() { 213 | todo!() 214 | } 215 | } 216 | --------------------------------------------------------------------------------