-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
ai-brain: implement thread mapping with an internal cache
- Loading branch information
Showing
3 changed files
with
133 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package aibrain | ||
|
||
import ( | ||
"sync" | ||
"time" | ||
) | ||
|
||
type cache struct { | ||
m sync.Map | ||
ttl time.Duration | ||
} | ||
|
||
type entry struct { | ||
threadID string | ||
expireTime time.Time | ||
} | ||
|
||
func newCache(ttl time.Duration) *cache { | ||
return &cache{ | ||
m: sync.Map{}, | ||
ttl: ttl, | ||
} | ||
} | ||
|
||
func (c *cache) Set(messageID, threadID string) { | ||
c.m.Store(messageID, &entry{ | ||
threadID: threadID, | ||
expireTime: time.Now().Add(c.ttl), | ||
}) | ||
} | ||
|
||
func (c *cache) Get(messageID string) (string, bool) { | ||
item, ok := c.m.Load(messageID) | ||
if !ok { | ||
return "", false | ||
} | ||
|
||
e, ok := item.(*entry) | ||
if !ok || time.Now().After(e.expireTime) { | ||
c.m.Delete(messageID) | ||
return "", false | ||
} | ||
|
||
return e.threadID, true | ||
} | ||
|
||
func (c *cache) Delete(messageID string) { | ||
c.m.Delete(messageID) | ||
} | ||
|
||
func (c *cache) Cleanup() { | ||
ticker := time.NewTicker(c.ttl / 16) | ||
defer ticker.Stop() | ||
|
||
for range ticker.C { | ||
c.m.Range(func(k interface{}, v interface{}) bool { | ||
e, ok := v.(*entry) | ||
if !ok || time.Now().After(e.expireTime) { | ||
c.m.Delete(k) | ||
} | ||
return true | ||
}) | ||
} | ||
} |