-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Extend game to multiplayer with AWS deployment #3
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -26,4 +26,4 @@ updates: | |
- "github-actions" | ||
commit-message: | ||
prefix: "github-actions" | ||
include: "scope" | ||
include: "scope" |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# alembic.ini | ||
[alembic] | ||
# path to migration scripts | ||
script_location = migrations | ||
|
||
# database connection URL | ||
sqlalchemy.url = postgresql://rpg_user:secure_password@localhost:5432/rpg_game | ||
|
||
[loggers] | ||
keys = root, sqlalchemy | ||
|
||
[handlers] | ||
keys = console | ||
|
||
[formatters] | ||
keys = generic | ||
|
||
[logger_root] | ||
level = WARN | ||
handlers = console | ||
|
||
[logger_sqlalchemy] | ||
level = WARN | ||
handlers = | ||
qualname = sqlalchemy.engine | ||
|
||
[handler_console] | ||
class = StreamHandler | ||
args = (sys.stderr,) | ||
level = NOTSET | ||
formatter = generic | ||
|
||
[formatter_generic] | ||
format = %(asctime)s %(levelname)-5.5s [%(name)s] %(message)s |
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,44 @@ | ||||||||||||||||||||||||||||||||||||||||
import asyncio | ||||||||||||||||||||||||||||||||||||||||
import websockets | ||||||||||||||||||||||||||||||||||||||||
import json | ||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||
async def connect_to_server(): | ||||||||||||||||||||||||||||||||||||||||
uri = "ws://localhost:8765" | ||||||||||||||||||||||||||||||||||||||||
async with websockets.connect(uri) as websocket: | ||||||||||||||||||||||||||||||||||||||||
Comment on lines
+7
to
+8
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use secure WebSocket (wss://) and environment variables for configuration The WebSocket URI and connection setup have security concerns:
- uri = "ws://localhost:8765"
+ uri = os.getenv("GAME_SERVER_URI", "wss://localhost:8765")
async with websockets.connect(uri) as websocket:
|
||||||||||||||||||||||||||||||||||||||||
# Authenticate player | ||||||||||||||||||||||||||||||||||||||||
await websocket.send( | ||||||||||||||||||||||||||||||||||||||||
json.dumps( | ||||||||||||||||||||||||||||||||||||||||
{"action": "authenticate", "username": "player", "password": "password"} | ||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||
Comment on lines
+10
to
+14
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove hardcoded credentials and add proper error handling Authentication credentials should not be hardcoded. Also, add error handling for authentication failures. - await websocket.send(
- json.dumps(
- {"action": "authenticate", "username": "player", "password": "password"}
- )
- )
+ try:
+ username = os.getenv("GAME_USERNAME")
+ password = os.getenv("GAME_PASSWORD")
+ if not username or not password:
+ raise ValueError("Missing authentication credentials")
+
+ await websocket.send(
+ json.dumps(
+ {"action": "authenticate", "username": username, "password": password}
+ )
+ )
+ except Exception as e:
+ logger.error(f"Authentication failed: {e}")
+ raise 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||
response = await websocket.recv() | ||||||||||||||||||||||||||||||||||||||||
print(response) | ||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||
# If class selection is required | ||||||||||||||||||||||||||||||||||||||||
response_data = json.loads(response) | ||||||||||||||||||||||||||||||||||||||||
if "classes" in response_data: | ||||||||||||||||||||||||||||||||||||||||
print("Available classes:") | ||||||||||||||||||||||||||||||||||||||||
for i, class_name in enumerate(response_data["classes"], 1): | ||||||||||||||||||||||||||||||||||||||||
print(f"{i}. {class_name}") | ||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||
class_choice = int(input("Select your class: ")) - 1 | ||||||||||||||||||||||||||||||||||||||||
selected_class = response_data["classes"][class_choice] | ||||||||||||||||||||||||||||||||||||||||
Comment on lines
+25
to
+26
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add input validation for class selection The class selection lacks input validation and error handling. - class_choice = int(input("Select your class: ")) - 1
- selected_class = response_data["classes"][class_choice]
+ while True:
+ try:
+ class_choice = int(input("Select your class (1-{}): ".format(
+ len(response_data["classes"])))) - 1
+ if 0 <= class_choice < len(response_data["classes"]):
+ selected_class = response_data["classes"][class_choice]
+ break
+ print("Invalid selection. Please try again.")
+ except ValueError:
+ print("Please enter a valid number.") 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||
# Send class selection to server | ||||||||||||||||||||||||||||||||||||||||
await websocket.send( | ||||||||||||||||||||||||||||||||||||||||
json.dumps({"action": "select_class", "class_name": selected_class}) | ||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||
response = await websocket.recv() | ||||||||||||||||||||||||||||||||||||||||
print(response) | ||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||
# Load game state | ||||||||||||||||||||||||||||||||||||||||
await websocket.send( | ||||||||||||||||||||||||||||||||||||||||
json.dumps({"action": "load_game_state", "player": {"name": "player"}}) | ||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||
response = await websocket.recv() | ||||||||||||||||||||||||||||||||||||||||
print(response) | ||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||
if __name__ == "__main__": | ||||||||||||||||||||||||||||||||||||||||
asyncio.run(connect_to_server()) |
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -0,0 +1,17 @@ | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
version: '3.8' | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
services: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
db: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
image: postgres:latest | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Specify exact PostgreSQL version instead of 'latest' tag Using the - image: postgres:latest
+ image: postgres:15.4 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
container_name: rpg_game_db | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
environment: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
POSTGRES_DB: rpg_game | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
POSTGRES_USER: rpg_user | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
POSTGRES_PASSWORD: secure_password | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Comment on lines
+8
to
+10
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Move sensitive credentials to environment variables Hardcoding database credentials in the docker-compose file is a security risk. Use environment variables instead. environment:
- POSTGRES_DB: rpg_game
- POSTGRES_USER: rpg_user
- POSTGRES_PASSWORD: secure_password
+ POSTGRES_DB: ${POSTGRES_DB:-rpg_game}
+ POSTGRES_USER: ${POSTGRES_USER:-rpg_user}
+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ports: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
- "5432:5432" | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
volumes: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
- db_data:/var/lib/postgresql/data | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Comment on lines
+4
to
+14
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion Add health check and resource limits Consider adding health checks and resource limits to ensure reliable operation in production. db:
image: postgres:latest
container_name: rpg_game_db
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U rpg_user -d rpg_game"]
+ interval: 10s
+ timeout: 5s
+ retries: 5
+ deploy:
+ resources:
+ limits:
+ memory: 1G
+ reservations:
+ memory: 512M
environment: 📝 Committable suggestion
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
volumes: | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
db_data: |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Generic single-database configuration. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
from logging.config import fileConfig | ||
|
||
from sqlalchemy import engine_from_config | ||
from sqlalchemy import pool | ||
|
||
from alembic import context | ||
|
||
# this is the Alembic Config object, which provides | ||
# access to the values within the .ini file in use. | ||
config = context.config | ||
|
||
# Interpret the config file for Python logging. | ||
# This line sets up loggers basically. | ||
if config.config_file_name is not None: | ||
fileConfig(config.config_file_name) | ||
|
||
# add your model's MetaData object here | ||
# for 'autogenerate' support | ||
# from myapp import mymodel | ||
# target_metadata = mymodel.Base.metadata | ||
target_metadata = None | ||
|
||
# other values from the config, defined by the needs of env.py, | ||
# can be acquired: | ||
# my_important_option = config.get_main_option("my_important_option") | ||
# ... etc. | ||
|
||
|
||
def run_migrations_offline() -> None: | ||
"""Run migrations in 'offline' mode. | ||
|
||
This configures the context with just a URL | ||
and not an Engine, though an Engine is acceptable | ||
here as well. By skipping the Engine creation | ||
we don't even need a DBAPI to be available. | ||
|
||
Calls to context.execute() here emit the given string to the | ||
script output. | ||
|
||
""" | ||
url = config.get_main_option("sqlalchemy.url") | ||
context.configure( | ||
url=url, | ||
target_metadata=target_metadata, | ||
literal_binds=True, | ||
dialect_opts={"paramstyle": "named"}, | ||
) | ||
|
||
with context.begin_transaction(): | ||
context.run_migrations() | ||
|
||
|
||
def run_migrations_online() -> None: | ||
"""Run migrations in 'online' mode. | ||
|
||
In this scenario we need to create an Engine | ||
and associate a connection with the context. | ||
|
||
""" | ||
connectable = engine_from_config( | ||
config.get_section(config.config_ini_section, {}), | ||
prefix="sqlalchemy.", | ||
poolclass=pool.NullPool, | ||
) | ||
|
||
with connectable.connect() as connection: | ||
context.configure(connection=connection, target_metadata=target_metadata) | ||
|
||
with context.begin_transaction(): | ||
context.run_migrations() | ||
|
||
|
||
if context.is_offline_mode(): | ||
run_migrations_offline() | ||
else: | ||
run_migrations_online() |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
"""${message} | ||
|
||
Revision ID: ${up_revision} | ||
Revises: ${down_revision | comma,n} | ||
Create Date: ${create_date} | ||
|
||
""" | ||
from typing import Sequence, Union | ||
|
||
from alembic import op | ||
import sqlalchemy as sa | ||
${imports if imports else ""} | ||
|
||
# revision identifiers, used by Alembic. | ||
revision: str = ${repr(up_revision)} | ||
down_revision: Union[str, None] = ${repr(down_revision)} | ||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} | ||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} | ||
|
||
|
||
def upgrade() -> None: | ||
${upgrades if upgrades else "pass"} | ||
|
||
|
||
def downgrade() -> None: | ||
${downgrades if downgrades else "pass"} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Expand server deployment instructions
The deployment section needs more detailed instructions:
Consider adding this structure: