State: Fixed default store messages not working properly

This commit is contained in:
diamondburned (Forefront) 2020-02-21 22:03:44 -08:00
parent 587d36fd6c
commit 1201652aa1
2 changed files with 11 additions and 18 deletions

View File

@ -40,15 +40,16 @@ type State struct {
// List of channels with few messages, so it doesn't bother hitting the API
// again.
fewMessages []discord.Snowflake
fewMessages map[discord.Snowflake]struct{}
fewMutex sync.Mutex
}
func NewFromSession(s *session.Session, store Store) (*State, error) {
state := &State{
Session: s,
Store: store,
StateLog: func(err error) {},
Session: s,
Store: store,
StateLog: func(err error) {},
fewMessages: map[discord.Snowflake]struct{}{},
}
return state, state.hookSession()
@ -378,19 +379,16 @@ func (s *State) Messages(channelID discord.Snowflake) ([]discord.Message, error)
// Is the channel tiny?
s.fewMutex.Lock()
for _, ch := range s.fewMessages {
if ch == channelID {
// Yes, skip the state.
s.fewMutex.Unlock()
return ms, nil
}
if _, ok := s.fewMessages[channelID]; ok {
s.fewMutex.Unlock()
return ms, nil
}
// No, fetch from the state.
s.fewMutex.Unlock()
}
ms, err = s.Session.Messages(channelID, 100)
ms, err = s.Session.Messages(channelID, uint(maxMsgs))
if err != nil {
return nil, err
}
@ -418,7 +416,7 @@ func (s *State) Messages(channelID discord.Snowflake) ([]discord.Message, error)
if len(ms) < maxMsgs {
// Tiny channel, store this.
s.fewMutex.Lock()
s.fewMessages = append(s.fewMessages, channelID)
s.fewMessages[channelID] = struct{}{}
s.fewMutex.Unlock()
return ms, nil

View File

@ -485,12 +485,7 @@ func (s *DefaultStore) MessageSet(message *discord.Message) error {
// Prepend the latest message at the end
if len(ms) > 0 {
var end = s.MaxMessages()
if len(ms) < end {
end = len(ms)
}
if end := s.MaxMessages(); len(ms) >= end {
// Copy hack to prepend. This copies the 0th-(end-1)th entries to
// 1st-endth.
copy(ms[1:end], ms[0:end-1])