jumpstorm/server/src/server.ts

180 lines
4.3 KiB
TypeScript
Raw Normal View History

import { Game } from "@engine/Game";
2023-08-23 21:44:59 -04:00
import { EntityNames, Player } from "@engine/entities";
import { WallBounds, Physics, Collision, NetworkUpdate } from "@engine/systems";
import {
2023-08-23 21:44:59 -04:00
type MessageQueueProvider,
type MessagePublisher,
MessageType,
type MessageProcessor,
type Message,
} from "@engine/network";
import { stringify, parse } from "@engine/utils";
import { Grid } from "@engine/structures";
import { Miscellaneous } from "@engine/config";
import { Server } from "bun";
2023-07-21 01:22:26 -04:00
2023-08-23 21:44:59 -04:00
const SERVER_PORT = 8080;
const SERVER_TICK_RATE = (1 / 100) * 1000;
const GAME_TOPIC = "game";
type SessionData = { sessionId: string };
interface ServerMessage extends Message {
sessionData: SessionData;
}
class ServerSocketMessageReceiver implements MessageQueueProvider {
2023-08-23 21:44:59 -04:00
private messages: ServerMessage[];
2023-07-21 01:22:26 -04:00
constructor() {
this.messages = [];
}
2023-08-23 21:44:59 -04:00
public addMessage(message: ServerMessage) {
this.messages.push(message);
}
2023-08-23 21:44:59 -04:00
public getNewMessages() {
return this.messages;
}
2023-08-23 21:44:59 -04:00
public clearMessages() {
this.messages = [];
}
}
2023-08-23 21:44:59 -04:00
class ServerMessageProcessor implements MessageProcessor {
constructor() {}
public process(_message: ServerMessage) {}
}
class ServerSocketMessagePublisher implements MessagePublisher {
2023-08-23 21:44:59 -04:00
private server?: Server;
private messages: Message[];
constructor(server?: Server) {
if (server) {
this.server = server;
}
this.messages = [];
}
2023-08-23 21:44:59 -04:00
public setServer(server: Server) {
this.server = server;
}
public addMessage(message: Message) {
this.messages.push(message);
}
2023-08-23 21:44:59 -04:00
public publish() {
this.messages.forEach(
(message) => this.server?.publish(GAME_TOPIC, stringify(message)),
);
this.messages = [];
}
}
const game = new Game();
const messageReceiver = new ServerSocketMessageReceiver();
2023-08-23 21:44:59 -04:00
const messagePublisher = new ServerSocketMessagePublisher();
const messageProcessor = new ServerMessageProcessor();
const sessionControllableEntities: Map<string, Set<string>> = new Map();
2023-08-23 21:44:59 -04:00
const server = Bun.serve<SessionData>({
port: SERVER_PORT,
fetch: async (req, server): Promise<Response> => {
const url = new URL(req.url);
const headers = new Headers();
headers.set("Access-Control-Allow-Origin", "*");
if (url.pathname == "/assign") {
const sessionId = crypto.randomUUID();
headers.set("Set-Cookie", `SessionId=${sessionId};`);
return new Response(sessionId, { headers });
}
const cookie = req.headers.get("cookie");
if (!cookie) {
return new Response("No session", { headers, status: 401 });
}
const sessionId = cookie.split(";").at(0)!.split("SessionId=").at(1);
if (url.pathname == "/game") {
headers.set(
"Set-Cookie",
`SessionId=${sessionId}; HttpOnly; SameSite=Strict;`,
);
server.upgrade(req, {
headers,
data: {
sessionId,
},
});
return new Response("upgraded", { headers });
}
if (url.pathname == "/me") {
return new Response(sessionId, { headers });
}
return new Response("Not found", { headers, status: 404 });
},
websocket: {
open(ws) {
const { sessionId } = ws.data;
if (sessionControllableEntities.has(sessionId)) {
2023-08-23 21:44:59 -04:00
// no need to add player
return;
}
2023-08-23 21:44:59 -04:00
const player = new Player(sessionId);
game.addEntity(player);
sessionControllableEntities.set(sessionId, new Set(player.id));
2023-08-23 21:44:59 -04:00
messagePublisher.addMessage({
type: MessageType.NEW_ENTITY,
body: {
entityName: EntityNames.Player,
args: { playerId: sessionId },
},
});
ws.subscribe(GAME_TOPIC);
},
message(ws, message) {
2023-08-23 21:44:59 -04:00
if (typeof message == "string") {
const receivedMessage = parse<ServerMessage>(message);
receivedMessage.sessionData = ws.data;
messageReceiver.addMessage(receivedMessage);
}
},
2023-08-23 21:44:59 -04:00
close(_ws) {},
},
});
2023-08-23 21:44:59 -04:00
messagePublisher.setServer(server);
[
new Physics(),
new Collision(new Grid()),
new WallBounds(Miscellaneous.WIDTH),
2023-08-23 21:44:59 -04:00
new NetworkUpdate(messageReceiver, messagePublisher, messageProcessor),
].forEach((system) => game.addSystem(system));
game.start();
setInterval(() => {
game.doGameLoop(performance.now());
2023-08-23 21:44:59 -04:00
}, SERVER_TICK_RATE);
console.log(`Listening on ${server.hostname}:${server.port}`);