main.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. // client2server - Go server with WebSocket + Redpanda
  2. // Copyright (c) 2026 Luis Rosales - MIT License
  3. //
  4. // Build: go build -o client2server-server
  5. // Run: ./client2server-server
  6. // WebSocket: ws://localhost:3843
  7. // HTTP API: http://localhost:3843
  8. package main
  9. import (
  10. "context"
  11. "encoding/json"
  12. "fmt"
  13. "log"
  14. "net/http"
  15. "os"
  16. "os/signal"
  17. "syscall"
  18. "time"
  19. "github.com/google/uuid"
  20. "github.com/redpanda-data/redpanda-sdk-go/redpanda"
  21. "github.com/redpanda-data/redpanda-sdk-go/schema"
  22. "nhooyr.io/websocket"
  23. )
  24. // Config
  25. type Config struct {
  26. RedpandaBrokers []string
  27. WebsocketPort int
  28. APIPort int
  29. Token string
  30. }
  31. var cfg = Config{
  32. RedpandaBrokers: []string{"localhost:9092"},
  33. WebsocketPort: 3843,
  34. APIPort: 3844,
  35. Token: "secret-token",
  36. }
  37. // Event from router
  38. type RouterEvent struct {
  39. ID string `json:"id"`
  40. RouterID string `json:"router_id"`
  41. Hostname string `json:"hostname"`
  42. EventType string `json:"event_type"`
  43. Timestamp time.Time `json:"timestamp"`
  44. Payload map[string]interface{} `json:"payload"`
  45. ReceivedAt time.Time `json:"received_at"`
  46. Connection string `json:"connection"`
  47. }
  48. // Command to router
  49. type RouterCommand struct {
  50. ID string `json:"id"`
  51. RouterID string `json:"router_id"`
  52. Command string `json:"command"`
  53. Args map[string]string `json:"args,omitempty"`
  54. SentAt time.Time `json:"sent_at"`
  55. }
  56. // Command result received from router
  57. type CommandResult struct {
  58. Success bool `json:"success"`
  59. Output string `json:"output"`
  60. Error string `json:"error"`
  61. }
  62. // Router state
  63. type Router struct {
  64. ID string
  65. LastSeen time.Time
  66. Conn *websocket.Conn
  67. Connected bool
  68. }
  69. var routers = make(map[string]*Router)
  70. // Pending commands awaiting results (command_id -> result channel)
  71. var pendingCommands = make(map[string]chan CommandResult)
  72. const commandTimeout = 30 * time.Second
  73. // Redpanda
  74. var rp *redpanda.Client
  75. func initRedpanda() error {
  76. cfg.RedpandaBrokers = getEnvComma("REDPANDA_BROKERS", "localhost:9092")
  77. var err error
  78. rp, err = redpanda.NewClient(&redpanda.ClientConfig{
  79. Brokers: cfg.RedpandaBrokers,
  80. })
  81. if err != nil {
  82. return fmt.Errorf("redpanda: %v", err)
  83. }
  84. // Create topics
  85. topics := []string{"router-events", "router-commands"}
  86. for _, topic := range topics {
  87. err := rp.CreateTopic(topic, 1, 3)
  88. if err != nil && !schema.ErrTopicExists.Exists(err) {
  89. log.Printf("Topic %s: %v", topic, err)
  90. }
  91. }
  92. return nil
  93. }
  94. func getEnvComma(key, def string) []string {
  95. val := os.Getenv(key)
  96. if val == "" {
  97. return []string{def}
  98. }
  99. return []string{val}
  100. }
  101. func getEnvStr(key, def string) string {
  102. if val := os.Getenv(key); val != "" {
  103. return val
  104. }
  105. return def
  106. }
  107. func getEnvInt(key string, def int) int {
  108. if val := os.Getenv(key); val != "" {
  109. var v int
  110. fmt.Sscanf(val, "%d", &v)
  111. return v
  112. }
  113. return def
  114. }
  115. // Publish event to Redpanda
  116. func publishEvent(event RouterEvent) error {
  117. data, _ := json.Marshal(event)
  118. return rp.Produce("router-events", []byte(event.ID), data)
  119. }
  120. // Publish command to Redpanda
  121. func publishCommand(cmd RouterCommand) error {
  122. data, _ := json.Marshal(cmd)
  123. return rp.Produce("router-commands", []byte(cmd.ID), data)
  124. }
  125. // WebSocket handler
  126. func handleWebSocket(w http.ResponseWriter, r *http.Request) {
  127. token := r.URL.Query().Get("token")
  128. if token != cfg.Token {
  129. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  130. return
  131. }
  132. conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
  133. CompressionMode: websocket.CompressionContextTakeover,
  134. })
  135. if err != nil {
  136. log.Printf("WS accept: %v", err)
  137. return
  138. }
  139. defer conn.Close(websocket.StatusNormalClosure, "")
  140. ctx := context.Background()
  141. // Read router registration
  142. var regMsg RouterEvent
  143. err = conn.Read(ctx, &regMsg)
  144. if err != nil {
  145. log.Printf("WS read reg: %v", err)
  146. return
  147. }
  148. routerID := regMsg.RouterID
  149. if routerID == "" {
  150. routerID = r.RemoteAddr
  151. }
  152. routers[routerID] = &Router{
  153. ID: routerID,
  154. LastSeen: time.Now(),
  155. Conn: conn,
  156. Connected: true,
  157. }
  158. log.Printf("Router connected: %s", routerID)
  159. // Message loop
  160. for {
  161. var event RouterEvent
  162. err := conn.Read(ctx, &event)
  163. if err != nil {
  164. break
  165. }
  166. event.ID = uuid.New().String()
  167. event.ReceivedAt = time.Now()
  168. event.Connection = "websocket"
  169. // Check if this is a command result
  170. if event.EventType == "command_result" {
  171. // Find pending command and send result
  172. if cmdID := event.Payload["command_id"]; cmdID != nil {
  173. cmdIDstr, _ := cmdID.(string)
  174. if ch, ok := pendingCommands[cmdIDstr]; ok {
  175. result := CommandResult{
  176. Success: event.Payload["success"] == true,
  177. Output: func() string { s, _ := event.Payload["output"].(string); return s }(),
  178. Error: func() string { s, _ := event.Payload["error"].(string); return s }(),
  179. }
  180. ch <- result
  181. }
  182. }
  183. }
  184. // Publish to Redpanda
  185. if err := publishEvent(event); err != nil {
  186. log.Printf("Publish error: %v", err)
  187. }
  188. log.Printf("[%s] %s", routerID, event.EventType)
  189. routers[routerID].LastSeen = time.Now()
  190. }
  191. if routers[routerID] != nil {
  192. routers[routerID].Connected = false
  193. }
  194. log.Printf("Router disconnected: %s", routerID)
  195. }
  196. // HTTP Event webhook
  197. func handleHTTPEvent(w http.ResponseWriter, r *http.Request) {
  198. if r.Method != "POST" {
  199. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  200. return
  201. }
  202. token := r.Header.Get("Authorization")
  203. if token != "Bearer "+cfg.Token && token != cfg.Token {
  204. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  205. return
  206. }
  207. var event RouterEvent
  208. if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
  209. http.Error(w, "Invalid JSON", http.StatusBadRequest)
  210. return
  211. }
  212. event.ID = uuid.New().String()
  213. event.ReceivedAt = time.Now()
  214. event.Connection = "http"
  215. if err := publishEvent(event); err != nil {
  216. w.WriteHeader(http.StatusInternalServerError)
  217. return
  218. }
  219. json.NewEncoder(w).Encode(map[string]string{"event_id": event.ID})
  220. }
  221. // Get routers
  222. func handleRouters(w http.ResponseWriter, r *http.Request) {
  223. list := []map[string]interface{}{}
  224. for id, router := range routers {
  225. list = append(list, map[string]interface{}{
  226. "id": id,
  227. "last_seen": router.LastSeen,
  228. "online": time.Since(router.LastSeen) < 60*time.Second,
  229. })
  230. }
  231. json.NewEncoder(w).Encode(map[string]interface{}{"routers": list})
  232. }
  233. // Send command and wait for result
  234. func handleCommand(w http.ResponseWriter, r *http.Request) {
  235. if r.Method != "POST" {
  236. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  237. return
  238. }
  239. var cmd RouterCommand
  240. if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
  241. http.Error(w, "Invalid JSON", http.StatusBadRequest)
  242. return
  243. }
  244. routerID := r.URL.Query().Get("router_id")
  245. if routerID == "" {
  246. routerID = cmd.RouterID
  247. }
  248. if routerID == "" {
  249. http.Error(w, "router_id required", http.StatusBadRequest)
  250. return
  251. }
  252. router := routers[routerID]
  253. if router == nil || !router.Connected {
  254. http.Error(w, "Router not connected", http.StatusServiceUnavailable)
  255. return
  256. }
  257. // Create result channel
  258. resultChan := make(chan CommandResult, 1)
  259. cmd.ID = uuid.New().String()
  260. cmd.RouterID = routerID
  261. cmd.SentAt = time.Now()
  262. // Store pending command
  263. pendingCommands[cmd.ID] = resultChan
  264. if err := publishCommand(cmd); err != nil {
  265. delete(pendingCommands, cmd.ID)
  266. log.Printf("Publish command: %v", err)
  267. http.Error(w, err.Error(), http.StatusInternalServerError)
  268. return
  269. }
  270. log.Printf("Command to %s: %s (waiting...)", routerID, cmd.Command)
  271. // Wait for result with timeout
  272. select {
  273. case result := <-resultChan:
  274. delete(pendingCommands, cmd.ID)
  275. json.NewEncoder(w).Encode(map[string]interface{}{
  276. "command_id": cmd.ID,
  277. "status": "completed",
  278. "success": result.Success,
  279. "output": result.Output,
  280. "error": result.Error,
  281. })
  282. case <-time.After(commandTimeout):
  283. delete(pendingCommands, cmd.ID)
  284. json.NewEncoder(w).Encode(map[string]string{
  285. "command_id": cmd.ID,
  286. "status": "timeout",
  287. "error": "Router did not respond",
  288. })
  289. }
  290. }
  291. // Health
  292. func handleHealth(w http.ResponseWriter, r *http.Request) {
  293. json.NewEncoder(w).Encode(map[string]interface{}{
  294. "status": "ok",
  295. "routers": len(routers),
  296. })
  297. }
  298. func main() {
  299. cfg.Token = getEnvStr("TOKEN", cfg.Token)
  300. cfg.WebsocketPort = getEnvInt("PORT", cfg.WebsocketPort)
  301. log.SetFlags(log.LstdFlags | log.Lshortfile)
  302. log.Printf("=== client2server Go Server ===")
  303. log.Printf("WebSocket: ws://localhost:%d", cfg.WebsocketPort)
  304. if err := initRedpanda(); err != nil {
  305. log.Printf("Redpanda init failed: %v", err)
  306. }
  307. http.HandleFunc("/", handleHealth)
  308. http.HandleFunc("/health", handleHealth)
  309. http.HandleFunc("/api/events", handleHTTPEvent)
  310. http.HandleFunc("/api/events/", handleHTTPEvent)
  311. http.HandleFunc("/api/routers", handleRouters)
  312. http.HandleFunc("/api/command", handleCommand)
  313. http.HandleFunc("/ws", handleWebSocket)
  314. go func() {
  315. sigCh := make(chan os.Signal, 1)
  316. signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
  317. <-sigCh
  318. log.Println("Shutting down...")
  319. for _, router := range routers {
  320. router.Conn.Close(websocket.StatusNormalClosure, "server shutdown")
  321. }
  322. os.Exit(0)
  323. }()
  324. log.Printf("Server ready on port %d", cfg.WebsocketPort)
  325. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", cfg.WebsocketPort), nil))
  326. }