diff options
Diffstat (limited to 'internal/storage')
| -rw-r--r-- | internal/storage/replay.go | 32 | ||||
| -rw-r--r-- | internal/storage/replay_test.go | 36 |
2 files changed, 68 insertions, 0 deletions
diff --git a/internal/storage/replay.go b/internal/storage/replay.go new file mode 100644 index 0000000..a2366a4 --- /dev/null +++ b/internal/storage/replay.go @@ -0,0 +1,32 @@ +package storage + +import ( + "sync" + "time" +) + +type ReplayCache struct { + ttl time.Duration + mu sync.Mutex + data map[string]time.Time +} + +func NewReplayCache(ttl time.Duration) *ReplayCache { + return &ReplayCache{ttl: ttl, data: map[string]time.Time{}} +} + +func (c *ReplayCache) CheckAndMark(hash string) (bool, error) { + c.mu.Lock() + defer c.mu.Unlock() + now := time.Now() + for k, ts := range c.data { + if now.Sub(ts) > c.ttl { + delete(c.data, k) + } + } + if _, exists := c.data[hash]; exists { + return true, nil + } + c.data[hash] = now + return false, nil +} diff --git a/internal/storage/replay_test.go b/internal/storage/replay_test.go new file mode 100644 index 0000000..4d147b8 --- /dev/null +++ b/internal/storage/replay_test.go @@ -0,0 +1,36 @@ +package storage + +import ( + "testing" + "time" +) + +func TestReplayCacheCheckAndMarkLivesOnlyInMemory(t *testing.T) { + cache := NewReplayCache(40 * time.Millisecond) + + replayed, err := cache.CheckAndMark("token-hash") + if err != nil { + t.Fatalf("CheckAndMark returned error: %v", err) + } + if replayed { + t.Fatal("first token use should not be marked as replayed") + } + + replayed, err = cache.CheckAndMark("token-hash") + if err != nil { + t.Fatalf("CheckAndMark returned error on second use: %v", err) + } + if !replayed { + t.Fatal("second token use should be marked as replayed") + } + + time.Sleep(60 * time.Millisecond) + + replayed, err = cache.CheckAndMark("token-hash") + if err != nil { + t.Fatalf("CheckAndMark returned error after ttl expiry: %v", err) + } + if replayed { + t.Fatal("expired token entry should be forgotten from memory") + } +} |
