File
Blob: tun/server/waf_cache.go
| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "time" |
| 6 | |
| 7 | "go.miragespace.co/specter/spec/protocol" |
| 8 | |
| 9 | "github.com/Yiling-J/theine-go" |
| 10 | ) |
| 11 | |
| 12 | const ( |
| 13 | hostWAFCacheBytes = 1 << 20 // 1MiB |
| 14 | hostWAFCacheTTL = 30 * time.Second |
| 15 | ) |
| 16 | |
| 17 | type hostWAFCacheEntry struct { |
| 18 | record *protocol.HostWAFRecord |
| 19 | expiresAt time.Time |
| 20 | } |
| 21 | |
| 22 | func (s *Server) initHostWAFCache() { |
| 23 | cache, err := theine.NewBuilder[string, *hostWAFCacheEntry](hostWAFCacheBytes).Build() |
| 24 | if err != nil { |
| 25 | panic("BUG: " + err.Error()) |
| 26 | } |
| 27 | s.hostWAFCache = cache |
| 28 | } |
| 29 | |
| 30 | func (s *Server) readCachedHostWAF(ctx context.Context, hostname string) (*protocol.HostWAFRecord, error) { |
| 31 | if err := ctx.Err(); err != nil { |
| 32 | return nil, err |
| 33 | } |
| 34 | cached := func() (*hostWAFCacheEntry, bool) { |
| 35 | entry, ok := s.hostWAFCache.Get(hostname) |
| 36 | return entry, ok && time.Now().Before(entry.expiresAt) |
| 37 | } |
| 38 | if entry, ok := cached(); ok { |
| 39 | return entry.record, nil |
| 40 | } |
| 41 | |
| 42 | result := s.hostWAFLoads.DoChan(hostname, func() (any, error) { |
| 43 | if entry, ok := cached(); ok { |
| 44 | return entry, nil |
| 45 | } |
| 46 | // Invalidating a cache entry can race this read. Preserve its original |
| 47 | // deadline so an older in-flight read cannot earn another full lifetime. |
| 48 | expiresAt := time.Now().Add(hostWAFCacheTTL) |
| 49 | lookupCtx, cancel := context.WithTimeout(s.ParentContext, lookupTimeout) |
| 50 | defer cancel() |
| 51 | record, _, err := s.readHostWAF(lookupCtx, hostname) |
| 52 | if err != nil { |
| 53 | return nil, err |
| 54 | } |
| 55 | if err := lookupCtx.Err(); err != nil { |
| 56 | return nil, err |
| 57 | } |
| 58 | entry := &hostWAFCacheEntry{record: record, expiresAt: expiresAt} |
| 59 | // Include keys and entry/message overhead, including successful absence. |
| 60 | cost := int64(256 + len(hostname)) |
| 61 | if record != nil { |
| 62 | cost += int64(record.SizeVT() + 256 + 64*len(record.Policy.Exclusions)) |
| 63 | } |
| 64 | if ttl := time.Until(expiresAt); ttl > 0 { |
| 65 | s.hostWAFCache.SetWithTTL(hostname, entry, cost, ttl) |
| 66 | } |
| 67 | return entry, nil |
| 68 | }) |
| 69 | // A cancelled waiter must not cancel the shared read or cache an error. |
| 70 | select { |
| 71 | case <-ctx.Done(): |
| 72 | return nil, ctx.Err() |
| 73 | case <-s.ParentContext.Done(): |
| 74 | return nil, s.ParentContext.Err() |
| 75 | case result := <-result: |
| 76 | if result.Err != nil { |
| 77 | return nil, result.Err |
| 78 | } |
| 79 | entry := result.Val.(*hostWAFCacheEntry) |
| 80 | if !time.Now().Before(entry.expiresAt) { |
| 81 | return nil, context.DeadlineExceeded |
| 82 | } |
| 83 | return entry.record, nil |
| 84 | } |
| 85 | } |