main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. // Idempotency: track recently executed commands (command_id -> timestamp)
  74. var executedCommands = make(map[string]time.Time)
  75. const idempotencyTTL = 5 * 60 * time.Second // 5 minutes
  76. // Redpanda
  77. var rp *redpanda.Client
  78. func initRedpanda() error {
  79. cfg.RedpandaBrokers = getEnvComma("REDPANDA_BROKERS", "localhost:9092")
  80. var err error
  81. rp, err = redpanda.NewClient(&redpanda.ClientConfig{
  82. Brokers: cfg.RedpandaBrokers,
  83. })
  84. if err != nil {
  85. return fmt.Errorf("redpanda: %v", err)
  86. }
  87. // Create topics
  88. topics := []string{"router-events", "router-commands"}
  89. for _, topic := range topics {
  90. err := rp.CreateTopic(topic, 1, 3)
  91. if err != nil && !schema.ErrTopicExists.Exists(err) {
  92. log.Printf("Topic %s: %v", topic, err)
  93. }
  94. }
  95. return nil
  96. }
  97. func getEnvComma(key, def string) []string {
  98. val := os.Getenv(key)
  99. if val == "" {
  100. return []string{def}
  101. }
  102. return []string{val}
  103. }
  104. func getEnvStr(key, def string) string {
  105. if val := os.Getenv(key); val != "" {
  106. return val
  107. }
  108. return def
  109. }
  110. func getEnvInt(key string, def int) int {
  111. if val := os.Getenv(key); val != "" {
  112. var v int
  113. fmt.Sscanf(val, "%d", &v)
  114. return v
  115. }
  116. return def
  117. }
  118. // Publish event to Redpanda
  119. func publishEvent(event RouterEvent) error {
  120. data, _ := json.Marshal(event)
  121. return rp.Produce("router-events", []byte(event.ID), data)
  122. }
  123. // Publish command to Redpanda
  124. func publishCommand(cmd RouterCommand) error {
  125. data, _ := json.Marshal(cmd)
  126. return rp.Produce("router-commands", []byte(cmd.ID), data)
  127. }
  128. // WebSocket handler
  129. func handleWebSocket(w http.ResponseWriter, r *http.Request) {
  130. token := r.URL.Query().Get("token")
  131. if token != cfg.Token {
  132. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  133. return
  134. }
  135. conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
  136. CompressionMode: websocket.CompressionContextTakeover,
  137. })
  138. if err != nil {
  139. log.Printf("WS accept: %v", err)
  140. return
  141. }
  142. defer conn.Close(websocket.StatusNormalClosure, "")
  143. ctx := context.Background()
  144. // Read router registration
  145. var regMsg RouterEvent
  146. err = conn.Read(ctx, &regMsg)
  147. if err != nil {
  148. log.Printf("WS read reg: %v", err)
  149. return
  150. }
  151. routerID := regMsg.RouterID
  152. if routerID == "" {
  153. routerID = r.RemoteAddr
  154. }
  155. routers[routerID] = &Router{
  156. ID: routerID,
  157. LastSeen: time.Now(),
  158. Conn: conn,
  159. Connected: true,
  160. }
  161. log.Printf("Router connected: %s", routerID)
  162. // Message loop
  163. for {
  164. var event RouterEvent
  165. err := conn.Read(ctx, &event)
  166. if err != nil {
  167. break
  168. }
  169. event.ID = uuid.New().String()
  170. event.ReceivedAt = time.Now()
  171. event.Connection = "websocket"
  172. // Check if this is a command result
  173. if event.EventType == "command_result" {
  174. // Find pending command and send result
  175. if cmdID := event.Payload["command_id"]; cmdID != nil {
  176. cmdIDstr, _ := cmdID.(string)
  177. if ch, ok := pendingCommands[cmdIDstr]; ok {
  178. result := CommandResult{
  179. Success: event.Payload["success"] == true,
  180. Output: func() string { s, _ := event.Payload["output"].(string); return s }(),
  181. Error: func() string { s, _ := event.Payload["error"].(string); return s }(),
  182. }
  183. ch <- result
  184. }
  185. // Mark as executed (for idempotency)
  186. executedCommands[cmdIDstr] = time.Now()
  187. }
  188. }
  189. // Publish to Redpanda
  190. if err := publishEvent(event); err != nil {
  191. log.Printf("Publish error: %v", err)
  192. }
  193. log.Printf("[%s] %s", routerID, event.EventType)
  194. routers[routerID].LastSeen = time.Now()
  195. }
  196. if routers[routerID] != nil {
  197. routers[routerID].Connected = false
  198. }
  199. log.Printf("Router disconnected: %s", routerID)
  200. }
  201. // HTTP Event webhook
  202. func handleHTTPEvent(w http.ResponseWriter, r *http.Request) {
  203. if r.Method != "POST" {
  204. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  205. return
  206. }
  207. token := r.Header.Get("Authorization")
  208. if token != "Bearer "+cfg.Token && token != cfg.Token {
  209. http.Error(w, "Unauthorized", http.StatusUnauthorized)
  210. return
  211. }
  212. var event RouterEvent
  213. if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
  214. http.Error(w, "Invalid JSON", http.StatusBadRequest)
  215. return
  216. }
  217. event.ID = uuid.New().String()
  218. event.ReceivedAt = time.Now()
  219. event.Connection = "http"
  220. if err := publishEvent(event); err != nil {
  221. w.WriteHeader(http.StatusInternalServerError)
  222. return
  223. }
  224. json.NewEncoder(w).Encode(map[string]string{"event_id": event.ID})
  225. }
  226. // Get routers
  227. func handleRouters(w http.ResponseWriter, r *http.Request) {
  228. list := []map[string]interface{}{}
  229. for id, router := range routers {
  230. list = append(list, map[string]interface{}{
  231. "id": id,
  232. "last_seen": router.LastSeen,
  233. "online": time.Since(router.LastSeen) < 60*time.Second,
  234. })
  235. }
  236. json.NewEncoder(w).Encode(map[string]interface{}{"routers": list})
  237. }
  238. // Send command and wait for result
  239. func handleCommand(w http.ResponseWriter, r *http.Request) {
  240. if r.Method != "POST" {
  241. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  242. return
  243. }
  244. var cmd RouterCommand
  245. if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
  246. http.Error(w, "Invalid JSON", http.StatusBadRequest)
  247. return
  248. }
  249. routerID := r.URL.Query().Get("router_id")
  250. if routerID == "" {
  251. routerID = cmd.RouterID
  252. }
  253. if routerID == "" {
  254. http.Error(w, "router_id required", http.StatusBadRequest)
  255. return
  256. }
  257. router := routers[routerID]
  258. if router == nil || !router.Connected {
  259. http.Error(w, "Router not connected", http.StatusServiceUnavailable)
  260. return
  261. }
  262. // ──────────────────────────────────────────────────────────
  263. // IDEMPOTENCY CHECK - Dedup before publishing!
  264. // ──────────────────────────────────────────────────────────
  265. // If client provides an idempotency key, reuse it
  266. xecID := cmd.ID
  267. if xecID == "" {
  268. // New command ID acts as idempotency key
  269. xecID = uuid.New().String()
  270. }
  271. // Check if already executed within TTL
  272. if lastExec, exists := executedCommands[xecID]; exists {
  273. if time.Since(lastExec) < idempotencyTTL {
  274. log.Printf("Idempotent reject: %s (recently executed)", xecID)
  275. json.NewEncoder(w).Encode(map[string]interface{}{
  276. "idempotent_reject": true,
  277. "existing_command_id": xecID,
  278. "message": "Command already executed",
  279. })
  280. return
  281. }
  282. // Old entry, allow retry
  283. delete(executedCommands, xecID)
  284. }
  285. // Create result channel
  286. resultChan := make(chan CommandResult, 1)
  287. cmd.ID = xecID
  288. cmd.RouterID = routerID
  289. cmd.SentAt = time.Now()
  290. // Store pending command
  291. pendingCommands[cmd.ID] = resultChan
  292. if err := publishCommand(cmd); err != nil {
  293. delete(pendingCommands, cmd.ID)
  294. log.Printf("Publish command: %v", err)
  295. http.Error(w, err.Error(), http.StatusInternalServerError)
  296. return
  297. }
  298. log.Printf("Command to %s: %s (waiting...)", routerID, cmd.Command)
  299. // Wait for result with timeout
  300. select {
  301. case result := <-resultChan:
  302. delete(pendingCommands, cmd.ID)
  303. json.NewEncoder(w).Encode(map[string]interface{}{
  304. "command_id": cmd.ID,
  305. "status": "completed",
  306. "success": result.Success,
  307. "output": result.Output,
  308. "error": result.Error,
  309. })
  310. case <-time.After(commandTimeout):
  311. delete(pendingCommands, cmd.ID)
  312. json.NewEncoder(w).Encode(map[string]string{
  313. "command_id": cmd.ID,
  314. "status": "timeout",
  315. "error": "Router did not respond",
  316. })
  317. }
  318. // Also mark timeout for idempotency (allows retry after TTL)
  319. // executedCommands stays, will expire naturally
  320. }
  321. // Health
  322. func handleHealth(w http.ResponseWriter, r *http.Request) {
  323. json.NewEncoder(w).Encode(map[string]interface{}{
  324. "status": "ok",
  325. "routers": len(routers),
  326. })
  327. }
  328. func main() {
  329. cfg.Token = getEnvStr("TOKEN", cfg.Token)
  330. cfg.WebsocketPort = getEnvInt("PORT", cfg.WebsocketPort)
  331. log.SetFlags(log.LstdFlags | log.Lshortfile)
  332. log.Printf("=== client2server Go Server ===")
  333. log.Printf("WebSocket: ws://localhost:%d", cfg.WebsocketPort)
  334. if err := initRedpanda(); err != nil {
  335. log.Printf("Redpanda init failed: %v", err)
  336. }
  337. http.HandleFunc("/", handleHealth)
  338. http.HandleFunc("/health", handleHealth)
  339. http.HandleFunc("/api/events", handleHTTPEvent)
  340. http.HandleFunc("/api/events/", handleHTTPEvent)
  341. http.HandleFunc("/api/routers", handleRouters)
  342. http.HandleFunc("/api/command", handleCommand)
  343. http.HandleFunc("/ws", handleWebSocket)
  344. go func() {
  345. sigCh := make(chan os.Signal, 1)
  346. signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
  347. <-sigCh
  348. log.Println("Shutting down...")
  349. for _, router := range routers {
  350. router.Conn.Close(websocket.StatusNormalClosure, "server shutdown")
  351. }
  352. os.Exit(0)
  353. }()
  354. log.Printf("Server ready on port %d", cfg.WebsocketPort)
  355. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", cfg.WebsocketPort), nil))
  356. }