summaryrefslogtreecommitdiff
path: root/server/main.go
blob: cd313568af835bde6f975d57dce20273a118729e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"net/http"
	"sync"
	"sync/atomic"
	"time"

	"github.com/gorilla/websocket"
)

type playerState struct {
	ID        string  `json:"id"`
	X         float64 `json:"x"`
	Y         float64 `json:"y"`
	VX        float64 `json:"vx"`
	VY        float64 `json:"vy"`
	Height    float64 `json:"height"`
	Layer     string  `json:"layer"`
	Cycle     int     `json:"cycle"`
	UpdatedAt int64   `json:"updatedAt"`
}

type stateMessage struct {
	Type   string  `json:"type"`
	X      float64 `json:"x"`
	Y      float64 `json:"y"`
	VX     float64 `json:"vx"`
	VY     float64 `json:"vy"`
	Height float64 `json:"height"`
	Layer  string  `json:"layer"`
	Cycle  int     `json:"cycle"`
}

type welcomeMessage struct {
	Type string `json:"type"`
	ID   string `json:"id"`
}

type snapshotMessage struct {
	Type    string        `json:"type"`
	Players []playerState `json:"players"`
}

type client struct {
	id   string
	conn *websocket.Conn
	hub  *hub
	mu   sync.Mutex
}

type hub struct {
	mu      sync.RWMutex
	clients map[string]*client
	states  map[string]playerState
	ids     atomic.Uint64
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func newHub() *hub {
	return &hub{
		clients: make(map[string]*client),
		states:  make(map[string]playerState),
	}
}

func (h *hub) addClient(conn *websocket.Conn) *client {
	id := fmt.Sprintf("ghost-%04d", h.ids.Add(1))
	client := &client{id: id, conn: conn, hub: h}

	h.mu.Lock()
	h.clients[id] = client
	h.mu.Unlock()

	return client
}

func (h *hub) removeClient(id string) {
	h.mu.Lock()
	delete(h.clients, id)
	delete(h.states, id)
	h.mu.Unlock()
	h.broadcastSnapshot()
}

func (h *hub) updateState(id string, message stateMessage) {
	h.mu.Lock()
	h.states[id] = playerState{
		ID:        id,
		X:         message.X,
		Y:         message.Y,
		VX:        message.VX,
		VY:        message.VY,
		Height:    message.Height,
		Layer:     message.Layer,
		Cycle:     message.Cycle,
		UpdatedAt: time.Now().UnixMilli(),
	}
	h.mu.Unlock()
	h.broadcastSnapshot()
}

func (h *hub) snapshot() []playerState {
	h.mu.RLock()
	defer h.mu.RUnlock()

	players := make([]playerState, 0, len(h.states))
	for _, state := range h.states {
		players = append(players, state)
	}
	return players
}

func (h *hub) clientCount() int {
	h.mu.RLock()
	defer h.mu.RUnlock()
	return len(h.clients)
}

func (h *hub) broadcastSnapshot() {
	payload, err := json.Marshal(snapshotMessage{Type: "snapshot", Players: h.snapshot()})
	if err != nil {
		log.Printf("snapshot marshal error: %v", err)
		return
	}

	h.mu.RLock()
	clients := make([]*client, 0, len(h.clients))
	for _, connected := range h.clients {
		clients = append(clients, connected)
	}
	h.mu.RUnlock()

	for _, connected := range clients {
		connected.writeJSON(payload)
	}
}

func (c *client) writeJSON(payload []byte) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if err := c.conn.WriteMessage(websocket.TextMessage, payload); err != nil {
		log.Printf("write error for %s: %v", c.id, err)
	}
}

func (c *client) sendWelcome() error {
	payload, err := json.Marshal(welcomeMessage{Type: "welcome", ID: c.id})
	if err != nil {
		return err
	}
	c.writeJSON(payload)
	return nil
}

func (c *client) readLoop() {
	defer func() {
		c.hub.removeClient(c.id)
		_ = c.conn.Close()
	}()

	if err := c.sendWelcome(); err != nil {
		log.Printf("welcome error for %s: %v", c.id, err)
		return
	}

	for {
		_, payload, err := c.conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
				log.Printf("read error for %s: %v", c.id, err)
			}
			return
		}

		var message stateMessage
		if err := json.Unmarshal(payload, &message); err != nil {
			continue
		}

		if message.Type != "state" {
			continue
		}

		c.hub.updateState(c.id, message)
	}
}

func main() {
	addr := flag.String("addr", ":8080", "HTTP service address")
	flag.Parse()

	h := newHub()
	mux := http.NewServeMux()

	mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Printf("websocket upgrade error: %v", err)
			return
		}

		client := h.addClient(conn)
		go client.readLoop()
	})

	mux.HandleFunc("/ping", func(w http.ResponseWriter, _ *http.Request) {
		withCORS(w)
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("pong"))
	})

	mux.HandleFunc("/status", func(w http.ResponseWriter, _ *http.Request) {
		withCORS(w)
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{
			"status":  "online",
			"players": h.clientCount(),
		})
	})

	mux.HandleFunc("/servers", func(w http.ResponseWriter, r *http.Request) {
		withCORS(w)
		w.Header().Set("Content-Type", "application/json")

		host := r.Host
		if host == "" {
			host = "localhost:8080"
		}

		scheme := "ws"
		if r.TLS != nil {
			scheme = "wss"
		}

		_ = json.NewEncoder(w).Encode(map[string]any{
			"servers": []map[string]string{{
				"url":    fmt.Sprintf("%s://%s/ws", scheme, host),
				"region": "local",
			}},
		})
	})

	log.Printf("CyberJump relay listening on %s", *addr)
	if err := http.ListenAndServe(*addr, mux); err != nil {
		log.Fatal(err)
	}
}

func withCORS(w http.ResponseWriter) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
}