Brijesh's Git Server — navigator-v2 @ 19f964e87980aeb2d2f6a016091d7bfe1bdb3732

api/internal/server/routes.go (view raw)

 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
package server

import (
	"api/internal/browser"
	"encoding/json"
	"log"
	"net/http"

	"fmt"
	"time"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/go-chi/cors"
	"github.com/google/uuid"

	"github.com/coder/websocket"
)

func (s *Server) RegisterRoutes() http.Handler {
	r := chi.NewRouter()
	r.Use(middleware.Logger)

	r.Use(cors.Handler(cors.Options{
		AllowedOrigins:   []string{"*"},
		AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"},
		AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token", "Upgrade", "Connection", "Sec-WebSocket-Key", "Sec-WebSocket-Version", "Sec-WebSocket-Extensions", "Sec-WebSocket-Protocol"},
		ExposedHeaders:   []string{"Link", "Upgrade", "Connection", "Sec-WebSocket-Accept"},
		AllowCredentials: true,
		MaxAge:           300,
	}))

	r.Get("/", s.HelloWorldHandler)

	r.Get("/health", s.healthHandler)

	r.Get("/websocket", s.websocketHandler)

	r.Route("/api/browser", func(r chi.Router) {
		r.Get("/sessions", s.listBrowserSessions)
		r.Post("/sessions", s.createBrowserSession)
		r.Route("/sessions/{sessionID}", func(r chi.Router) {
			r.Get("/", s.getBrowserSession)
			r.Delete("/", s.stopBrowserSession)
			r.Get("/vnc", s.browserVNCProxy)
		})
	})

	return r
}

func (s *Server) HelloWorldHandler(w http.ResponseWriter, r *http.Request) {
	resp := make(map[string]string)
	resp["message"] = "Hello World"

	jsonResp, err := json.Marshal(resp)
	if err != nil {
		log.Fatalf("error handling JSON marshal. Err: %v", err)
	}

	_, _ = w.Write(jsonResp)
}

func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) {
	jsonResp, _ := json.Marshal(s.db.Health())
	_, _ = w.Write(jsonResp)
}

func (s *Server) websocketHandler(w http.ResponseWriter, r *http.Request) {
	socket, err := websocket.Accept(w, r, nil)

	if err != nil {
		log.Printf("could not open websocket: %v", err)
		_, _ = w.Write([]byte("could not open websocket"))
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	defer socket.Close(websocket.StatusGoingAway, "server closing websocket")

	ctx := r.Context()
	socketCtx := socket.CloseRead(ctx)

	for {
		payload := fmt.Sprintf("server timestamp: %d", time.Now().UnixNano())
		err := socket.Write(socketCtx, websocket.MessageText, []byte(payload))
		if err != nil {
			break
		}
		time.Sleep(time.Second * 2)
	}
}

func (s *Server) listBrowserSessions(w http.ResponseWriter, r *http.Request) {
	sessions, err := s.browserService.ListSessions(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	json.NewEncoder(w).Encode(sessions)
}

func (s *Server) createBrowserSession(w http.ResponseWriter, r *http.Request) {
	session, err := s.browserService.StartSession(r.Context())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(session)
}

func (s *Server) getBrowserSession(w http.ResponseWriter, r *http.Request) {
	sessionID, err := uuid.Parse(chi.URLParam(r, "sessionID"))
	if err != nil {
		http.Error(w, "invalid session ID", http.StatusBadRequest)
		return
	}

	session, err := s.browserService.GetSession(r.Context(), sessionID)
	if err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}
	json.NewEncoder(w).Encode(session)
}

func (s *Server) stopBrowserSession(w http.ResponseWriter, r *http.Request) {
	sessionID, err := uuid.Parse(chi.URLParam(r, "sessionID"))
	if err != nil {
		http.Error(w, "invalid session ID", http.StatusBadRequest)
		return
	}

	if err := s.browserService.StopSession(r.Context(), sessionID); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

func (s *Server) browserVNCProxy(w http.ResponseWriter, r *http.Request) {
	log.Printf("VNC proxy request received from %s", r.RemoteAddr)
	log.Printf("Headers: %v", r.Header)

	sessionID, err := uuid.Parse(chi.URLParam(r, "sessionID"))
	if err != nil {
		log.Printf("Invalid session ID: %v", err)
		http.Error(w, "invalid session ID", http.StatusBadRequest)
		return
	}

	log.Printf("Getting session for ID: %s", sessionID)
	session, err := s.browserService.GetSession(r.Context(), sessionID)
	if err != nil {
		log.Printf("Failed to get session: %v", err)
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}

	// Add WebSocket upgrade options
	upgradeOptions := &websocket.AcceptOptions{
		InsecureSkipVerify: true,
	}

	log.Printf("Attempting WebSocket upgrade")
	ws, err := websocket.Accept(w, r, upgradeOptions)
	if err != nil {
		log.Printf("WebSocket upgrade failed: %v", err)
		log.Printf("Request headers: %v", r.Header)
		http.Error(w, "could not upgrade to websocket", http.StatusInternalServerError)
		return
	}
	defer ws.Close(websocket.StatusInternalError, "")

	log.Printf("Creating VNC proxy for session %s", sessionID)
	proxy := browser.NewVNCProxy(session)
	if err := proxy.ServeWebSocket(r.Context(), ws); err != nil {
		log.Printf("VNC proxy error for session %s: %v", sessionID, err)
	}
}