Repository navigation
Expand file tree
/
Copy pathclient_cache_test.go
More file actions
250 lines (201 loc) · 7.83 KB
/
Copy pathclient_cache_test.go
File metadata and controls
250 lines (201 loc) · 7.83 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
package mcpgrafana
import (
"context"
"net/http"
"net/url"
"sync"
"testing"
"github.com/grafana/incident-go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/metric/metricdata"
)
func TestClientCache_GrafanaClient(t *testing.T) {
cache := NewClientCache(nil)
defer cache.Close()
key := clientCacheKey{url: "http://localhost:3000", apiKey: "test-key", orgID: 1}
createCount := 0
createFn := func() *GrafanaClient {
createCount++
return &GrafanaClient{}
}
// First call should create
client1 := cache.GetOrCreateGrafanaClient(key, createFn)
require.NotNil(t, client1)
assert.Equal(t, 1, createCount)
// Second call with same key should return cached
client2 := cache.GetOrCreateGrafanaClient(key, createFn)
assert.Same(t, client1, client2)
assert.Equal(t, 1, createCount, "createFn should not be called again for same key")
// Different key should create new client
key2 := clientCacheKey{url: "http://other:3000", apiKey: "other-key", orgID: 2}
client3 := cache.GetOrCreateGrafanaClient(key2, createFn)
require.NotNil(t, client3)
assert.NotSame(t, client1, client3)
assert.Equal(t, 2, createCount)
g, _, _ := cache.Size()
assert.Equal(t, 2, g)
}
func TestClientCache_IncidentClient(t *testing.T) {
cache := NewClientCache(nil)
defer cache.Close()
key := clientCacheKey{url: "http://localhost:3000", apiKey: "test-key", orgID: 1}
createCount := 0
createFn := func() *incident.Client {
createCount++
return incident.NewClient("http://localhost:3000/api/plugins/grafana-irm-app/resources/api/v1/", "test-key")
}
client1 := cache.GetOrCreateIncidentClient(key, createFn)
require.NotNil(t, client1)
assert.Equal(t, 1, createCount)
client2 := cache.GetOrCreateIncidentClient(key, createFn)
assert.Same(t, client1, client2)
assert.Equal(t, 1, createCount)
_, i, _ := cache.Size()
assert.Equal(t, 1, i)
}
func TestClientCache_ConcurrentAccess(t *testing.T) {
cache := NewClientCache(nil)
defer cache.Close()
key := clientCacheKey{url: "http://localhost:3000", apiKey: "test-key", orgID: 1}
var mu sync.Mutex
createCount := 0
createFn := func() *GrafanaClient {
mu.Lock()
createCount++
mu.Unlock()
return &GrafanaClient{}
}
const numGoroutines = 50
var wg sync.WaitGroup
wg.Add(numGoroutines)
clients := make([]*GrafanaClient, numGoroutines)
for i := 0; i < numGoroutines; i++ {
go func(idx int) {
defer wg.Done()
clients[idx] = cache.GetOrCreateGrafanaClient(key, createFn)
}(i)
}
wg.Wait()
// All goroutines should get the same client
for i := 1; i < numGoroutines; i++ {
assert.Same(t, clients[0], clients[i], "All goroutines should get the same cached client")
}
// createFn should be called exactly once
assert.Equal(t, 1, createCount, "Client should be created exactly once")
}
func TestClientCache_DifferentCredentials(t *testing.T) {
cache := NewClientCache(nil)
defer cache.Close()
keys := []clientCacheKey{
{url: "http://host1:3000", apiKey: "key1", orgID: 1, forwardedHeaders: "X-WEBAUTH-USER=admin"}, // base key
{url: "http://host1:3000", apiKey: "key2", orgID: 1, forwardedHeaders: "X-WEBAUTH-USER=admin"}, // different key
{url: "http://host1:3000", apiKey: "key1", orgID: 2, forwardedHeaders: "X-WEBAUTH-USER=admin"}, // different org
{url: "http://host2:3000", apiKey: "key1", orgID: 1, forwardedHeaders: "X-WEBAUTH-USER=admin"}, // different url
{url: "http://host1:3000", apiKey: "key1", orgID: 1, forwardedHeaders: "X-WEBAUTH-USER=admin"}, // same as first
{url: "http://host1:3000", apiKey: "key1", orgID: 1, forwardedHeaders: "X-WEBAUTH-USER=john.doe"}, // different user
}
const numUniqueKeys = 5
clients := make([]*GrafanaClient, len(keys))
for i, key := range keys {
clients[i] = cache.GetOrCreateGrafanaClient(key, func() *GrafanaClient {
return &GrafanaClient{}
})
}
// First and last should be the same (same key)
assert.Same(t, clients[0], clients[4])
// All others should be different
assert.NotSame(t, clients[0], clients[1])
assert.NotSame(t, clients[0], clients[2])
assert.NotSame(t, clients[0], clients[3])
assert.NotSame(t, clients[0], clients[5])
g, _, _ := cache.Size()
assert.Equal(t, numUniqueKeys, g) // 5 unique keys
}
func TestCacheKeyFromRequest(t *testing.T) {
key1 := cacheKeyFromRequest("http://localhost:3000", "key1", nil, 1, nil)
key2 := cacheKeyFromRequest("http://localhost:3000", "key1", nil, 1, nil)
assert.Equal(t, key1, key2)
key3 := cacheKeyFromRequest("http://localhost:3000", "key1", url.UserPassword("admin", "pass"), 1, nil)
assert.NotEqual(t, key1, key3)
assert.Equal(t, "admin", key3.username)
assert.Equal(t, "pass", key3.password)
}
func TestClientCache_Close(t *testing.T) {
cache := NewClientCache(nil)
key := clientCacheKey{url: "http://localhost:3000", apiKey: "key", orgID: 1}
cache.GetOrCreateGrafanaClient(key, func() *GrafanaClient {
return &GrafanaClient{}
})
cache.GetOrCreateIncidentClient(key, func() *incident.Client {
return incident.NewClient("http://localhost:3000/incident", "key")
})
g, i, _ := cache.Size()
assert.Equal(t, 1, g)
assert.Equal(t, 1, i)
cache.Close()
g, i, _ = cache.Size()
assert.Equal(t, 0, g)
assert.Equal(t, 0, i)
}
// TestClientCache_MetricsUseInjectedMeterProvider verifies that
// WithClientCacheMeterProvider routes the cache's instruments to the given
// provider instead of the (possibly noop) global one, so metrics reach a
// scrapeable registry in deployments that reset otel.GetMeterProvider() for
// reasons unrelated to mcp-grafana (see issue #1072).
type closeCountingTransport struct {
http.RoundTripper
closed int
}
func (t *closeCountingTransport) CloseIdleConnections() { t.closed++ }
func TestClientCache_EvictsLeastRecentlyUsed(t *testing.T) {
cache := NewClientCache(nil)
defer cache.Close()
keyFor := func(i int) clientCacheKey {
return clientCacheKey{url: "http://localhost:3000", orgID: int64(i)}
}
first := &closeCountingTransport{}
cache.GetOrCreateIncidentClient(keyFor(0), func() *incident.Client {
return &incident.Client{HTTPClient: &http.Client{Transport: first}}
})
for i := 0; i <= clientCacheMaxSize; i++ {
cache.GetOrCreateGrafanaClient(keyFor(i), func() *GrafanaClient { return &GrafanaClient{} })
}
for i := 1; i <= clientCacheMaxSize; i++ {
cache.GetOrCreateIncidentClient(keyFor(i), func() *incident.Client { return &incident.Client{} })
}
grafana, incidentCount, _ := cache.Size()
assert.Equal(t, clientCacheMaxSize, grafana)
assert.Equal(t, clientCacheMaxSize, incidentCount)
assert.Equal(t, 1, first.closed, "evicted incident client should have idle connections closed")
// The oldest Grafana client was evicted and is recreated on the next lookup.
created := false
cache.GetOrCreateGrafanaClient(keyFor(0), func() *GrafanaClient { created = true; return &GrafanaClient{} })
assert.True(t, created)
}
func TestClientCache_MetricsUseInjectedMeterProvider(t *testing.T) {
reader := sdkmetric.NewManualReader()
provider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
cache := NewClientCache(nil, WithClientCacheMeterProvider(provider))
defer cache.Close()
key := clientCacheKey{url: "http://localhost:3000", apiKey: "key", orgID: 1}
cache.GetOrCreateGrafanaClient(key, func() *GrafanaClient {
return &GrafanaClient{}
})
// Second lookup for the same key should record a hit.
cache.GetOrCreateGrafanaClient(key, func() *GrafanaClient {
return &GrafanaClient{}
})
var data metricdata.ResourceMetrics
require.NoError(t, reader.Collect(context.Background(), &data))
require.Len(t, data.ScopeMetrics, 1)
names := make(map[string]bool)
for _, m := range data.ScopeMetrics[0].Metrics {
names[m.Name] = true
}
assert.True(t, names["mcp.client_cache.lookups"])
assert.True(t, names["mcp.client_cache.hits"])
assert.True(t, names["mcp.client_cache.misses"])
assert.True(t, names["mcp.client_cache.size"])
}