Skip to content

Commit f1ff766

Browse files
committed
Update examples to use simplified API and fix linting issues
- Updated all examples to use new config-based API instead of removed builder methods - Fixed compression examples to use WithCompression(&compression.Config{...}) - Fixed redis examples to use WithRedis(&obcache.RedisConfig{...}) - Fixed metrics examples to use WithMetrics(&obcache.MetricsConfig{...}) - Removed deprecated WithContext usage from examples - Fixed context parameter ordering in cache hit/miss functions - Removed unused test functions and imports - Cleaned up unused parameters in wrap functions All examples now compile and run correctly with the simplified API. All linting checks pass.
1 parent ea94008 commit f1ff766

9 files changed

Lines changed: 70 additions & 153 deletions

File tree

examples/advanced_hooks_example.go

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -127,29 +127,24 @@ func demonstrateHookComposition() {
127127
func testScenario1(cache *obcache.Cache) {
128128
fmt.Println("\n--- Scenario 1: Metrics key with production context ---")
129129

130-
prodCtx := context.WithValue(context.Background(), "env", "production")
131130
key := "metrics:api_requests"
132131

133132
// Set and get to trigger hooks
134133
_ = cache.Set(key, 150, time.Hour)
135-
_, _ = cache.Get(key, obcache.WithContext(prodCtx))
134+
_, _ = cache.Get(key)
136135

137136
// Test miss scenario
138-
_, _ = cache.Get("metrics:missing_key", obcache.WithContext(prodCtx))
137+
_, _ = cache.Get("metrics:missing_key")
139138
}
140139

141140
func testScenario2(cache *obcache.Cache) {
142141
fmt.Println("\n--- Scenario 2: Debug key with debug context ---")
143142

144-
debugCtx := context.WithValue(
145-
context.WithValue(context.Background(), "debug", true),
146-
"env", "staging",
147-
)
148143
key := "debug:session_data"
149144

150145
// Set and get to trigger hooks
151146
_ = cache.Set(key, map[string]string{"user": "alice", "session": "abc123"}, time.Hour)
152-
_, _ = cache.Get(key, obcache.WithContext(debugCtx))
147+
_, _ = cache.Get(key)
153148
}
154149

155150
func testScenario3(cache *obcache.Cache) {

examples/basic/basic

11.8 MB
Binary file not shown.

examples/compression/main.go

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -120,12 +120,15 @@ func noCompressionExample() {
120120

121121
func gzipCompressionExample() {
122122
// Create cache with gzip compression
123-
cache, err := obcache.New(obcache.NewDefaultConfig().
123+
config := obcache.NewDefaultConfig().
124124
WithMaxEntries(100).
125-
WithCompressionEnabled(true).
126-
WithCompressionAlgorithm(compression.CompressorGzip).
127-
WithCompressionMinSize(500). // Compress values larger than 500 bytes
128-
WithCompressionLevel(6)) // Balanced compression level
125+
WithCompression(&compression.Config{
126+
Enabled: true,
127+
Algorithm: compression.CompressorGzip,
128+
MinSize: 500, // Compress values larger than 500 bytes
129+
Level: 6, // Balanced compression level
130+
})
131+
cache, err := obcache.New(config)
129132
if err != nil {
130133
log.Fatalf("Failed to create cache: %v", err)
131134
}
@@ -171,12 +174,15 @@ func gzipCompressionExample() {
171174

172175
func deflateCompressionExample() {
173176
// Create cache with deflate compression
174-
cache, err := obcache.New(obcache.NewDefaultConfig().
177+
config := obcache.NewDefaultConfig().
175178
WithMaxEntries(100).
176-
WithCompressionEnabled(true).
177-
WithCompressionAlgorithm(compression.CompressorDeflate).
178-
WithCompressionMinSize(1000). // Higher threshold
179-
WithCompressionLevel(9)) // Maximum compression
179+
WithCompression(&compression.Config{
180+
Enabled: true,
181+
Algorithm: compression.CompressorDeflate,
182+
MinSize: 1000, // Higher threshold
183+
Level: 9, // Maximum compression
184+
})
185+
cache, err := obcache.New(config) // Maximum compression
180186
if err != nil {
181187
log.Fatalf("Failed to create cache: %v", err)
182188
}
@@ -212,11 +218,14 @@ func compressionThresholdExample() {
212218
for _, minSize := range testSizes {
213219
fmt.Printf("\n Testing with minimum size: %d bytes\n", minSize)
214220

215-
cache, err := obcache.New(obcache.NewDefaultConfig().
221+
config := obcache.NewDefaultConfig().
216222
WithMaxEntries(50).
217-
WithCompressionEnabled(true).
218-
WithCompressionAlgorithm(compression.CompressorGzip).
219-
WithCompressionMinSize(minSize))
223+
WithCompression(&compression.Config{
224+
Enabled: true,
225+
Algorithm: compression.CompressorGzip,
226+
MinSize: minSize,
227+
})
228+
cache, err := obcache.New(config)
220229
if err != nil {
221230
log.Printf("Failed to create cache: %v", err)
222231
continue
@@ -274,11 +283,14 @@ func performanceComparisonExample() {
274283
fmt.Printf(" Testing %d operations with gzip compression...\n", iterations)
275284
start = time.Now()
276285

277-
compressedCache, _ := obcache.New(obcache.NewDefaultConfig().
286+
config := obcache.NewDefaultConfig().
278287
WithMaxEntries(200).
279-
WithCompressionEnabled(true).
280-
WithCompressionAlgorithm(compression.CompressorGzip).
281-
WithCompressionMinSize(1000))
288+
WithCompression(&compression.Config{
289+
Enabled: true,
290+
Algorithm: compression.CompressorGzip,
291+
MinSize: 1000,
292+
})
293+
compressedCache, _ := obcache.New(config)
282294

283295
for i := 0; i < iterations; i++ {
284296
key := fmt.Sprintf("test_%d", i)

examples/metrics/main.go

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,12 @@ func prometheusExample() {
8484

8585
// Create cache with Prometheus metrics
8686
cacheConfig := obcache.NewDefaultConfig().
87-
WithDefaultTTL(5*time.Minute).
88-
WithMetricsExporter(prometheusExporter, "user-cache")
87+
WithDefaultTTL(5 * time.Minute).
88+
WithMetrics(&obcache.MetricsConfig{
89+
Exporter: prometheusExporter,
90+
Enabled: true,
91+
CacheName: "user-cache",
92+
})
8993

9094
cache, err := obcache.New(cacheConfig)
9195
if err != nil {
@@ -158,9 +162,12 @@ func opentelemetryExample() {
158162

159163
// Create cache with OpenTelemetry metrics
160164
cacheConfig := obcache.NewDefaultConfig().
161-
WithDefaultTTL(10*time.Minute).
162-
WithMetricsExporter(otelExporter, "product-cache").
163-
WithMetricsReportingInterval(5 * time.Second)
165+
WithDefaultTTL(10 * time.Minute).
166+
WithMetrics(&obcache.MetricsConfig{
167+
Exporter: otelExporter,
168+
Enabled: true,
169+
CacheName: "product-cache",
170+
})
164171

165172
cache, err := obcache.New(cacheConfig)
166173
if err != nil {
@@ -226,10 +233,14 @@ func multiExporterExample() {
226233

227234
// Create cache with multi-exporter
228235
cacheConfig := obcache.NewDefaultConfig().
229-
WithMetricsExporter(multiExporter, "multi-cache").
230-
WithMetricsLabels(metrics.Labels{
231-
"component": "multi-example",
232-
"tier": "cache",
236+
WithMetrics(&obcache.MetricsConfig{
237+
Exporter: multiExporter,
238+
Enabled: true,
239+
CacheName: "multi-cache",
240+
Labels: metrics.Labels{
241+
"component": "multi-example",
242+
"tier": "cache",
243+
},
233244
})
234245

235246
cache, err := obcache.New(cacheConfig)

examples/redis-cache/main.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,9 @@ func main() {
5252
func basicRedisExample() {
5353
// Create a Redis cache with simple address
5454
config := obcache.NewRedisConfig("localhost:6379").
55-
WithRedisKeyPrefix("example:").
55+
WithRedis(&obcache.RedisConfig{
56+
KeyPrefix: "example:",
57+
}).
5658
WithDefaultTTL(30 * time.Minute)
5759

5860
cache, err := obcache.New(config)
@@ -87,7 +89,9 @@ func basicRedisExample() {
8789
func functionWrappingExample() {
8890
// Create Redis cache configuration
8991
config := obcache.NewRedisConfig("localhost:6379").
90-
WithRedisKeyPrefix("func:").
92+
WithRedis(&obcache.RedisConfig{
93+
KeyPrefix: "func:",
94+
}).
9195
WithDefaultTTL(15 * time.Minute)
9296

9397
cache, err := obcache.New(config)
@@ -151,7 +155,9 @@ func distributedCachingExample() {
151155

152156
// Create cache configuration with the custom client
153157
config := obcache.NewRedisConfigWithClient(client).
154-
WithRedisKeyPrefix("distributed:").
158+
WithRedis(&obcache.RedisConfig{
159+
KeyPrefix: "distributed:",
160+
}).
155161
WithDefaultTTL(1 * time.Hour)
156162

157163
cache, err := obcache.New(config)

pkg/obcache/cache.go

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import (
1919
"github.com/vnykmshr/obcache-go/pkg/metrics"
2020
)
2121

22-
2322
func (c *Cache) rlock(fn func()) {
2423
c.mu.RLock()
2524
defer c.mu.RUnlock()
@@ -32,14 +31,14 @@ func (c *Cache) lock(fn func()) {
3231
fn()
3332
}
3433

35-
func (c *Cache) hit(key string, value any, ctx context.Context) {
34+
func (c *Cache) hit(ctx context.Context, key string, value any) {
3635
c.stats.incHits()
3736
if c.hooks != nil {
3837
c.hooks.invokeOnHitWithCtx(ctx, key, value, nil)
3938
}
4039
}
4140

42-
func (c *Cache) miss(key string, ctx context.Context) {
41+
func (c *Cache) miss(ctx context.Context, key string) {
4342
c.stats.incMisses()
4443
if c.hooks != nil {
4544
c.hooks.invokeOnMissWithCtx(ctx, key, nil)
@@ -212,17 +211,17 @@ func (c *Cache) Get(key string) (any, bool) {
212211
c.rlock(func() {
213212
entry, ok := c.store.Get(key)
214213
if !ok {
215-
c.miss(key, ctx)
214+
c.miss(ctx, key)
216215
return
217216
}
218217

219218
value, err := c.decompressValue(entry)
220219
if err != nil {
221-
c.miss(key, ctx)
220+
c.miss(ctx, key)
222221
return
223222
}
224223

225-
c.hit(key, value, ctx)
224+
c.hit(ctx, key, value)
226225
result = value
227226
found = true
228227
})

pkg/obcache/logging_test.go

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -265,30 +265,6 @@ func TestLoggingHooksIntegration(t *testing.T) {
265265
}
266266
}
267267

268-
func testLoggingWithContext(t *testing.T) { // Disabled: context API was simplified
269-
testLogger := NewTestLogger()
270-
hooks := CreateLoggingHooks(&LoggingConfig{
271-
Logger: testLogger,
272-
LogCacheHits: true,
273-
})
274-
275-
cache, err := New(NewDefaultConfig().WithHooks(hooks))
276-
if err != nil {
277-
t.Fatalf("Failed to create cache: %v", err)
278-
}
279-
280-
// Set value and get with context
281-
_ = cache.Set("user-key", "user-data", time.Hour)
282-
283-
// Test basic cache operation logging
284-
_, _ = cache.Get("user-key")
285-
286-
// Verify logging occurred (context features were simplified in API)
287-
if !testLogger.HasLogWithMessage("Cache miss") {
288-
t.Error("Expected cache operation to be logged")
289-
}
290-
}
291-
292268
func TestLoggingHookBuilder(t *testing.T) {
293269
// Test fluent builder interface
294270
hooks := NewLoggingHookBuilder().

pkg/obcache/wrap.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ func wrapFunction[T any](cache *Cache, fn T, opts *WrapOptions) T {
105105

106106
// executeWrappedFunction handles the core wrapping logic
107107
func executeWrappedFunction(cache *Cache, fnValue reflect.Value, fnType reflect.Type, opts *WrapOptions, args []reflect.Value) []reflect.Value {
108-
ctx, keyArgs := extractContextAndArgs(fnType, args)
108+
_, keyArgs := extractContextAndArgs(fnType, args)
109109
key := opts.KeyFunc(keyArgs)
110110

111111
// If caching is disabled, call original function directly
@@ -120,7 +120,7 @@ func executeWrappedFunction(cache *Cache, fnValue reflect.Value, fnType reflect.
120120
return convertCachedValue(cachedValue, fnType, hasErrorReturn)
121121
}
122122

123-
return executeFunctionWithSingleflight(cache, fnValue, fnType, opts, args, ctx, keyArgs, key, hasErrorReturn)
123+
return executeFunctionWithSingleflight(cache, fnValue, fnType, opts, args, key, hasErrorReturn)
124124
}
125125

126126
// extractContextAndArgs extracts context and key args from function arguments
@@ -155,7 +155,7 @@ func hasErrorReturn(fnType reflect.Type) bool {
155155
}
156156

157157
// executeFunctionWithSingleflight executes the function with singleflight pattern
158-
func executeFunctionWithSingleflight(cache *Cache, fnValue reflect.Value, fnType reflect.Type, opts *WrapOptions, args []reflect.Value, ctx context.Context, keyArgs []any, key string, hasErrorReturn bool) []reflect.Value {
158+
func executeFunctionWithSingleflight(cache *Cache, fnValue reflect.Value, fnType reflect.Type, opts *WrapOptions, args []reflect.Value, key string, hasErrorReturn bool) []reflect.Value {
159159
// Use singleflight to prevent duplicate calls
160160
compute := func() (any, error) {
161161
results := fnValue.Call(args)

pkg/obcache/wrap_test.go

Lines changed: 0 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package obcache
22

33
import (
4-
"context"
54
"errors"
65
"fmt"
76
"sync"
@@ -413,87 +412,6 @@ func TestWrapConvenienceFunctions(t *testing.T) {
413412
}
414413
}
415414

416-
func testWrapContextAwareFunctions(t *testing.T) { // Disabled: context API was simplified
417-
// Test context-aware wrapped functions with hooks
418-
var hitCtx context.Context
419-
var hitArgs []any
420-
var missCtx context.Context
421-
var missArgs []any
422-
423-
hooks := &Hooks{}
424-
hooks.AddOnHitCtx(func(ctx context.Context, _ string, _ any, args []any) {
425-
hitCtx = ctx
426-
hitArgs = args
427-
})
428-
hooks.AddOnMissCtx(func(ctx context.Context, _ string, args []any) {
429-
missCtx = ctx
430-
missArgs = args
431-
})
432-
433-
cache, err := New(NewDefaultConfig().WithHooks(hooks))
434-
if err != nil {
435-
t.Fatalf("Failed to create cache: %v", err)
436-
}
437-
438-
// Test function with context.Context as first parameter
439-
callCount := int32(0)
440-
contextFunc := func(_ context.Context, x int) int {
441-
atomic.AddInt32(&callCount, 1)
442-
return x * 2
443-
}
444-
445-
wrappedCtxFunc := Wrap(cache, contextFunc)
446-
447-
// Create context with test value
448-
type testKey string
449-
ctx := context.WithValue(context.Background(), testKey("testKey"), "testValue")
450-
451-
// First call - should miss and call original function
452-
result1 := wrappedCtxFunc(ctx, 5)
453-
if result1 != 10 {
454-
t.Fatalf("Expected result 10, got %d", result1)
455-
}
456-
if callCount != 1 {
457-
t.Fatalf("Expected function to be called once, called %d times", callCount)
458-
}
459-
460-
// Check miss hook was called with correct context and args
461-
if missCtx != ctx {
462-
t.Fatal("Miss hook should have received the context")
463-
}
464-
if len(missArgs) != 1 || missArgs[0] != 5 {
465-
t.Fatalf("Expected args [5], got %v", missArgs)
466-
}
467-
468-
// Second call - should hit cache
469-
result2 := wrappedCtxFunc(ctx, 5)
470-
if result2 != 10 {
471-
t.Fatalf("Expected cached result 10, got %d", result2)
472-
}
473-
if callCount != 1 {
474-
t.Fatalf("Expected function to be called only once, called %d times", callCount)
475-
}
476-
477-
// Check hit hook was called with correct context and args
478-
if hitCtx != ctx {
479-
t.Fatal("Hit hook should have received the context")
480-
}
481-
if len(hitArgs) != 1 || hitArgs[0] != 5 {
482-
t.Fatalf("Expected args [5], got %v", hitArgs)
483-
}
484-
485-
// Test function without context (should still work)
486-
normalFunc := func(x int) int {
487-
return x * 3
488-
}
489-
wrappedNormalFunc := Wrap(cache, normalFunc)
490-
491-
result3 := wrappedNormalFunc(4)
492-
if result3 != 12 {
493-
t.Fatalf("Expected result 12, got %d", result3)
494-
}
495-
}
496-
497415
//nolint:gocyclo // Test function complexity is acceptable
498416
func TestErrorCaching(t *testing.T) {
499417
cache, err := New(NewDefaultConfig())

0 commit comments

Comments
 (0)