diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 50910bd..0000000 --- a/.appveyor.yml +++ /dev/null @@ -1,11 +0,0 @@ -install: - - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - if not defined RUSTFLAGS rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --locked diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ffc462f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +.idea +.github +pkg +target +dist +**/node_modules +tests +Dockerfile diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 7a91325..0000000 --- a/.travis.yml +++ /dev/null @@ -1,69 +0,0 @@ -language: rust -sudo: false - -cache: cargo - -matrix: - include: - - # Builds with wasm-pack. - - rust: beta - env: RUST_BACKTRACE=1 - addons: - firefox: latest - chrome: stable - before_script: - - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) - - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) - - cargo install-update -a - - curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh -s -- -f - script: - - cargo generate --git . --name testing - # Having a broken Cargo.toml (in that it has curlies in fields) anywhere - # in any of our parent dirs is problematic. - - mv Cargo.toml Cargo.toml.tmpl - - cd testing - - wasm-pack build - - wasm-pack test --chrome --firefox --headless - - # Builds on nightly. - - rust: nightly - env: RUST_BACKTRACE=1 - before_script: - - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) - - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) - - cargo install-update -a - - rustup target add wasm32-unknown-unknown - script: - - cargo generate --git . --name testing - - mv Cargo.toml Cargo.toml.tmpl - - cd testing - - cargo check - - cargo check --target wasm32-unknown-unknown - - cargo check --no-default-features - - cargo check --target wasm32-unknown-unknown --no-default-features - - cargo check --no-default-features --features console_error_panic_hook - - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook - - cargo check --no-default-features --features "console_error_panic_hook wee_alloc" - - cargo check --target wasm32-unknown-unknown --no-default-features --features "console_error_panic_hook wee_alloc" - - # Builds on beta. - - rust: beta - env: RUST_BACKTRACE=1 - before_script: - - (test -x $HOME/.cargo/bin/cargo-install-update || cargo install cargo-update) - - (test -x $HOME/.cargo/bin/cargo-generate || cargo install --vers "^0.2" cargo-generate) - - cargo install-update -a - - rustup target add wasm32-unknown-unknown - script: - - cargo generate --git . --name testing - - mv Cargo.toml Cargo.toml.tmpl - - cd testing - - cargo check - - cargo check --target wasm32-unknown-unknown - - cargo check --no-default-features - - cargo check --target wasm32-unknown-unknown --no-default-features - - cargo check --no-default-features --features console_error_panic_hook - - cargo check --target wasm32-unknown-unknown --no-default-features --features console_error_panic_hook - # Note: no enabling the `wee_alloc` feature here because it requires - # nightly for now. diff --git a/Cargo.toml b/Cargo.toml index 7217af9..30ee4ed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,47 +1,8 @@ [package] -name = "rust-wasm" +name = "rust-wasm-pong" version = "0.1.0" authors = ["Thilo Behnke "] edition = "2018" [workspace] -members = ["pong", "server"] - -[lib] -crate-type = ["cdylib", "rlib"] - -[dependencies.web-sys] -version = "0.3" -features = [ - "console", -] - -[features] -default = ["console_error_panic_hook"] - -[dependencies] -wasm-bindgen = {version = "0.2.63", features = ["serde-serialize"]} -serde = { version = "1.0", features = ["derive"] } -serde_json = { version = "1.0.79" } -pong = { path = "pong", version = "0.1.0" } - -# The `console_error_panic_hook` crate provides better debugging of panics by -# logging them with `console.error`. This is great for development, but requires -# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for -# code size when deploying. -console_error_panic_hook = { version = "0.1.6", optional = true } - -# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size -# compared to the default allocator's ~10K. It is slower than the default -# allocator, however. -# -# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. -wee_alloc = { version = "0.4.5", optional = true } - -[dev-dependencies] -wasm-bindgen-test = "0.3.13" -rstest = "0.12.0" - -[profile.release] -# Tell `rustc` to optimize for small code size. -opt-level = "s" +members = ["client/wasm", "pong", "server"] diff --git a/LICENSE_APACHE b/LICENSE_APACHE deleted file mode 100644 index 1b5ec8b..0000000 --- a/LICENSE_APACHE +++ /dev/null @@ -1,176 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS diff --git a/LICENSE_MIT b/LICENSE_MIT deleted file mode 100644 index 5c85c0c..0000000 --- a/LICENSE_MIT +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2018 Thilo Behnke - -Permission is hereby granted, free of charge, to any -person obtaining a copy of this software and associated -documentation files (the "Software"), to deal in the -Software without restriction, including without -limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software -is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice -shall be included in all copies or substantial portions -of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF -ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED -TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A -PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT -SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR -IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index 1e4617a..0000000 --- a/README.md +++ /dev/null @@ -1,69 +0,0 @@ -
- -

wasm-pack-template

- - A template for kick starting a Rust and WebAssembly project using wasm-pack. - -

- Build Status -

- -

- Tutorial - | - Chat -

- - Built with 🦀🕸 by The Rust and WebAssembly Working Group -
- -## About - -[**📚 Read this template tutorial! 📚**][template-docs] - -This template is designed for compiling Rust libraries into WebAssembly and -publishing the resulting package to NPM. - -Be sure to check out [other `wasm-pack` tutorials online][tutorials] for other -templates and usages of `wasm-pack`. - -[tutorials]: https://rustwasm.github.io/docs/wasm-pack/tutorials/index.html -[template-docs]: https://rustwasm.github.io/docs/wasm-pack/tutorials/npm-browser-packages/index.html - -## 🚴 Usage - -### 🐑 Use `cargo generate` to Clone this Template - -[Learn more about `cargo generate` here.](https://github.com/ashleygwilliams/cargo-generate) - -``` -cargo generate --git https://github.com/rustwasm/wasm-pack-template.git --name my-project -cd my-project -``` - -### 🛠️ Build with `wasm-pack build` - -``` -wasm-pack build -``` - -### 🔬 Test in Headless Browsers with `wasm-pack test` - -``` -wasm-pack test --headless --firefox -``` - -### 🎁 Publish to NPM with `wasm-pack publish` - -``` -wasm-pack publish -``` - -## 🔋 Batteries Included - -* [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen) for communicating - between WebAssembly and JavaScript. -* [`console_error_panic_hook`](https://github.com/rustwasm/console_error_panic_hook) - for logging panic messages to the developer console. -* [`wee_alloc`](https://github.com/rustwasm/wee_alloc), an allocator optimized - for small code size. diff --git a/client/.dockerignore b/client/.dockerignore new file mode 100644 index 0000000..4ef74f4 --- /dev/null +++ b/client/.dockerignore @@ -0,0 +1,6 @@ +pkg +tests +dist +node_modules +Dockerfile +.dockerignore diff --git a/client/Dockerfile b/client/Dockerfile new file mode 100644 index 0000000..e4c393b --- /dev/null +++ b/client/Dockerfile @@ -0,0 +1,33 @@ +FROM rust:latest as rust_build_stage + +RUN apt-get update && apt-get upgrade -y +RUN apt-get install curl + +RUN curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh + +RUN mkdir -p /build/client/wasm +ADD ./pong /build/pong +ADD ./client/wasm /build/client/wasm +WORKDIR /build/client/wasm +RUN wasm-pack build + +FROM node:12 as www_build_stage + +RUN mkdir /build + +ADD ./client/www /build/www +RUN ls /build/www +RUN mkdir /build/www/node_modules +WORKDIR /build/www + +COPY --from=rust_build_stage /build/client/wasm/pkg/ /build/wasm/pkg/ + +RUN npm install +RUN npm run build + +FROM nginx:latest + +COPY --from=www_build_stage /build/www/dist/ /usr/share/nginx/pong/web + +COPY ./client/nginx/default.conf /etc/nginx/conf.d/default.conf +COPY ./client/nginx/nginx.conf /etc/nginx/nginx.conf diff --git a/client/nginx/default.conf b/client/nginx/default.conf new file mode 100644 index 0000000..44ce7e4 --- /dev/null +++ b/client/nginx/default.conf @@ -0,0 +1,37 @@ +server { + listen 80; + listen [::]:80; + + root /usr/share/nginx; + + location = / { + return 301 /pong/web; + } + + location /pong/web/ { + try_files $uri $uri/ /index.html; + } + + location /pong/api/ { + proxy_pass http://api_server/; + + proxy_redirect off; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Host $server_name; + } + + location /pong/ws { + proxy_pass http://api_server/ws; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Host $host; + } + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root /usr/share/nginx/html; + } +} diff --git a/client/nginx/nginx.conf b/client/nginx/nginx.conf new file mode 100644 index 0000000..887f8af --- /dev/null +++ b/client/nginx/nginx.conf @@ -0,0 +1,45 @@ + +user nginx; +worker_processes auto; + +error_log /var/log/nginx/error.log notice; +pid /var/run/nginx.pid; + + +events { + worker_connections 1024; +} + + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + + log_format main '$remote_addr - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" ' + '"$http_user_agent" "$http_x_forwarded_for"'; + + access_log /var/log/nginx/access.log main; + + sendfile on; + #tcp_nopush on; + + keepalive_timeout 65; + + #gzip on; + + include /etc/nginx/conf.d/*.conf; + + map $http_upgrade $connection_upgrade { + default upgrade; + '' close; + } + + upstream api_server { + server localhost:4000; + } + + upstream web_client { + server localhost:8080; + } +} diff --git a/client/wasm/.dockerignore b/client/wasm/.dockerignore new file mode 100644 index 0000000..ceb4432 --- /dev/null +++ b/client/wasm/.dockerignore @@ -0,0 +1,2 @@ +pkg +tests diff --git a/client/wasm/Cargo.toml b/client/wasm/Cargo.toml new file mode 100644 index 0000000..84a5e2b --- /dev/null +++ b/client/wasm/Cargo.toml @@ -0,0 +1,44 @@ +[package] +name = "rust-wasm" +version = "0.1.0" +authors = ["Thilo Behnke "] +edition = "2018" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies.web-sys] +version = "0.3" +features = [ + "console", +] + +[features] +default = ["console_error_panic_hook"] + +[dependencies] +wasm-bindgen = {version = "0.2.63", features = ["serde-serialize"]} +serde = { version = "1.0", features = ["derive"] } +serde_json = { version = "1.0.79" } +pong = { path = "../../pong", version = "0.1.0" } + +# The `console_error_panic_hook` crate provides better debugging of panics by +# logging them with `console.error`. This is great for development, but requires +# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for +# code size when deploying. +console_error_panic_hook = { version = "0.1.6", optional = true } + +# `wee_alloc` is a tiny allocator for wasm that is only ~1K in code size +# compared to the default allocator's ~10K. It is slower than the default +# allocator, however. +# +# Unfortunately, `wee_alloc` requires nightly Rust when targeting wasm for now. +wee_alloc = { version = "0.4.5", optional = true } + +[dev-dependencies] +wasm-bindgen-test = "0.3.13" +rstest = "0.12.0" + +[profile.release] +# Tell `rustc` to optimize for small code size. +opt-level = "s" diff --git a/src/lib.rs b/client/wasm/src/lib.rs similarity index 100% rename from src/lib.rs rename to client/wasm/src/lib.rs diff --git a/src/utils.rs b/client/wasm/src/utils.rs similarity index 100% rename from src/utils.rs rename to client/wasm/src/utils.rs diff --git a/tests/web.rs b/client/wasm/tests/web.rs similarity index 100% rename from tests/web.rs rename to client/wasm/tests/web.rs diff --git a/www/.bin/create-wasm-app.js b/client/www/.bin/create-wasm-app.js similarity index 100% rename from www/.bin/create-wasm-app.js rename to client/www/.bin/create-wasm-app.js diff --git a/client/www/.dockerignore b/client/www/.dockerignore new file mode 100644 index 0000000..1b7d195 --- /dev/null +++ b/client/www/.dockerignore @@ -0,0 +1,3 @@ +.bin +dist +node_modules diff --git a/www/.gitignore b/client/www/.gitignore similarity index 100% rename from www/.gitignore rename to client/www/.gitignore diff --git a/www/.travis.yml b/client/www/.travis.yml similarity index 100% rename from www/.travis.yml rename to client/www/.travis.yml diff --git a/www/LICENSE-APACHE b/client/www/LICENSE-APACHE similarity index 100% rename from www/LICENSE-APACHE rename to client/www/LICENSE-APACHE diff --git a/www/LICENSE-MIT b/client/www/LICENSE-MIT similarity index 100% rename from www/LICENSE-MIT rename to client/www/LICENSE-MIT diff --git a/www/README.md b/client/www/README.md similarity index 100% rename from www/README.md rename to client/www/README.md diff --git a/www/bootstrap.js b/client/www/bootstrap.js similarity index 100% rename from www/bootstrap.js rename to client/www/bootstrap.js diff --git a/www/index.html b/client/www/index.html similarity index 98% rename from www/index.html rename to client/www/index.html index bce07fb..7e2456e 100644 --- a/www/index.html +++ b/client/www/index.html @@ -63,7 +63,7 @@
- +
diff --git a/www/index.js b/client/www/index.js similarity index 91% rename from www/index.js rename to client/www/index.js index 3711280..020d6ee 100644 --- a/www/index.js +++ b/client/www/index.js @@ -1,4 +1,4 @@ -import { FieldWrapper, GameObject } from "wasm-app"; +import { FieldWrapper } from "wasm-app"; const GRID_COLOR = "#CCCCCC"; @@ -181,7 +181,7 @@ window.WASM_PONG.height = height window.WASM_PONG.createOnlineSession = () => { resetRequested = true; - fetch("http://localhost:4000/create_session", {method: 'POST'}).then(res => res.json()).then(({data: session}) => { + fetch("/pong/api/create_session", {method: 'POST'}).then(res => res.json()).then(({data: session}) => { console.log("Created session:") console.log(session) networkSession = session.session @@ -191,7 +191,7 @@ window.WASM_PONG.createOnlineSession = () => { session_display_tag.style.display = 'block'; session_display_tag.innerHTML = JSON.stringify(session) - websocket = new WebSocket(`ws://localhost:4000/ws?session_id=${session.session.hash}&connection_type=host`) + websocket = new WebSocket(`ws://${location.host}/pong/ws?session_id=${session.session.hash}&connection_type=host`) websocket.onmessage = (event) => { addEvents(event); } @@ -210,8 +210,12 @@ window.WASM_PONG.joinOnlineSession = () => { return; } - const sessionId = document.getElementById('join-online-input').value - fetch(`http://localhost:4000/join_session`, {method: 'POST', body: JSON.stringify({session_id: sessionId})}).then(res => res.json()).then(({data: session}) => { + const sessionId = document.getElementById('join-online-input').value; + executeJoinSession(sessionId); +} + +const executeJoinSession = (sessionId) => { + fetch(`/pong/api/join_session`, {method: 'POST', body: JSON.stringify({session_id: sessionId})}).then(res => res.json()).then(({data: session}) => { console.log("Joined session:") console.log(session); networkSession = session.session @@ -223,7 +227,7 @@ window.WASM_PONG.joinOnlineSession = () => { // Field will be instrumented by only drawing the objects for the peer, e.g. collision detection will happen at the host. field = null; - websocket = new WebSocket(`ws://localhost:4000/ws?session_id=${session.session.hash}&connection_type=peer`) + websocket = new WebSocket(`ws://${location.host}/pong/ws?session_id=${session.session.hash}&connection_type=peer`) websocket.onmessage = (event) => { addEvents(event); } @@ -252,8 +256,8 @@ const addEvents = wsEvent => { gameEvents.forEach(gameEvent => { const deserialized = {...gameEvent, msg: JSON.parse(gameEvent.msg)}; events.push(deserialized); - events.slice(events.length - 100, events.length) }) + events = events.slice(events.length - 100, events.length) } window.WASM_PONG.pauseGame = () => { @@ -371,3 +375,9 @@ const getInputActions = () => { listenToKeys(); render(JSON.parse(field.objects())); requestAnimationFrame(renderLoop); + +const queryParams = location.search ? location.search.slice(1).split("&").map(it => it.split("=")) : []; +const joinSession = queryParams.find(([name,]) => name === "join_session"); +if (joinSession) { + executeJoinSession(joinSession[1]) +} diff --git a/www/package-lock.json b/client/www/package-lock.json similarity index 99% rename from www/package-lock.json rename to client/www/package-lock.json index 2ae43e2..b929ae9 100644 --- a/www/package-lock.json +++ b/client/www/package-lock.json @@ -9,7 +9,7 @@ "version": "0.1.0", "license": "(MIT OR Apache-2.0)", "dependencies": { - "wasm-app": "file:../pkg" + "wasm-app": "file:../wasm/pkg" }, "bin": { "create-wasm-app": ".bin/create-wasm-app.js" @@ -23,6 +23,11 @@ } }, "../pkg": { + "name": "rust-wasm", + "version": "0.1.0", + "extraneous": true + }, + "../wasm/pkg": { "name": "rust-wasm", "version": "0.1.0" }, @@ -6579,7 +6584,7 @@ "dev": true }, "node_modules/wasm-app": { - "resolved": "../pkg", + "resolved": "../wasm/pkg", "link": true }, "node_modules/watchpack": { @@ -12574,7 +12579,7 @@ "dev": true }, "wasm-app": { - "version": "file:../pkg" + "version": "file:../wasm/pkg" }, "watchpack": { "version": "1.6.1", diff --git a/www/package.json b/client/www/package.json similarity index 91% rename from www/package.json rename to client/www/package.json index 5cd9cc4..ee58f6c 100644 --- a/www/package.json +++ b/client/www/package.json @@ -8,7 +8,7 @@ }, "scripts": { "build": "webpack --config webpack.config.js", - "start": "webpack-dev-server --host '0.0.0.0'" + "start": "webpack-dev-server" }, "repository": { "type": "git", @@ -27,7 +27,7 @@ }, "homepage": "https://github.com/rustwasm/create-wasm-app#readme", "dependencies": { - "wasm-app": "file:../pkg" + "wasm-app": "file:../wasm/pkg" }, "devDependencies": { "hello-wasm-pack": "^0.1.0", diff --git a/www/webpack.config.js b/client/www/webpack.config.js similarity index 58% rename from www/webpack.config.js rename to client/www/webpack.config.js index 80ad814..14011a9 100644 --- a/www/webpack.config.js +++ b/client/www/webpack.config.js @@ -11,4 +11,15 @@ module.exports = { plugins: [ new CopyWebpackPlugin(['index.html']) ], + devServer: { + publicPath: '/pong/web/', + openPage: 'pong/web/', + open: true, + proxy: { + '/pong/api': { + target: 'http://localhost:4000', + pathRewrite: { '^/pong/api': '' } + } + } + }, }; diff --git a/server/docker-compose.yml b/docker-compose.yml similarity index 55% rename from server/docker-compose.yml rename to docker-compose.yml index 3217f09..25b0e15 100644 --- a/server/docker-compose.yml +++ b/docker-compose.yml @@ -10,7 +10,7 @@ services: kafka: container_name: pong_server_kafka build: - context: kafka + context: ./kafka ports: - '9092:9092' - '9093:9093' @@ -18,13 +18,40 @@ services: environment: - KAFKA_BROKER_ID=1 - KAFKA_CFG_INTER_BROKER_LISTENER_NAME=DOCKER - - KAFKA_CFG_LISTENERS=LOCAL://:9093,DOCKER://:9092 + - KAFKA_CFG_LISTENERS=LOCAL://:9093,DOCKER://kafka:9092 - KAFKA_CFG_ADVERTISED_LISTENERS=LOCAL://127.0.0.1:9093,DOCKER://kafka:9092 - KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=LOCAL:PLAINTEXT,DOCKER:PLAINTEXT - KAFKA_CFG_ZOOKEEPER_CONNECT=zookeeper:2181 - ALLOW_PLAINTEXT_LISTENER=yes depends_on: - zookeeper + healthcheck: + test: [ "CMD", "/opt/bitnami/kafka/bin/kafka-topics.sh", "--bootstrap-server", "localhost:9093", "--describe"] + interval: 30s + timeout: 10s + retries: 5 + server: + container_name: pong_server + build: + context: ./ + dockerfile: ./server/Dockerfile + ports: + - '4000:4000' + restart: on-failure + depends_on: + - kafka + environment: + KAFKA_HOST: 'kafka:9092' + KAFKA_TOPIC_MANAGER_HOST: 'kafka:7243' + nginx: + container_name: pong_nginx + build: + context: ./ + dockerfile: ./client/Dockerfile + ports: + - '80:80' + network_mode: 'host' +# command: [ nginx-debug, '-g', 'daemon off;' ] # kaka-rest-proxy: # container_name: pong_server_kafka_rest_proxy # image: 'confluentinc/cp-kafka-rest' diff --git a/server/kafka/Dockerfile b/kafka/Dockerfile similarity index 100% rename from server/kafka/Dockerfile rename to kafka/Dockerfile diff --git a/server/kafka/custom-entrypoint.sh b/kafka/custom-entrypoint.sh similarity index 100% rename from server/kafka/custom-entrypoint.sh rename to kafka/custom-entrypoint.sh diff --git a/server/kafka/kafka-script-proxy/.dockerignore b/kafka/kafka-script-proxy/.dockerignore similarity index 100% rename from server/kafka/kafka-script-proxy/.dockerignore rename to kafka/kafka-script-proxy/.dockerignore diff --git a/server/kafka/kafka-script-proxy/.gitignore b/kafka/kafka-script-proxy/.gitignore similarity index 100% rename from server/kafka/kafka-script-proxy/.gitignore rename to kafka/kafka-script-proxy/.gitignore diff --git a/server/kafka/kafka-script-proxy/Cargo.toml b/kafka/kafka-script-proxy/Cargo.toml similarity index 100% rename from server/kafka/kafka-script-proxy/Cargo.toml rename to kafka/kafka-script-proxy/Cargo.toml diff --git a/server/kafka/kafka-script-proxy/src/main.rs b/kafka/kafka-script-proxy/src/main.rs similarity index 97% rename from server/kafka/kafka-script-proxy/src/main.rs rename to kafka/kafka-script-proxy/src/main.rs index c3c933c..88626bf 100644 --- a/server/kafka/kafka-script-proxy/src/main.rs +++ b/kafka/kafka-script-proxy/src/main.rs @@ -57,7 +57,7 @@ async fn handle_add_partition() -> Result, Infallible> { let next_partition = current_count + 1; write_to_log(&format!("Updating partition count to {} for the following topics: {}", next_partition, TOPICS.join(","))).await; for topic in TOPICS { - let output = run_command(&format!("/opt/bitnami/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --alter --topic {} --partitions {}", topic, next_partition)).await; + let output = run_command(&format!("/opt/bitnami/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9093 --alter --topic {} --partitions {}", topic, next_partition)).await; if let Err(e) = output { let error = format!("Failed to update the partition count: {}", e); write_to_log(&error).await; @@ -75,7 +75,7 @@ async fn handle_add_partition() -> Result, Infallible> { } async fn get_highest_partition_count() -> Result { - let output = run_command("/opt/bitnami/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --describe | grep -Po '(?<=PartitionCount: )(\\d+)' | sort -r | head -1").await.unwrap(); + let output = run_command("/opt/bitnami/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9093 --describe | grep -Po '(?<=PartitionCount: )(\\d+)' | sort -r | head -1").await.unwrap(); let output_str = std::str::from_utf8(&*output.stdout); if let Err(e) = output_str { let message = format!("Failed to convert command output to string: {:?}", e); diff --git a/run-server.sh b/run-server.sh index 024fd5c..9f7a820 100755 --- a/run-server.sh +++ b/run-server.sh @@ -1,6 +1,8 @@ #!/usr/bin/env bash -cd server +set -e + +cd server || exit source .env diff --git a/server/.dockerignore b/server/.dockerignore new file mode 100644 index 0000000..ecce2e8 --- /dev/null +++ b/server/.dockerignore @@ -0,0 +1,3 @@ +.env +Dockerfile +tests diff --git a/server/.env b/server/.env index 6d7b559..d09916f 100644 --- a/server/.env +++ b/server/.env @@ -1,2 +1,2 @@ KAFKA_HOST=localhost -KAFKA_PORT=9092 +KAFKA_PORT=9093 diff --git a/server/Dockerfile b/server/Dockerfile new file mode 100644 index 0000000..6907ea6 --- /dev/null +++ b/server/Dockerfile @@ -0,0 +1,16 @@ +FROM rust:latest as build_stage + +RUN mkdir /build +ADD ./pong /build/pong +ADD ./server /build/server +WORKDIR /build/server +RUN cargo build --release + +FROM ubuntu:20.04 + +RUN apt-get update && apt-get install libssl1.1 + +COPY --from=build_stage /build/server/target/release/server /usr/local/bin/ +RUN chmod +x /usr/local/bin/server + +CMD /usr/local/bin/server diff --git a/server/src/http.rs b/server/src/http.rs index b219f88..385a815 100644 --- a/server/src/http.rs +++ b/server/src/http.rs @@ -31,8 +31,8 @@ pub struct HttpServer { session_manager: Arc>, } impl HttpServer { - pub fn new(addr: [u8; 4], port: u16, kafka_host: &str) -> HttpServer { - let session_manager = Arc::new(Mutex::new(SessionManager::new(kafka_host))); + pub fn new(addr: [u8; 4], port: u16, kafka_host: &str, kafka_topic_manager_host: &str) -> HttpServer { + let session_manager = Arc::new(Mutex::new(SessionManager::new(kafka_host, kafka_topic_manager_host))); HttpServer { addr, port, @@ -415,10 +415,7 @@ pub fn build_success_res(value: &str) -> Result, Infallible> { let mut res = Response::new(Body::from(json)); let headers = res.headers_mut(); headers.insert("Content-Type", "application/json".parse().unwrap()); - headers.insert( - "Access-Control-Allow-Origin", - "*".parse().unwrap(), - ); + headers.insert("Access-Control-Allow-Origin", "*".parse().unwrap()); Ok(res) } diff --git a/server/src/main.rs b/server/src/main.rs index 08b6b8f..3d4bd5f 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -11,7 +11,18 @@ pub mod utils; #[tokio::main] pub async fn main() { - HttpServer::new([192, 168, 178, 0], 4000, "localhost:9093") + let kafka_host_env = std::env::var("KAFKA_HOST"); + let kafka_host = match kafka_host_env { + Ok(val) => val, + Err(_) => "localhost:9093".to_owned() + }; + let kafka_partition_manager_host_env = std::env::var("KAFKA_TOPIC_MANAGER_HOST"); + let kafka_topic_manager_host = match kafka_partition_manager_host_env { + Ok(val) => val, + Err(_) => "localhost:7243".to_owned() + }; + + HttpServer::new([0, 0, 0, 0], 4000, &kafka_host, &kafka_topic_manager_host) .run() .await .expect("failed to run server"); diff --git a/server/src/session.rs b/server/src/session.rs index 5e174fd..e570708 100644 --- a/server/src/session.rs +++ b/server/src/session.rs @@ -23,11 +23,11 @@ pub struct SessionManager { // TODO: On startup read the session events from kafka to restore the session id <-> hash mappings. impl SessionManager { - pub fn new(kafka_host: &str) -> SessionManager { + pub fn new(kafka_host: &str, kafka_topic_manager_host: &str) -> SessionManager { SessionManager { kafka_host: kafka_host.to_owned(), sessions: vec![], - topic_manager: KafkaTopicManager::from("localhost:7243"), + topic_manager: KafkaTopicManager::from(kafka_topic_manager_host), session_producer: EventWriter::new(Box::new(KafkaDefaultEventWriterImpl::new( kafka_host, ))), @@ -77,7 +77,10 @@ impl SessionManager { return Err(error); } if session.players[0] == player { - let error = format!("Can't join session, because player {:?} is already in session: {}", player, session_id); + let error = format!( + "Can't join session, because player {:?} is already in session: {}", + player, session_id + ); return Err(error); } session.players.push(player.clone()); @@ -172,78 +175,6 @@ impl SessionManager { } } -pub struct CachingSessionManager { - inner: SessionManager, - reader_cache: HashMap>>, - writer_cache: HashMap>>, -} - -impl CachingSessionManager { - pub fn new(kafka_host: &str) -> CachingSessionManager { - CachingSessionManager { - inner: SessionManager::new(kafka_host), - reader_cache: HashMap::new(), - writer_cache: HashMap::new(), - } - } - - pub fn get_session(&self, session_id: &str) -> Option { - self.inner.get_session(session_id) - } - - pub async fn create_session(&mut self, player: Player) -> Result { - self.inner.create_session(player).await - } - - pub async fn join_session( - &mut self, - session_id: String, - player: Player, - ) -> Result { - self.inner.join_session(session_id, player).await - } - - pub fn get_session_reader( - &mut self, - session_id: &str, - ) -> Result>, String> { - let cached = self.reader_cache.get(session_id); - if let Some(reader) = cached { - println!("Reusing existing reader for session: {:?}", session_id); - return Ok(Arc::clone(reader)); - } - let reader = self - .inner - .get_session_reader(session_id, &["move", "input", "status", "session"]); - if let Err(e) = reader { - return Err(e); - } - let reader = Arc::new(Mutex::new(reader.unwrap())); - self.reader_cache - .insert(session_id.to_string(), Arc::clone(&reader)); - return Ok(Arc::clone(&reader)); - } - - pub fn get_session_writer( - &mut self, - session_id: &str, - ) -> Result>, String> { - let cached = self.writer_cache.get(session_id); - if let Some(writer) = cached { - println!("Reusing existing writer for session: {:?}", session_id); - return Ok(Arc::clone(writer)); - } - let writer = self.inner.get_session_writer(session_id); - if let Err(e) = writer { - return Err(e); - } - let writer = Arc::new(Mutex::new(writer.unwrap())); - self.writer_cache - .insert(session_id.to_string(), Arc::clone(&writer)); - return Ok(Arc::clone(&writer)); - } -} - #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Session { pub id: u16, diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..e69de29