-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrusera.go
More file actions
218 lines (180 loc) · 4.71 KB
/
trusera.go
File metadata and controls
218 lines (180 loc) · 4.71 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
package trusera
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"sync"
"time"
)
const (
defaultBaseURL = "https://api.trusera.io"
defaultFlushInterval = 30 * time.Second
defaultBatchSize = 100
)
// Client sends agent events to Trusera API
type Client struct {
apiKey string
baseURL string
agentID string
httpClient *http.Client
events []Event
mu sync.Mutex
flushSize int
done chan struct{}
ticker *time.Ticker
wg sync.WaitGroup
}
// Option configures a Client
type Option func(*Client)
// WithBaseURL sets the Trusera API base URL
func WithBaseURL(url string) Option {
return func(c *Client) {
c.baseURL = url
}
}
// WithAgentID sets the agent identifier
func WithAgentID(id string) Option {
return func(c *Client) {
c.agentID = id
}
}
// WithFlushInterval sets how often to auto-flush events
func WithFlushInterval(d time.Duration) Option {
return func(c *Client) {
if c.ticker != nil {
c.ticker.Stop()
}
c.ticker = time.NewTicker(d)
}
}
// WithBatchSize sets the max events before auto-flush
func WithBatchSize(n int) Option {
return func(c *Client) {
if n > 0 {
c.flushSize = n
}
}
}
// NewClient creates a Trusera monitoring client
func NewClient(apiKey string, opts ...Option) *Client {
c := &Client{
apiKey: apiKey,
baseURL: defaultBaseURL,
httpClient: &http.Client{Timeout: 10 * time.Second},
events: make([]Event, 0, defaultBatchSize),
flushSize: defaultBatchSize,
done: make(chan struct{}),
ticker: time.NewTicker(defaultFlushInterval),
}
for _, opt := range opts {
opt(c)
}
c.wg.Add(1)
go c.backgroundFlusher()
return c
}
// backgroundFlusher periodically flushes events
func (c *Client) backgroundFlusher() {
defer c.wg.Done()
for {
select {
case <-c.ticker.C:
_ = c.Flush()
case <-c.done:
return
}
}
}
// Track queues an event for sending
func (c *Client) Track(event Event) {
c.mu.Lock()
defer c.mu.Unlock()
c.events = append(c.events, event)
if len(c.events) >= c.flushSize {
go func() {
_ = c.Flush()
}()
}
}
// Flush sends all queued events to the API
func (c *Client) Flush() error {
c.mu.Lock()
if len(c.events) == 0 {
c.mu.Unlock()
return nil
}
events := make([]Event, len(c.events))
copy(events, c.events)
c.events = c.events[:0]
c.mu.Unlock()
payload := map[string]interface{}{
"agent_id": c.agentID,
"events": events,
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("failed to marshal events: %w", err)
}
req, err := http.NewRequest(http.MethodPost, c.baseURL+"/v1/events", bytes.NewReader(body)) // #nosec G704 -- URL built from operator-configured baseURL, not user-controlled input
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.apiKey)
resp, err := c.httpClient.Do(req) // #nosec G704 -- same taint origin: operator-configured baseURL
if err != nil {
return fmt.Errorf("failed to send events: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= 400 {
return fmt.Errorf("API returned status %d", resp.StatusCode)
}
return nil
}
// RegisterAgent registers an agent with Trusera, returns agent ID
func (c *Client) RegisterAgent(name, framework string) (string, error) {
if name == "" {
return "", errors.New("agent name is required")
}
payload := map[string]string{
"name": name,
"framework": framework,
}
body, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("failed to marshal payload: %w", err)
}
req, err := http.NewRequest(http.MethodPost, c.baseURL+"/v1/agents", bytes.NewReader(body)) // #nosec G704 -- URL built from operator-configured baseURL, not user-controlled input
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+c.apiKey)
resp, err := c.httpClient.Do(req) // #nosec G704 -- same taint origin: operator-configured baseURL
if err != nil {
return "", fmt.Errorf("failed to register agent: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= 400 {
return "", fmt.Errorf("API returned status %d", resp.StatusCode)
}
var result struct {
AgentID string `json:"agent_id"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("failed to decode response: %w", err)
}
c.mu.Lock()
c.agentID = result.AgentID
c.mu.Unlock()
return result.AgentID, nil
}
// Close flushes remaining events and stops background goroutine
func (c *Client) Close() error {
c.ticker.Stop()
close(c.done)
c.wg.Wait()
return c.Flush()
}