File size: 3,125 Bytes
3a81980
 
cfb8175
db492de
 
 
 
cfb8175
 
db492de
 
cfb8175
3a81980
 
 
 
 
 
cfb8175
 
 
 
 
db492de
cfb8175
 
db492de
 
 
 
 
cfb8175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db492de
 
 
 
 
 
 
 
 
 
 
 
cfb8175
 
 
 
 
 
 
 
 
 
 
 
db492de
 
 
 
 
 
 
 
 
 
 
 
cfb8175
 
 
 
 
db492de
 
 
 
 
 
 
 
 
 
 
 
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
package executor

import (
	"context"
	json "github.com/goccy/go-json"
	"fmt"
	"strings"
	"sync"
	"time"

	"github.com/router-for-me/CLIProxyAPI/v6/internal/cache"
)

type codexCache struct {
	ID     string
	Expire time.Time
}

// codexCacheMap stores prompt cache IDs keyed by model+user_id.
// Protected by codexCacheMu. Entries expire after 1 hour.
var (
	codexCacheMap = make(map[string]codexCache)
	codexCacheMu  sync.RWMutex
	codexKVStore  cache.KVStore
)

// SetCodexKVStore configures an optional external store for codex prompt cache.
func SetCodexKVStore(store cache.KVStore) {
	codexKVStore = store
}

// codexCacheCleanupInterval controls how often expired entries are purged.
const codexCacheCleanupInterval = 15 * time.Minute

// codexCacheCleanupOnce ensures the background cleanup goroutine starts only once.
var codexCacheCleanupOnce sync.Once

// startCodexCacheCleanup launches a background goroutine that periodically
// removes expired entries from codexCacheMap to prevent memory leaks.
func startCodexCacheCleanup() {
	go func() {
		ticker := time.NewTicker(codexCacheCleanupInterval)
		defer ticker.Stop()
		for range ticker.C {
			purgeExpiredCodexCache()
		}
	}()
}

// purgeExpiredCodexCache removes entries that have expired.
func purgeExpiredCodexCache() {
	now := time.Now()
	codexCacheMu.Lock()
	defer codexCacheMu.Unlock()
	for key, cache := range codexCacheMap {
		if cache.Expire.Before(now) {
			delete(codexCacheMap, key)
		}
	}
}

// getCodexCache retrieves a cached entry, returning ok=false if not found or expired.
func getCodexCache(key string) (codexCache, bool) {
	if codexKVStore != nil {
		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		payload, err := codexKVStore.Get(ctx, codexRedisKey(key))
		cancel()
		if err == nil && payload != "" {
			var entry codexCache
			if json.Unmarshal([]byte(payload), &entry) == nil && !entry.Expire.Before(time.Now()) {
				return entry, true
			}
		}
	}

	codexCacheCleanupOnce.Do(startCodexCacheCleanup)
	codexCacheMu.RLock()
	cache, ok := codexCacheMap[key]
	codexCacheMu.RUnlock()
	if !ok || cache.Expire.Before(time.Now()) {
		return codexCache{}, false
	}
	return cache, true
}

// setCodexCache stores a cache entry.
func setCodexCache(key string, cache codexCache) {
	if codexKVStore != nil {
		if payload, err := json.Marshal(cache); err == nil {
			ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
			ttl := time.Until(cache.Expire)
			if ttl <= 0 {
				ttl = time.Hour
			}
			_ = codexKVStore.Set(ctx, codexRedisKey(key), string(payload), ttl)
			cancel()
		}
	}

	codexCacheCleanupOnce.Do(startCodexCacheCleanup)
	codexCacheMu.Lock()
	codexCacheMap[key] = cache
	codexCacheMu.Unlock()
}

func codexRedisKey(key string) string {
	trimmed := strings.TrimSpace(key)
	if trimmed == "" {
		return "codex"
	}
	parts := strings.SplitN(trimmed, ":", 2)
	if len(parts) == 2 && strings.TrimSpace(parts[0]) != "" && strings.TrimSpace(parts[1]) != "" {
		return fmt.Sprintf("codex:%s:%s", strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]))
	}
	return fmt.Sprintf("codex:%s", trimmed)
}