Skip to content

Commit

Permalink
Merge branch 'main' into backend
Browse files Browse the repository at this point in the history
  • Loading branch information
ettolrach authored Mar 3, 2024
2 parents 9ff124e + 045f0a2 commit e198cbd
Show file tree
Hide file tree
Showing 42 changed files with 1,415 additions and 251 deletions.
53 changes: 53 additions & 0 deletions .github/workflows/build-cache-server.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
name: "Build CosmicKube cache server"
on:
push:
branches:
- main
jobs:
build-server:
name: "Build Cache Server"
runs-on: ubuntu-20.04
permissions:
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4

- name: Download Go
uses: actions/setup-go@v5
with:
go-version: '^1.22'

- name: Build
run: |
cd kube_cache
go build && strip kube_cache
- name: Upload Artifact
uses: actions/upload-artifact@v1
with:
name: cache_server
path: kube_cache/kube_cache


- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to DockerHub
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

# this will push the docker images to the github container registry
# you will need to give actions permission to push there first
- name: Build and push
id: docker_build
uses: docker/build-push-action@v3
with:
context: .
file: kube_cache/cache.Dockerfile
push: true
tags: |
ghcr.io/pilksoc/kubecache:latest
ghcr.io/pilksoc/kubecache:dev-${{ github.run_number }}
4 changes: 2 additions & 2 deletions .github/workflows/build-game-client.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: "Build CosmicKube game client"
on:
push:
branches:
- main
- main

env:
GODOT_VERSION: 4.2.1
Expand Down Expand Up @@ -59,4 +59,4 @@ jobs:
###### Repository/Build Configurations ######
app_location: "build/web"
skip_app_build: true
###### End of Repository/Build Configurations ######
###### End of Repository/Build Configurations ######
2 changes: 1 addition & 1 deletion .github/workflows/build-game-server.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ jobs:
uses: docker/build-push-action@v3
with:
context: .
file: server.Dockerfile
file: backend/server.Dockerfile
push: true
tags: |
ghcr.io/pilksoc/cosmickube:dev-latest
Expand Down
1 change: 1 addition & 0 deletions backend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ futures = { version = "0.3", default-features=false}
serde_repr = "0.1"
reqwest = "0.11.24"
url = "2.5.0"
rand = "0.8.5"
4 changes: 2 additions & 2 deletions server.Dockerfile → backend/server.Dockerfile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
FROM alpine:3.19.1
FROM debian:12.5-slim

RUN apk update && apk add ca-certificates && apk cache clean
RUN apt update && apt install ca-certificates -y && apt upgrade -y
WORKDIR /usr/local/cosmic_kube
COPY backend/target/release/cosmic_kube_amd64 /usr/local/bin/cosmic_kube

Expand Down
12 changes: 9 additions & 3 deletions backend/src/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
use crate::{ws, Clients, Result};
use warp::Reply;

pub async fn ws_handler(ws: warp::ws::Ws, clients: Clients) -> Result<impl Reply>
{
pub async fn ws_handler(ws: warp::ws::Ws, clients: Clients) -> Result<impl Reply> {
println!("ws_handler"); //debug

Ok(ws.on_upgrade(move |socket| ws::client_connection(socket, clients)))
}
}

pub async fn metrics_handler(clients: Clients) -> Result<impl Reply> {
let metricsString = "cosmic_kube_clients{type=\"connected\"} ".to_string()
+ &clients.lock().await.len().to_string()
+ "\n";
Ok(metricsString)
}
2 changes: 1 addition & 1 deletion backend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ pub mod local_grid;
pub mod cache_client;
pub mod recipe;

type Coordinate = [u64; 2];
pub type Coordinate = [u64; 2];
17 changes: 9 additions & 8 deletions backend/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,23 @@ type Result<T> = std::result::Result<T, Rejection>;

#[tokio::main]
async fn main() {

//initialise a hashmap to store currently connected clients. We may want some more logic here if we want currently connected clients to be stored somewhere
let clients: Clients = Arc::new(Mutex::new(HashMap::new()));

println!("configuring websocket route"); //debug
println!("Configuring websocket route"); //debug
let ws_route = warp::path("ws")
.and(warp::ws())
.and(with_clients(clients.clone()))
.and_then(handlers::ws_handler);
.and(warp::ws())
.and(with_clients(clients.clone()))
.and_then(handlers::ws_handler)
.or(warp::path("metrics")
.and(with_clients(clients.clone()))
.and_then(handlers::metrics_handler));

let routes = ws_route.with(warp::cors().allow_any_origin());
println!("starting server"); //debug
warp::serve(routes).run(([127, 0, 0, 1], 8000)).await; //PORT 8000 localhost
println!("Starting server on http://0.0.0.0:8000"); //debug
warp::serve(routes).run(([0, 0, 0, 0], 8000)).await;
}

fn with_clients(clients: Clients) -> impl Filter<Extract = (Clients,), Error = Infallible> + Clone {
warp::any().map(move || clients.clone())
}

1 change: 0 additions & 1 deletion backend/src/websocketstructs.rs

This file was deleted.

86 changes: 69 additions & 17 deletions backend/src/ws/gen_json.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
use core::fmt;
use cosmic_kube::grid::Grid;
use cosmic_kube::kube::Kube;
use cosmic_kube::local_grid::LocalGrid;
use cosmic_kube::space::{Space, SpaceKind};
use cosmic_kube::Coordinate;
use core::fmt;
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_json::json;
use serde_repr::{Serialize_repr, Deserialize_repr};
use serde_json::{json, Value};
use serde_repr::{Deserialize_repr, Serialize_repr};

//example valid json:
// { "initialised": true, "player": "charlie zoot", "coordinates": [10, 10], "action": { "kind": 1, "kube": { "id": {"uuid": "f7993723-2529-50c4-950d-ba104d29b5df" }, "name": "dirt" }, "coordinates": [10,11] } }


// this is the data we expect to recieve from the player
#[derive(Serialize, Deserialize)]
pub struct PlayerInfo {
player: String, //Player, //the player requesting the data
coordinates: [u64; 2], //current player coordinates
initialised: bool,
player: String, //Player, //the player requesting the data
coordinates: [u64; 2], //current player coordinates
action: Option<Action>, // 0, block picked up 1, block placed
}

Expand All @@ -32,30 +42,72 @@ impl fmt::Display for ActionType {
pub struct Action {
kind: ActionType,
kube: Kube,
coordinates: Coordinate,
}

fn recalculate_game(state: PlayerInfo) -> String {
fn perform_action(mut grid: Grid, action: Action) -> Grid {
let kube_result: SpaceKind;
match action.kind {
ActionType::Pickup => kube_result = SpaceKind::EmptySpace,
ActionType::Place => kube_result = SpaceKind::Kube(action.kube),
}

let space_in_question: Space = Space::new(action.coordinates, kube_result);
grid.insert(space_in_question);
grid
}

fn debug_message(state: &PlayerInfo) {
// debug: log of event to server console
println!("{} @ (x:{}, y:{})", state.player, state.coordinates[0], state.coordinates[1]);
match state.action {
println!(
"{} @ (x:{}, y:{})",
state.player, state.coordinates[0], state.coordinates[1]
);
let mut _has_action: bool = true;
match &state.action {
Some(p) => println!("{}: {}", p.kind, p.kube.name),
None => println!(""),
None => _has_action = false,
}
}

//send action to database to get result !!!<----
fn recalculate_game(state: PlayerInfo) -> String {
debug_message(&state); //debug

// total_grid: Grid = get grid from GO db
let example_grid: Grid = Grid::new(2048, 2048);
let new_grid_to_send: Grid;

// then we want to update the grid by performing action
match state.action {
Some(p) => new_grid_to_send = perform_action(example_grid, p),
_ => new_grid_to_send = example_grid,
}

let resp = json!({
"grid" : "edited grid"
});
//store new_grid_to_send in the database

resp.to_string()
let new_grid: LocalGrid =
LocalGrid::from_grid_and_coord(&new_grid_to_send, state.coordinates, 48);
let resp: Value;

if state.initialised {
// if the player is not new to the game, continue game loop
resp = json!({
"grid" : new_grid,
});
} else {
let mut rng = rand::thread_rng();
resp = json!({
"coordinates" : [rng.gen_range(0..2048), rng.gen_range(0..2048)]
});
}

resp.to_string()
}

pub fn create_response(message: &str) -> String {

// Parse the string of data into serde_json::Value.
let state: PlayerInfo = serde_json::from_str(message).expect("something went wrong in json parse");
let state: PlayerInfo =
serde_json::from_str(message).expect("something went wrong in json parse");

recalculate_game(state)
}

9 changes: 0 additions & 9 deletions diesel.toml

This file was deleted.

79 changes: 79 additions & 0 deletions game-source/WebSockets.gd
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
extends Node
class_name WebSocketClient

@export var handshake_headers : PackedStringArray
@export var supported_protocols : PackedStringArray
@export var tls_trusted_certificate : X509Certificate
@export var tls_verify := true


var socket = WebSocketPeer.new()
var last_state = WebSocketPeer.STATE_CLOSED


signal connected_to_server()
signal connection_closed()
signal message_received(message: Variant)


func connect_to_url(url) -> int:
socket.supported_protocols = supported_protocols
socket.handshake_headers = handshake_headers
var tls_options = TLSOptions.client(tls_trusted_certificate)
var err = socket.connect_to_url(url, tls_options)
if err != OK:
print("i tried :(", err)
return err
last_state = socket.get_ready_state()
return OK


func send(message) -> int:
print(socket.get_ready_state())
if typeof(message) == TYPE_STRING:
return socket.send_text(message)
return socket.send(var_to_bytes(message))


func get_message() -> Variant:
if socket.get_available_packet_count() < 1:
return null
var pkt = socket.get_packet()
if socket.was_string_packet():
return pkt.get_string_from_utf8()
return bytes_to_var(pkt)


func close(code := 1000, reason := "") -> void:
socket.close(code, reason)
last_state = socket.get_ready_state()


func clear() -> void:
socket = WebSocketPeer.new()
last_state = socket.get_ready_state()


func get_socket() -> WebSocketPeer:
return socket


func poll() -> void:
if socket.get_ready_state() != socket.STATE_CLOSED:
socket.poll()
var state = socket.get_ready_state()
if last_state != state:
last_state = state
if state == socket.STATE_OPEN:
connected_to_server.emit()
elif state == socket.STATE_CLOSED:
connection_closed.emit()
while socket.get_ready_state() == socket.STATE_OPEN and socket.get_available_packet_count():
message_received.emit(get_message())


func _ready():
connect_to_url("ws://localhost:8000/ws")

func _process(delta):
poll()
Binary file added game-source/assets/Illustration95.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

importer="texture"
type="CompressedTexture2D"
uid="uid://bay85nk58yj5e"
path="res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"
uid="uid://bdap4f6w37byq"
path="res://.godot/imported/Illustration95.png-83b3dbf36a7985d78f181801efd673ad.ctex"
metadata={
"vram_texture": false
}

[deps]

source_file="res://icon.svg"
dest_files=["res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"]
source_file="res://assets/Illustration95.png"
dest_files=["res://.godot/imported/Illustration95.png-83b3dbf36a7985d78f181801efd673ad.ctex"]

[params]

Expand All @@ -32,6 +32,3 @@ process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1
svg/scale=1.0
editor/scale_with_editor_scale=false
editor/convert_colors_with_editor_theme=false
File renamed without changes.
1 change: 0 additions & 1 deletion game-source/icon.svg

This file was deleted.

Loading

0 comments on commit e198cbd

Please sign in to comment.