aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2024-07-29 03:44:10 +0900
committernsfisis <nsfisis@gmail.com>2024-07-29 19:38:39 +0900
commitd73fd8bf5bf589a4a391c867e980761fadb647ce (patch)
tree15f2454b48cae461a6d8acc7edb2c2111d445d3e
parent3f95e0e6d62267cf8863e98f3ab7de8971a91000 (diff)
downloadphperkaigi-2025-albatross-d73fd8bf5bf589a4a391c867e980761fadb647ce.tar.gz
phperkaigi-2025-albatross-d73fd8bf5bf589a4a391c867e980761fadb647ce.tar.zst
phperkaigi-2025-albatross-d73fd8bf5bf589a4a391c867e980761fadb647ce.zip
feat: partially implement watching
-rw-r--r--backend/api/generated.go224
-rw-r--r--backend/api/handlers.go48
-rw-r--r--backend/game/client.go5
-rw-r--r--backend/game/http.go9
-rw-r--r--backend/game/hub.go28
-rw-r--r--backend/game/message.go12
-rw-r--r--backend/game/ws.go3
-rw-r--r--backend/main.go1
-rw-r--r--frontend/app/.server/api/schema.d.ts42
-rw-r--r--frontend/app/components/GolfPlayApp.tsx1
-rw-r--r--frontend/app/components/GolfWatchApp.tsx136
-rw-r--r--frontend/app/components/GolfWatchApps/GolfWatchAppConnecting.tsx3
-rw-r--r--frontend/app/components/GolfWatchApps/GolfWatchAppFinished.tsx3
-rw-r--r--frontend/app/components/GolfWatchApps/GolfWatchAppGaming.tsx39
-rw-r--r--frontend/app/components/GolfWatchApps/GolfWatchAppStarting.tsx7
-rw-r--r--frontend/app/components/GolfWatchApps/GolfWatchAppWaiting.tsx3
-rw-r--r--frontend/app/routes/golf.$gameId.watch.tsx33
-rw-r--r--openapi.yaml95
18 files changed, 644 insertions, 48 deletions
diff --git a/backend/api/generated.go b/backend/api/generated.go
index e39e3ba..7e64929 100644
--- a/backend/api/generated.go
+++ b/backend/api/generated.go
@@ -34,7 +34,12 @@ const (
// Defines values for GamePlayerMessageS2CExecResultPayloadStatus.
const (
- Success GamePlayerMessageS2CExecResultPayloadStatus = "success"
+ GamePlayerMessageS2CExecResultPayloadStatusSuccess GamePlayerMessageS2CExecResultPayloadStatus = "success"
+)
+
+// Defines values for GameWatcherMessageS2CExecResultPayloadStatus.
+const (
+ GameWatcherMessageS2CExecResultPayloadStatusSuccess GameWatcherMessageS2CExecResultPayloadStatus = "success"
)
// Game defines model for Game.
@@ -123,6 +128,57 @@ type GamePlayerMessageS2CStartPayload struct {
StartAt int `json:"start_at"`
}
+// GameWatcherMessage defines model for GameWatcherMessage.
+type GameWatcherMessage struct {
+ union json.RawMessage
+}
+
+// GameWatcherMessageS2C defines model for GameWatcherMessageS2C.
+type GameWatcherMessageS2C struct {
+ union json.RawMessage
+}
+
+// GameWatcherMessageS2CCode defines model for GameWatcherMessageS2CCode.
+type GameWatcherMessageS2CCode struct {
+ Data GameWatcherMessageS2CCodePayload `json:"data"`
+ Type string `json:"type"`
+}
+
+// GameWatcherMessageS2CCodePayload defines model for GameWatcherMessageS2CCodePayload.
+type GameWatcherMessageS2CCodePayload struct {
+ Code string `json:"code"`
+ PlayerId int `json:"player_id"`
+}
+
+// GameWatcherMessageS2CExecResult defines model for GameWatcherMessageS2CExecResult.
+type GameWatcherMessageS2CExecResult struct {
+ Data GameWatcherMessageS2CExecResultPayload `json:"data"`
+ Type string `json:"type"`
+}
+
+// GameWatcherMessageS2CExecResultPayload defines model for GameWatcherMessageS2CExecResultPayload.
+type GameWatcherMessageS2CExecResultPayload struct {
+ PlayerId int `json:"player_id"`
+ Score *int `json:"score"`
+ Status GameWatcherMessageS2CExecResultPayloadStatus `json:"status"`
+ Stderr string `json:"stderr"`
+ Stdout string `json:"stdout"`
+}
+
+// GameWatcherMessageS2CExecResultPayloadStatus defines model for GameWatcherMessageS2CExecResultPayload.Status.
+type GameWatcherMessageS2CExecResultPayloadStatus string
+
+// GameWatcherMessageS2CStart defines model for GameWatcherMessageS2CStart.
+type GameWatcherMessageS2CStart struct {
+ Data GameWatcherMessageS2CStartPayload `json:"data"`
+ Type string `json:"type"`
+}
+
+// GameWatcherMessageS2CStartPayload defines model for GameWatcherMessageS2CStartPayload.
+type GameWatcherMessageS2CStartPayload struct {
+ StartAt int `json:"start_at"`
+}
+
// JwtPayload defines model for JwtPayload.
type JwtPayload struct {
DisplayName string `json:"display_name"`
@@ -397,6 +453,130 @@ func (t *GamePlayerMessageS2C) UnmarshalJSON(b []byte) error {
return err
}
+// AsGameWatcherMessageS2C returns the union data inside the GameWatcherMessage as a GameWatcherMessageS2C
+func (t GameWatcherMessage) AsGameWatcherMessageS2C() (GameWatcherMessageS2C, error) {
+ var body GameWatcherMessageS2C
+ err := json.Unmarshal(t.union, &body)
+ return body, err
+}
+
+// FromGameWatcherMessageS2C overwrites any union data inside the GameWatcherMessage as the provided GameWatcherMessageS2C
+func (t *GameWatcherMessage) FromGameWatcherMessageS2C(v GameWatcherMessageS2C) error {
+ b, err := json.Marshal(v)
+ t.union = b
+ return err
+}
+
+// MergeGameWatcherMessageS2C performs a merge with any union data inside the GameWatcherMessage, using the provided GameWatcherMessageS2C
+func (t *GameWatcherMessage) MergeGameWatcherMessageS2C(v GameWatcherMessageS2C) error {
+ b, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+
+ merged, err := runtime.JSONMerge(t.union, b)
+ t.union = merged
+ return err
+}
+
+func (t GameWatcherMessage) MarshalJSON() ([]byte, error) {
+ b, err := t.union.MarshalJSON()
+ return b, err
+}
+
+func (t *GameWatcherMessage) UnmarshalJSON(b []byte) error {
+ err := t.union.UnmarshalJSON(b)
+ return err
+}
+
+// AsGameWatcherMessageS2CStart returns the union data inside the GameWatcherMessageS2C as a GameWatcherMessageS2CStart
+func (t GameWatcherMessageS2C) AsGameWatcherMessageS2CStart() (GameWatcherMessageS2CStart, error) {
+ var body GameWatcherMessageS2CStart
+ err := json.Unmarshal(t.union, &body)
+ return body, err
+}
+
+// FromGameWatcherMessageS2CStart overwrites any union data inside the GameWatcherMessageS2C as the provided GameWatcherMessageS2CStart
+func (t *GameWatcherMessageS2C) FromGameWatcherMessageS2CStart(v GameWatcherMessageS2CStart) error {
+ b, err := json.Marshal(v)
+ t.union = b
+ return err
+}
+
+// MergeGameWatcherMessageS2CStart performs a merge with any union data inside the GameWatcherMessageS2C, using the provided GameWatcherMessageS2CStart
+func (t *GameWatcherMessageS2C) MergeGameWatcherMessageS2CStart(v GameWatcherMessageS2CStart) error {
+ b, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+
+ merged, err := runtime.JSONMerge(t.union, b)
+ t.union = merged
+ return err
+}
+
+// AsGameWatcherMessageS2CCode returns the union data inside the GameWatcherMessageS2C as a GameWatcherMessageS2CCode
+func (t GameWatcherMessageS2C) AsGameWatcherMessageS2CCode() (GameWatcherMessageS2CCode, error) {
+ var body GameWatcherMessageS2CCode
+ err := json.Unmarshal(t.union, &body)
+ return body, err
+}
+
+// FromGameWatcherMessageS2CCode overwrites any union data inside the GameWatcherMessageS2C as the provided GameWatcherMessageS2CCode
+func (t *GameWatcherMessageS2C) FromGameWatcherMessageS2CCode(v GameWatcherMessageS2CCode) error {
+ b, err := json.Marshal(v)
+ t.union = b
+ return err
+}
+
+// MergeGameWatcherMessageS2CCode performs a merge with any union data inside the GameWatcherMessageS2C, using the provided GameWatcherMessageS2CCode
+func (t *GameWatcherMessageS2C) MergeGameWatcherMessageS2CCode(v GameWatcherMessageS2CCode) error {
+ b, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+
+ merged, err := runtime.JSONMerge(t.union, b)
+ t.union = merged
+ return err
+}
+
+// AsGameWatcherMessageS2CExecResult returns the union data inside the GameWatcherMessageS2C as a GameWatcherMessageS2CExecResult
+func (t GameWatcherMessageS2C) AsGameWatcherMessageS2CExecResult() (GameWatcherMessageS2CExecResult, error) {
+ var body GameWatcherMessageS2CExecResult
+ err := json.Unmarshal(t.union, &body)
+ return body, err
+}
+
+// FromGameWatcherMessageS2CExecResult overwrites any union data inside the GameWatcherMessageS2C as the provided GameWatcherMessageS2CExecResult
+func (t *GameWatcherMessageS2C) FromGameWatcherMessageS2CExecResult(v GameWatcherMessageS2CExecResult) error {
+ b, err := json.Marshal(v)
+ t.union = b
+ return err
+}
+
+// MergeGameWatcherMessageS2CExecResult performs a merge with any union data inside the GameWatcherMessageS2C, using the provided GameWatcherMessageS2CExecResult
+func (t *GameWatcherMessageS2C) MergeGameWatcherMessageS2CExecResult(v GameWatcherMessageS2CExecResult) error {
+ b, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+
+ merged, err := runtime.JSONMerge(t.union, b)
+ t.union = merged
+ return err
+}
+
+func (t GameWatcherMessageS2C) MarshalJSON() ([]byte, error) {
+ b, err := t.union.MarshalJSON()
+ return b, err
+}
+
+func (t *GameWatcherMessageS2C) UnmarshalJSON(b []byte) error {
+ err := t.union.UnmarshalJSON(b)
+ return err
+}
+
// ServerInterface represents all server handlers.
type ServerInterface interface {
// List games
@@ -730,26 +910,28 @@ func (sh *strictHandler) PostLogin(ctx echo.Context) error {
// Base64 encoded, gzipped, json marshaled Swagger object
var swaggerSpec = []string{
- "H4sIAAAAAAAC/9xX3W7jNhN9FX38CmwLCP7LItj6Lk23aRZb1Fi3V4vAoMWxzZQitRxqEzfQuxf8kWRZ",
- "8kpJfFE0F44tcYZnzpwhZ55IotJMSZAGyfyJYLKDlLqvNzQF+z/TKgNtOLinjGMm6H4lw1t4pGkmgMzd",
- "+mhKYmL2mf2NRnO5JUVMWK6p4UquEBIlGTbsLi4nlQmXBragrc2WprDirLF02rUw02otILULv9OwIXPy",
- "/3Ed0zgENF6EZUVM0FBtgK2oaXj/8e3l5bu37yadcNBQ4+OVeUrmn0kiFAIjMXmg3HC5XYE02nJUP3H7",
- "EIsQMqqBhJ0tKS4+/2XDJccdMHIXH5BZuT8is4iJhi8518AsipKlEmDczE8H9XeVS7W+h8TY4GzmFoLu",
- "Qf8GiHTrAlUSft+Q+edv09oyXc6uSRE/0+h6tiTFXRcS++blYK5ny/fS6P2LEH0Cyl5mea0YnI7HvW3X",
- "FTW0T8OnvC3oXij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C/wdE7EKwdUs72OJOtvRJ2G8Y/OqPfb4+cev8N5LzfC+1FCE3VYIMUipnpTVRmyiK4Bh09yIwZP",
+ "8bpRFRc0jJioaK4ox7IallJyoMJIJ9hQb5OrpsIxonUvDJTWfOan7Bmp3Z4UuJsiPCtXuIPwAgaKxZrJ",
+ "qsPktw1Dj6FHvXx/a2r17lWnhqOZ5ge+Z6iaLuKad0gXA2fJr2CvO21MMLGS9jPWnU1u+ZJqJRE9A0wJ",
+ "yr0tLL3b2QPxyRdQaMNARoPxYGQwyxgEjRmZkqvBaDAiPjGcsoEbrmnkQrgGWxQmqvb66iEkU3IP+t4K",
+ "GBVFI9Cg0K5FhlnkcwL2C97xodqnbKsoP773SyrT3gANQZXqt4neSMX+sseT/ci5Jl4zWUT50QhjLAU6",
+ "XyajUdZ5NAjrFo1jzgJrefiEjiWlvSqZipAwDRF26YVluyNUKbprvDTEI9mtcJd8YKg9ufKcRuqT69HV",
+ "K3yJymW5JOxPUi1ZGILwimy3Ujc31MWHwr61gkkUUbXLfcscS/2Me8OX7EY1bWWh+fEQHuGibZMFl8pb",
+ "2lYW/ZeJ2U68evRvbYj/Z9S5B+3RzDFDHS7XbrbFEhsYM5OoP1gRBwVQ/yDdzeCF0Ygp4laq8OBzIns6",
+ "nlw1DZZXzspsJBZHNwewysa011ao5Z9wMFGfzb/B3s/2Nc4a6ZL9udu2VwnnO48megNCG6gQOjqP+6bz",
+ "g/hCOQu9QEFozqIce6Vzbj/PpieVV6SzyvDfEZTnaJ2mafp3AAAA///2zTVTJhwAAA==",
}
// GetSwagger returns the content of the embedded swagger specification file
diff --git a/backend/api/handlers.go b/backend/api/handlers.go
index cd8b3b5..f50558d 100644
--- a/backend/api/handlers.go
+++ b/backend/api/handlers.go
@@ -179,26 +179,46 @@ func _assertJwtPayloadIsCompatibleWithJWTClaims() {
_ = p
}
+func setupJWTFromAuthorizationHeader(c echo.Context) error {
+ authorization := c.Request().Header.Get("Authorization")
+ const prefix = "Bearer "
+ if !strings.HasPrefix(authorization, prefix) {
+ return echo.NewHTTPError(http.StatusUnauthorized)
+ }
+ token := authorization[len(prefix):]
+ claims, err := auth.ParseJWT(token)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusUnauthorized, err.Error())
+ }
+ c.Set("user", claims)
+ c.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), "user", claims)))
+ return nil
+}
+
+func NewEchoJWTMiddleware() echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ err := setupJWTFromAuthorizationHeader(c)
+ if err != nil {
+ return echo.NewHTTPError(http.StatusUnauthorized, err.Error())
+ }
+ return next(c)
+ }
+ }
+}
+
func NewJWTMiddleware() StrictMiddlewareFunc {
return func(handler StrictHandlerFunc, operationID string) StrictHandlerFunc {
if operationID == "PostLogin" {
return handler
- } else {
- return func(c echo.Context, request interface{}) (response interface{}, err error) {
- authorization := c.Request().Header.Get("Authorization")
- const prefix = "Bearer "
- if !strings.HasPrefix(authorization, prefix) {
- return nil, echo.NewHTTPError(http.StatusUnauthorized)
- }
- token := authorization[len(prefix):]
+ }
- claims, err := auth.ParseJWT(token)
- if err != nil {
- return nil, echo.NewHTTPError(http.StatusUnauthorized)
- }
- c.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), "user", claims)))
- return handler(c, request)
+ return func(c echo.Context, request interface{}) (interface{}, error) {
+ err := setupJWTFromAuthorizationHeader(c)
+ if err != nil {
+ return nil, echo.NewHTTPError(http.StatusUnauthorized, err.Error())
}
+ return handler(c, request)
}
}
}
diff --git a/backend/game/client.go b/backend/game/client.go
index 7cd66a4..fa699ce 100644
--- a/backend/game/client.go
+++ b/backend/game/client.go
@@ -12,12 +12,13 @@ type playerClient struct {
hub *gameHub
conn *websocket.Conn
s2cMessages chan playerMessageS2C
+ playerID int
}
// Receives messages from the client and sends them to the hub.
func (c *playerClient) readPump() {
defer func() {
- log.Printf("closing client")
+ log.Printf("closing player client")
c.hub.unregisterPlayer <- c
c.conn.Close()
}()
@@ -87,7 +88,7 @@ func (c *watcherClient) writePump() {
defer func() {
ticker.Stop()
c.conn.Close()
- log.Printf("closing watcher")
+ log.Printf("closing watcher client")
c.hub.unregisterWatcher <- c
}()
for {
diff --git a/backend/game/http.go b/backend/game/http.go
index beda46c..1ac77b0 100644
--- a/backend/game/http.go
+++ b/backend/game/http.go
@@ -5,6 +5,7 @@ import (
"strconv"
"github.com/labstack/echo/v4"
+ // "github.com/nsfisis/iosdc-2024-albatross/backend/auth"
)
type sockHandler struct {
@@ -18,7 +19,11 @@ func newSockHandler(hubs *GameHubs) *sockHandler {
}
func (h *sockHandler) HandleSockGolfPlay(c echo.Context) error {
- // TODO: auth
+ // user := c.Get("user").(*auth.JWTClaims)
+ // if user == nil {
+ // return echo.NewHTTPError(http.StatusUnauthorized)
+ // }
+ // TODO: check user permission
gameId := c.Param("gameId")
gameIdInt, err := strconv.Atoi(gameId)
if err != nil {
@@ -34,7 +39,7 @@ func (h *sockHandler) HandleSockGolfPlay(c echo.Context) error {
if foundHub == nil {
return echo.NewHTTPError(http.StatusNotFound, "Game not found")
}
- return servePlayerWs(foundHub, c.Response(), c.Request(), "a")
+ return servePlayerWs(foundHub, c.Response(), c.Request(), 1)
}
func (h *sockHandler) HandleSockGolfWatch(c echo.Context) error {
diff --git a/backend/game/hub.go b/backend/game/hub.go
index d4a9231..770d257 100644
--- a/backend/game/hub.go
+++ b/backend/game/hub.go
@@ -121,6 +121,14 @@ func (hub *gameHub) run() {
},
}
}
+ for watcher := range hub.watchers {
+ watcher.s2cMessages <- &watcherMessageS2CStart{
+ Type: watcherMessageTypeS2CStart,
+ Data: watcherMessageS2CStartPayload{
+ StartAt: int(startAt.Unix()),
+ },
+ }
+ }
err := hub.q.UpdateGameStartedAt(hub.ctx, db.UpdateGameStartedAtParams{
GameID: int32(hub.game.gameID),
StartedAt: pgtype.Timestamp{
@@ -151,9 +159,27 @@ func (hub *gameHub) run() {
Type: playerMessageTypeS2CExecResult,
Data: playerMessageS2CExecResultPayload{
Score: &score,
- Status: api.Success,
+ Status: api.GamePlayerMessageS2CExecResultPayloadStatusSuccess,
},
}
+ for watcher := range hub.watchers {
+ watcher.s2cMessages <- &watcherMessageS2CCode{
+ Type: watcherMessageTypeS2CCode,
+ Data: watcherMessageS2CCodePayload{
+ PlayerId: message.client.playerID,
+ Code: code,
+ },
+ }
+ watcher.s2cMessages <- &watcherMessageS2CExecResult{
+ Type: watcherMessageTypeS2CExecResult,
+ Data: watcherMessageS2CExecResultPayload{
+ PlayerId: message.client.playerID,
+ Score: &score,
+ Stdout: "",
+ Stderr: "",
+ },
+ }
+ }
default:
log.Fatalf("unexpected message type: %T", message.message)
}
diff --git a/backend/game/message.go b/backend/game/message.go
index 9116bde..bb57eb5 100644
--- a/backend/game/message.go
+++ b/backend/game/message.go
@@ -66,4 +66,16 @@ func asPlayerMessageC2S(raw map[string]json.RawMessage) (playerMessageC2S, error
}
}
+const (
+ watcherMessageTypeS2CStart = "watcher:s2c:start"
+ watcherMessageTypeS2CExecResult = "watcher:s2c:execreslut"
+ watcherMessageTypeS2CCode = "watcher:s2c:code"
+)
+
type watcherMessageS2C = interface{}
+type watcherMessageS2CStart = api.GameWatcherMessageS2CStart
+type watcherMessageS2CStartPayload = api.GameWatcherMessageS2CStartPayload
+type watcherMessageS2CCode = api.GameWatcherMessageS2CCode
+type watcherMessageS2CCodePayload = api.GameWatcherMessageS2CCodePayload
+type watcherMessageS2CExecResult = api.GameWatcherMessageS2CExecResult
+type watcherMessageS2CExecResultPayload = api.GameWatcherMessageS2CExecResultPayload
diff --git a/backend/game/ws.go b/backend/game/ws.go
index 013db7a..9a3956b 100644
--- a/backend/game/ws.go
+++ b/backend/game/ws.go
@@ -23,7 +23,7 @@ var upgrader = websocket.Upgrader{
},
}
-func servePlayerWs(hub *gameHub, w http.ResponseWriter, r *http.Request, team string) error {
+func servePlayerWs(hub *gameHub, w http.ResponseWriter, r *http.Request, playerID int) error {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return err
@@ -32,6 +32,7 @@ func servePlayerWs(hub *gameHub, w http.ResponseWriter, r *http.Request, team st
hub: hub,
conn: conn,
s2cMessages: make(chan playerMessageS2C),
+ playerID: playerID,
}
hub.registerPlayer <- player
diff --git a/backend/main.go b/backend/main.go
index 91caa73..fe113dc 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -71,6 +71,7 @@ func main() {
}
defer gameHubs.Close()
sockGroup := e.Group("/sock")
+ // sockGroup.Use(api.NewEchoJWTMiddleware())
sockHandler := gameHubs.SockHandler()
sockGroup.GET("/golf/:gameId/play", func(c echo.Context) error {
return sockHandler.HandleSockGolfPlay(c)
diff --git a/frontend/app/.server/api/schema.d.ts b/frontend/app/.server/api/schema.d.ts
index 40a3347..1d3313e 100644
--- a/frontend/app/.server/api/schema.d.ts
+++ b/frontend/app/.server/api/schema.d.ts
@@ -261,6 +261,48 @@ export interface components {
/** @example print('Hello, world!') */
code: string;
};
+ GameWatcherMessage: components["schemas"]["GameWatcherMessageS2C"];
+ GameWatcherMessageS2C: components["schemas"]["GameWatcherMessageS2CStart"] | components["schemas"]["GameWatcherMessageS2CCode"] | components["schemas"]["GameWatcherMessageS2CExecResult"];
+ GameWatcherMessageS2CStart: {
+ /** @constant */
+ type: "watcher:s2c:start";
+ data: components["schemas"]["GameWatcherMessageS2CStartPayload"];
+ };
+ GameWatcherMessageS2CStartPayload: {
+ /** @example 946684800 */
+ start_at: number;
+ };
+ GameWatcherMessageS2CCode: {
+ /** @constant */
+ type: "watcher:s2c:code";
+ data: components["schemas"]["GameWatcherMessageS2CCodePayload"];
+ };
+ GameWatcherMessageS2CCodePayload: {
+ /** @example 1 */
+ player_id: number;
+ /** @example print('Hello, world!') */
+ code: string;
+ };
+ GameWatcherMessageS2CExecResult: {
+ /** @constant */
+ type: "watcher:s2c:execresult";
+ data: components["schemas"]["GameWatcherMessageS2CExecResultPayload"];
+ };
+ GameWatcherMessageS2CExecResultPayload: {
+ /** @example 1 */
+ player_id: number;
+ /**
+ * @example success
+ * @enum {string}
+ */
+ status: "success";
+ /** @example 100 */
+ score: number | null;
+ /** @example Hello, world! */
+ stdout: string;
+ /** @example */
+ stderr: string;
+ };
};
responses: never;
parameters: never;
diff --git a/frontend/app/components/GolfPlayApp.tsx b/frontend/app/components/GolfPlayApp.tsx
index c6c20d4..13afb22 100644
--- a/frontend/app/components/GolfPlayApp.tsx
+++ b/frontend/app/components/GolfPlayApp.tsx
@@ -66,7 +66,6 @@ export default function GolfPlayApp({ game }: { game: Game }) {
}, [gameState, startedAt, game.duration_seconds]);
const [currentScore, setCurrentScore] = useState<number | null>(null);
- void setCurrentScore;
const onCodeChange = useDebouncedCallback((code: string) => {
console.log("player:c2s:code");
diff --git a/frontend/app/components/GolfWatchApp.tsx b/frontend/app/components/GolfWatchApp.tsx
new file mode 100644
index 0000000..bcd1f0f
--- /dev/null
+++ b/frontend/app/components/GolfWatchApp.tsx
@@ -0,0 +1,136 @@
+import type { components } from "../.server/api/schema";
+import { useState, useEffect } from "react";
+import useWebSocket, { ReadyState } from "react-use-websocket";
+import GolfWatchAppConnecting from "./GolfWatchApps/GolfWatchAppConnecting";
+import GolfWatchAppWaiting from "./GolfWatchApps/GolfWatchAppWaiting";
+import GolfWatchAppStarting from "./GolfWatchApps/GolfWatchAppStarting";
+import GolfWatchAppGaming from "./GolfWatchApps/GolfWatchAppGaming";
+import GolfWatchAppFinished from "./GolfWatchApps/GolfWatchAppFinished";
+
+type WebSocketMessage = components["schemas"]["GameWatcherMessageS2C"];
+
+type Game = components["schemas"]["Game"];
+type Problem = components["schemas"]["Problem"];
+
+type GameState = "connecting" | "waiting" | "starting" | "gaming" | "finished";
+
+export default function GolfWatchApp({ game }: { game: Game }) {
+ // const socketUrl = `wss://t.nil.ninja/iosdc/2024/sock/golf/${game.game_id}/play`;
+ const socketUrl =
+ process.env.NODE_ENV === "development"
+ ? `ws://localhost:8002/sock/golf/${game.game_id}/play`
+ : `ws://api-server/sock/golf/${game.game_id}/play`;
+
+ const { lastJsonMessage, readyState } = useWebSocket<WebSocketMessage>(
+ socketUrl,
+ {},
+ );
+
+ const [gameState, setGameState] = useState<GameState>("connecting");
+
+ const [problem, setProblem] = useState<Problem | null>(null);
+
+ const [startedAt, setStartedAt] = useState<number | null>(null);
+
+ const [timeLeftSeconds, setTimeLeftSeconds] = useState<number | null>(null);
+
+ useEffect(() => {
+ if (gameState === "starting" && startedAt !== null) {
+ const timer1 = setInterval(() => {
+ setTimeLeftSeconds((prev) => {
+ if (prev === null) {
+ return null;
+ }
+ if (prev <= 1) {
+ clearInterval(timer1);
+ setGameState("gaming");
+ return 0;
+ }
+ return prev - 1;
+ });
+ }, 1000);
+
+ const timer2 = setInterval(() => {
+ const nowSec = Math.floor(Date.now() / 1000);
+ const finishedAt = startedAt + game.duration_seconds;
+ if (nowSec >= finishedAt) {
+ clearInterval(timer2);
+ setGameState("finished");
+ }
+ }, 1000);
+
+ return () => {
+ clearInterval(timer1);
+ clearInterval(timer2);
+ };
+ }
+ }, [gameState, startedAt, game.duration_seconds]);
+
+ const [scoreA, setScoreA] = useState<number | null>(null);
+ const [scoreB, setScoreB] = useState<number | null>(null);
+ const [codeA, setCodeA] = useState<string>("");
+ const [codeB, setCodeB] = useState<string>("");
+
+ if (readyState === ReadyState.UNINSTANTIATED) {
+ throw new Error("WebSocket is not connected");
+ }
+
+ useEffect(() => {
+ if (readyState === ReadyState.CLOSING || readyState === ReadyState.CLOSED) {
+ if (gameState !== "finished") {
+ setGameState("connecting");
+ }
+ } else if (readyState === ReadyState.CONNECTING) {
+ setGameState("connecting");
+ } else if (readyState === ReadyState.OPEN) {
+ if (lastJsonMessage !== null) {
+ console.log(lastJsonMessage.type);
+ if (lastJsonMessage.type === "watcher:s2c:start") {
+ if (
+ gameState !== "starting" &&
+ gameState !== "gaming" &&
+ gameState !== "finished"
+ ) {
+ const { start_at } = lastJsonMessage.data;
+ setStartedAt(start_at);
+ const nowSec = Math.floor(Date.now() / 1000);
+ setTimeLeftSeconds(start_at - nowSec);
+ setGameState("starting");
+ }
+ } else if (lastJsonMessage.type === "watcher:s2c:code") {
+ const { player_id, code } = lastJsonMessage.data;
+ setCodeA(code);
+ } else if (lastJsonMessage.type === "watcher:s2c:execresult") {
+ const { score } = lastJsonMessage.data;
+ if (score !== null && (scoreA === null || score < scoreA)) {
+ setScoreA(score);
+ }
+ }
+ } else {
+ setGameState("waiting");
+ }
+ }
+ }, [lastJsonMessage, readyState, gameState, scoreA]);
+
+ if (gameState === "connecting") {
+ return <GolfWatchAppConnecting />;
+ } else if (gameState === "waiting") {
+ return <GolfWatchAppWaiting />;
+ } else if (gameState === "starting") {
+ return <GolfWatchAppStarting timeLeft={timeLeftSeconds!} />;
+ } else if (gameState === "gaming") {
+ return (
+ <GolfWatchAppGaming
+ problem={problem!.description}
+ codeA={codeA}
+ scoreA={scoreA}
+ codeB={codeB}
+ scoreB={scoreB}
+ />
+ );
+ } else if (gameState === "finished") {
+ return <GolfWatchAppFinished />;
+ } else {
+ return null;
+ }
+}
diff --git a/frontend/app/components/GolfWatchApps/GolfWatchAppConnecting.tsx b/frontend/app/components/GolfWatchApps/GolfWatchAppConnecting.tsx
new file mode 100644
index 0000000..07e359f
--- /dev/null
+++ b/frontend/app/components/GolfWatchApps/GolfWatchAppConnecting.tsx
@@ -0,0 +1,3 @@
+export default function GolfWatchAppConnecting() {
+ return <div>Connecting...</div>;
+}
diff --git a/frontend/app/components/GolfWatchApps/GolfWatchAppFinished.tsx b/frontend/app/components/GolfWatchApps/GolfWatchAppFinished.tsx
new file mode 100644
index 0000000..330d1a6
--- /dev/null
+++ b/frontend/app/components/GolfWatchApps/GolfWatchAppFinished.tsx
@@ -0,0 +1,3 @@
+export default function GolfWatchAppFinished() {
+ return <div>Finished</div>;
+}
diff --git a/frontend/app/components/GolfWatchApps/GolfWatchAppGaming.tsx b/frontend/app/components/GolfWatchApps/GolfWatchAppGaming.tsx
new file mode 100644
index 0000000..d58a04f
--- /dev/null
+++ b/frontend/app/components/GolfWatchApps/GolfWatchAppGaming.tsx
@@ -0,0 +1,39 @@
+export default function GolfWatchAppGaming({
+ problem,
+ codeA,
+ scoreA,
+ codeB,
+ scoreB,
+}: {
+ problem: string;
+ codeA: string;
+ scoreA: number | null;
+ codeB: string;
+ scoreB: number | null;
+}) {
+ return (
+ <div style={{ display: "flex", flexDirection: "column" }}>
+ <div style={{ display: "flex", flex: 1, justifyContent: "center" }}>
+ <div>{problem}</div>
+ </div>
+ <div style={{ display: "flex", flex: 3 }}>
+ <div style={{ display: "flex", flex: 3, flexDirection: "column" }}>
+ <div style={{ flex: 1, justifyContent: "center" }}>{scoreA}</div>
+ <div style={{ flex: 3 }}>
+ <pre>
+ <code>{codeA}</code>
+ </pre>
+ </div>
+ </div>
+ <div style={{ display: "flex", flex: 3, flexDirection: "column" }}>
+ <div style={{ flex: 1, justifyContent: "center" }}>{scoreB}</div>
+ <div style={{ flex: 3 }}>
+ <pre>
+ <code>{codeB}</code>
+ </pre>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/app/components/GolfWatchApps/GolfWatchAppStarting.tsx b/frontend/app/components/GolfWatchApps/GolfWatchAppStarting.tsx
new file mode 100644
index 0000000..643af93
--- /dev/null
+++ b/frontend/app/components/GolfWatchApps/GolfWatchAppStarting.tsx
@@ -0,0 +1,7 @@
+export default function GolfWatchAppStarting({
+ timeLeft,
+}: {
+ timeLeft: number;
+}) {
+ return <div>Starting... ({timeLeft} s)</div>;
+}
diff --git a/frontend/app/components/GolfWatchApps/GolfWatchAppWaiting.tsx b/frontend/app/components/GolfWatchApps/GolfWatchAppWaiting.tsx
new file mode 100644
index 0000000..6733b3b
--- /dev/null
+++ b/frontend/app/components/GolfWatchApps/GolfWatchAppWaiting.tsx
@@ -0,0 +1,3 @@
+export default function GolfWatchAppWaiting() {
+ return <div>Waiting...</div>;
+}
diff --git a/frontend/app/routes/golf.$gameId.watch.tsx b/frontend/app/routes/golf.$gameId.watch.tsx
new file mode 100644
index 0000000..e1cb5d7
--- /dev/null
+++ b/frontend/app/routes/golf.$gameId.watch.tsx
@@ -0,0 +1,33 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { isAuthenticated } from "../.server/auth";
+import { apiClient } from "../.server/api/client";
+import { useLoaderData } from "@remix-run/react";
+import GolfWatchApp from "../components/GolfWatchApp";
+
+export async function loader({ params, request }: LoaderFunctionArgs) {
+ const { token } = await isAuthenticated(request, {
+ failureRedirect: "/login",
+ });
+ const { data, error } = await apiClient.GET("/games/{game_id}", {
+ params: {
+ path: {
+ game_id: Number(params.gameId),
+ },
+ header: {
+ Authorization: `Bearer ${token}`,
+ },
+ },
+ });
+ if (error) {
+ throw new Error(error.message);
+ }
+ return {
+ game: data,
+ };
+}
+
+export default function GolfWatch() {
+ const { game } = useLoaderData<typeof loader>();
+
+ return <GolfWatchApp game={game} />;
+}
diff --git a/openapi.yaml b/openapi.yaml
index d058381..fa6c8d0 100644
--- a/openapi.yaml
+++ b/openapi.yaml
@@ -306,11 +306,94 @@ components:
example: "print('Hello, world!')"
required:
- code
- # GameWatcherMessage:
- # oneOf:
- # - $ref: '#/components/schemas/GameWatcherMessageS2C'
- # - $ref: '#/components/schemas/GameWatcherMessageC2S'
- # GameWatcherMessageS2C:
- # oneOf:
+ GameWatcherMessage:
+ oneOf:
+ - $ref: '#/components/schemas/GameWatcherMessageS2C'
+ # - $ref: '#/components/schemas/GameWatcherMessageC2S'
+ GameWatcherMessageS2C:
+ oneOf:
+ - $ref: '#/components/schemas/GameWatcherMessageS2CStart'
+ - $ref: '#/components/schemas/GameWatcherMessageS2CCode'
+ - $ref: '#/components/schemas/GameWatcherMessageS2CExecResult'
+ GameWatcherMessageS2CStart:
+ type: object
+ properties:
+ type:
+ type: string
+ const: "watcher:s2c:start"
+ data:
+ $ref: '#/components/schemas/GameWatcherMessageS2CStartPayload'
+ required:
+ - type
+ - data
+ GameWatcherMessageS2CStartPayload:
+ type: object
+ properties:
+ start_at:
+ type: integer
+ example: 946684800
+ required:
+ - start_at
+ GameWatcherMessageS2CCode:
+ type: object
+ properties:
+ type:
+ type: string
+ const: "watcher:s2c:code"
+ data:
+ $ref: '#/components/schemas/GameWatcherMessageS2CCodePayload'
+ required:
+ - type
+ - data
+ GameWatcherMessageS2CCodePayload:
+ type: object
+ properties:
+ player_id:
+ type: integer
+ example: 1
+ code:
+ type: string
+ example: "print('Hello, world!')"
+ required:
+ - player_id
+ - code
+ GameWatcherMessageS2CExecResult:
+ type: object
+ properties:
+ type:
+ type: string
+ const: "watcher:s2c:execresult"
+ data:
+ $ref: '#/components/schemas/GameWatcherMessageS2CExecResultPayload'
+ required:
+ - type
+ - data
+ GameWatcherMessageS2CExecResultPayload:
+ type: object
+ properties:
+ player_id:
+ type: integer
+ example: 1
+ status:
+ type: string
+ example: "success"
+ enum:
+ - success
+ score:
+ type: integer
+ nullable: true
+ example: 100
+ stdout:
+ type: string
+ example: "Hello, world!"
+ stderr:
+ type: string
+ example: ""
+ required:
+ - player_id
+ - status
+ - score
+ - stdout
+ - stderr
# GameWatcherMessageC2S:
# oneOf: