-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrol_pool.go
More file actions
381 lines (330 loc) · 8.79 KB
/
control_pool.go
File metadata and controls
381 lines (330 loc) · 8.79 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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package sprites
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"sync"
"time"
"github.com/gorilla/websocket"
)
const (
// maxPoolSize is a sanity cap; checkout fails if pool is full
maxPoolSize = 100
// poolDrainThreshold: when checkin and size > this, drain idle conns
poolDrainThreshold = 20
// poolDrainTarget: drain down to this many conns when draining
poolDrainTarget = 10
dialTimeout = 5 * time.Second
keepAliveWindow = 30 * time.Second
)
// controlPool manages a pool of control WebSocket connections for a sprite
type controlPool struct {
client *Client
spriteName string
mu sync.Mutex
conns []*controlConn
pendingDials int // number of dials in progress (outside lock)
closed bool
}
// controlConn represents a control WebSocket connection
type controlConn struct {
ws *websocket.Conn
mu sync.Mutex
busy bool
lastUsed time.Time
ctx context.Context
cancel context.CancelFunc
readCh chan controlMessage
closedCh chan struct{}
closeOnce sync.Once
}
// controlMessage represents a message on the control connection
type controlMessage struct {
MessageType int // WebSocket message type (binary or text)
Data []byte // Raw message data
}
// newControlPool creates a new control connection pool for a sprite
func newControlPool(client *Client, spriteName string) *controlPool {
return &controlPool{
client: client,
spriteName: spriteName,
conns: make([]*controlConn, 0, 32),
}
}
// checkout gets an idle connection from the pool, or creates a new one if needed.
// Dials happen outside the pool lock to avoid blocking all other checkout/checkin
// operations during network I/O (up to 5s).
func (p *controlPool) checkout(ctx context.Context) (*controlConn, error) {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return nil, fmt.Errorf("pool is closed")
}
// Try to find an idle connection
for i, conn := range p.conns {
conn.mu.Lock()
if !conn.busy {
// Check if connection is still alive
select {
case <-conn.closedCh:
// Connection is closed, remove it
conn.mu.Unlock()
p.conns = append(p.conns[:i], p.conns[i+1:]...)
dbg("sprites: removed closed control conn", "sprite", p.spriteName, "pool", len(p.conns))
continue
default:
}
conn.busy = true
conn.mu.Unlock()
dbg("sprites: checkout control conn", "sprite", p.spriteName, "pool", len(p.conns))
p.mu.Unlock()
return conn, nil
}
conn.mu.Unlock()
}
// No idle connections — check if we can dial a new one
if len(p.conns)+p.pendingDials >= maxPoolSize {
p.mu.Unlock()
return nil, fmt.Errorf("no available connections in pool (at cap %d)", maxPoolSize)
}
// Reserve a slot and release the lock before dialing
p.pendingDials++
p.mu.Unlock()
conn, err := p.dial(ctx)
// Re-acquire lock to update pool state
p.mu.Lock()
p.pendingDials--
if err != nil {
p.mu.Unlock()
return nil, err
}
// Check if pool was closed while we were dialing
if p.closed {
p.mu.Unlock()
conn.close()
return nil, fmt.Errorf("pool closed during dial")
}
conn.busy = true
p.conns = append(p.conns, conn)
dbg("sprites: dialed new control conn", "sprite", p.spriteName, "pool", len(p.conns))
p.mu.Unlock()
return conn, nil
}
// checkin returns a connection to the pool and may drain idle conns if pool is large
func (p *controlPool) checkin(conn *controlConn) {
if conn == nil {
return
}
conn.mu.Lock()
conn.busy = false
conn.lastUsed = time.Now()
conn.mu.Unlock()
dbg("sprites: checkin control conn", "sprite", p.spriteName, "idle_at", conn.lastUsed.Unix())
p.mu.Lock()
p.tryDrainLocked()
p.mu.Unlock()
}
// tryDrainLocked removes idle connections when the pool is large and idle.
// Caller must hold p.mu.
func (p *controlPool) tryDrainLocked() {
if p.closed || len(p.conns) <= poolDrainThreshold {
return
}
type idleConn struct {
conn *controlConn
lastUsed time.Time
}
var idles []idleConn
for _, c := range p.conns {
c.mu.Lock()
if !c.busy {
select {
case <-c.closedCh:
c.mu.Unlock()
continue
default:
}
idles = append(idles, idleConn{conn: c, lastUsed: c.lastUsed})
}
c.mu.Unlock()
}
toClose := len(p.conns) - poolDrainTarget
if toClose <= 0 || len(idles) == 0 {
return
}
if toClose > len(idles) {
toClose = len(idles)
}
sort.Slice(idles, func(i, j int) bool { return idles[i].lastUsed.Before(idles[j].lastUsed) })
closeSet := make(map[*controlConn]bool, toClose)
for i := 0; i < toClose; i++ {
closeSet[idles[i].conn] = true
}
for _, c := range p.conns {
if closeSet[c] {
c.close()
}
}
newConns := make([]*controlConn, 0, len(p.conns)-toClose)
for _, c := range p.conns {
if !closeSet[c] {
newConns = append(newConns, c)
}
}
p.conns = newConns
dbg("sprites: drained control pool", "sprite", p.spriteName, "pool_size", len(p.conns))
}
// dial creates a new control WebSocket connection
func (p *controlPool) dial(ctx context.Context) (*controlConn, error) {
wsURL, err := p.buildControlURL()
if err != nil {
return nil, err
}
// Set up WebSocket dialer
dialer := &websocket.Dialer{
ReadBufferSize: 1024 * 1024, // 1MB
WriteBufferSize: 1024 * 1024, // 1MB
HandshakeTimeout: dialTimeout,
}
// Add TLS config if needed
if wsURL.Scheme == "wss" {
dialer.TLSClientConfig = &tls.Config{
InsecureSkipVerify: false,
}
}
// Set headers including auth and feature flag
header := http.Header{}
header.Set("Authorization", fmt.Sprintf("Bearer %s", p.client.token))
header.Set("User-Agent", "sprites-go-sdk/1.0")
// Connect to WebSocket
ws, resp, err := dialer.DialContext(ctx, wsURL.String(), header)
if err != nil {
// Enrich error with HTTP status/body when available
if resp != nil {
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
return nil, fmt.Errorf("failed to dial control connection: %v (HTTP %d: %s)", err, resp.StatusCode, string(body))
}
return nil, fmt.Errorf("failed to dial control connection: %v", err)
}
connCtx, cancel := context.WithCancel(context.Background())
conn := &controlConn{
ws: ws,
lastUsed: time.Now(),
ctx: connCtx,
cancel: cancel,
readCh: make(chan controlMessage, 1000), // Large buffer to prevent blocking
closedCh: make(chan struct{}),
}
// Start read loop
go conn.readLoop()
dbg("sprites: created control conn", "sprite", p.spriteName, "pool_size", len(p.conns)+1)
return conn, nil
}
// buildControlURL builds the WebSocket URL for the control endpoint
func (p *controlPool) buildControlURL() (*url.URL, error) {
baseURL := p.client.baseURL
// Convert HTTP(S) to WS(S)
if len(baseURL) >= 4 && baseURL[:4] == "http" {
baseURL = "ws" + baseURL[4:]
}
// Parse base URL
u, err := url.Parse(baseURL)
if err != nil {
return nil, fmt.Errorf("invalid base URL: %w", err)
}
// Build path (no keep_alive in URL - that's in operation params)
u.Path = fmt.Sprintf("/v1/sprites/%s/control", p.spriteName)
return u, nil
}
// close closes all connections in the pool
func (p *controlPool) close() {
p.mu.Lock()
defer p.mu.Unlock()
p.closed = true
for _, conn := range p.conns {
conn.close()
}
p.conns = nil
}
// readLoop continuously reads messages from the control connection
func (c *controlConn) readLoop() {
defer func() {
c.closeOnce.Do(func() {
close(c.closedCh)
})
}()
for {
select {
case <-c.ctx.Done():
return
default:
}
// Read next message (could be JSON or binary)
messageType, data, err := c.ws.ReadMessage()
if err != nil {
// Connection closed or error
return
}
// Create message wrapper
msg := controlMessage{
MessageType: messageType,
Data: data,
}
// Check if connection is busy (in use by an operation)
c.mu.Lock()
busy := c.busy
c.mu.Unlock()
if busy {
// Connection is busy - forward message to operation
select {
case c.readCh <- msg:
case <-c.ctx.Done():
return
}
} else {
// Connection is idle - handle control messages
if messageType == websocket.TextMessage {
// Try to parse as control message
var ctrlMsg struct {
Type string `json:"type"`
}
if json.Unmarshal(data, &ctrlMsg) == nil {
switch ctrlMsg.Type {
case "dial":
// Server is requesting a new connection - ignore in SDK
case "keepalive":
// Keepalive message - stay alive
default:
// Unknown message type
}
}
}
// Binary messages while idle are unexpected, ignore
}
}
}
// close closes the control connection
func (c *controlConn) close() {
c.closeOnce.Do(func() {
c.cancel()
if c.ws != nil {
c.ws.Close()
}
close(c.closedCh)
})
}
// sendRelease sends a release message to return the connection to the pool
func (c *controlConn) sendRelease() error {
c.mu.Lock()
defer c.mu.Unlock()
msg := map[string]interface{}{
"type": "release",
}
return c.ws.WriteJSON(msg)
}