-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
245 lines (202 loc) · 5.97 KB
/
server.go
File metadata and controls
245 lines (202 loc) · 5.97 KB
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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
"time"
)
// Server is the control API server.
type Server struct {
store *SessionStore
mux *http.ServeMux
}
// NewServer creates a new control API server.
func NewServer(store *SessionStore) *Server {
s := &Server{store: store}
s.mux = http.NewServeMux()
s.mux.HandleFunc("GET /health", s.handleHealth)
s.mux.HandleFunc("POST /sessions", s.handleCreateSession)
s.mux.HandleFunc("GET /sessions/{id}", s.handleGetSession)
s.mux.HandleFunc("POST /sessions/{id}/rules", s.handleAddRules)
s.mux.HandleFunc("POST /sessions/{id}/actions", s.handleAction)
s.mux.HandleFunc("GET /sessions/{id}/log", s.handleGetLog)
s.mux.HandleFunc("DELETE /sessions/{id}", s.handleDeleteSession)
return s
}
// ServeHTTP implements http.Handler.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.mux.ServeHTTP(w, r)
}
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Server) handleCreateSession(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
writeError(w, http.StatusBadRequest, "failed to read request body")
return
}
var req CreateSessionRequest
if err := json.Unmarshal(body, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return
}
if req.Port < 0 {
writeError(w, http.StatusBadRequest, "port must be non-negative (0 for auto-assign)")
return
}
if req.Target.RealtimeHost == "" && req.Target.RestHost == "" {
writeError(w, http.StatusBadRequest, "target must have at least one of realtimeHost or restHost")
return
}
timeoutMs := req.TimeoutMs
if timeoutMs <= 0 {
timeoutMs = 30000
}
// Parse rules
var rules []*Rule
if len(req.Rules) > 0 {
if err := json.Unmarshal(req.Rules, &rules); err != nil {
writeError(w, http.StatusBadRequest, "invalid rules: "+err.Error())
return
}
}
session := &Session{
ID: GenerateID(),
Target: req.Target,
Rules: rules,
EventLog: NewEventLog(),
timeoutMs: timeoutMs,
}
// Attempt to bind the port (port 0 means auto-assign)
actualPort, err := StartSessionListener(session, req.Port)
if err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
// Set up auto-cleanup timer
session.timeoutTimer = time.AfterFunc(time.Duration(timeoutMs)*time.Millisecond, func() {
log.Printf("session %s timed out after %dms, cleaning up", session.ID, timeoutMs)
s.cleanupSession(session.ID)
})
s.store.Create(session)
resp := CreateSessionResponse{
SessionID: session.ID,
Proxy: ProxyConfig{
Host: fmt.Sprintf("localhost:%d", actualPort),
Port: actualPort,
},
}
log.Printf("created session %s on port %d (timeout %dms, %d rules)",
session.ID, actualPort, timeoutMs, len(rules))
writeJSON(w, http.StatusCreated, resp)
}
func (s *Server) handleGetSession(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
session, ok := s.store.Get(id)
if !ok {
writeError(w, http.StatusNotFound, "session not found")
return
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"sessionId": session.ID,
"port": session.Port,
"target": session.Target,
"ruleCount": session.RuleCount(),
})
}
func (s *Server) handleAddRules(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
session, ok := s.store.Get(id)
if !ok {
writeError(w, http.StatusNotFound, "session not found")
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
writeError(w, http.StatusBadRequest, "failed to read request body")
return
}
var req AddRulesRequest
if err := json.Unmarshal(body, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return
}
var rules []*Rule
if err := json.Unmarshal(req.Rules, &rules); err != nil {
writeError(w, http.StatusBadRequest, "invalid rules: "+err.Error())
return
}
prepend := strings.EqualFold(req.Position, "prepend")
session.AddRules(rules, prepend)
session.ResetTimeout()
writeJSON(w, http.StatusOK, map[string]int{"ruleCount": session.RuleCount()})
}
func (s *Server) handleAction(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
session, ok := s.store.Get(id)
if !ok {
writeError(w, http.StatusNotFound, "session not found")
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
writeError(w, http.StatusBadRequest, "failed to read request body")
return
}
var req ActionRequest
if err := json.Unmarshal(body, &req); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON: "+err.Error())
return
}
session.ResetTimeout()
if err := ExecuteImperativeAction(session, req); err != nil {
writeError(w, http.StatusConflict, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Server) handleGetLog(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
session, ok := s.store.Get(id)
if !ok {
writeError(w, http.StatusNotFound, "session not found")
return
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"events": session.EventLog.Events(),
})
}
func (s *Server) handleDeleteSession(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
events := s.cleanupSession(id)
if events == nil {
writeError(w, http.StatusNotFound, "session not found")
return
}
writeJSON(w, http.StatusOK, map[string]interface{}{
"events": events,
})
}
func (s *Server) cleanupSession(id string) []Event {
session, ok := s.store.Delete(id)
if !ok {
return nil
}
log.Printf("cleaning up session %s on port %d", session.ID, session.Port)
StopSessionListener(session)
session.Close()
return session.EventLog.Events()
}
// -- helpers --
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}