1
0
Fork 0

Make sure to send leftover messages when application is closing

This commit is contained in:
Michał Rudowicz 2024-02-11 00:24:11 +01:00
parent 6f0f78907c
commit 9f67c17fc4
2 changed files with 10 additions and 10 deletions

View File

@ -22,11 +22,12 @@ func tg_sender_worker(tg_events <-chan GenericMessage, s Sender, wg *sync.WaitGr
waitingStarted := false waitingStarted := false
timeoutEvents := make(chan interface{}) timeoutEvents := make(chan interface{})
loop:
for { for {
select { select {
case ev, ok := <-tg_events: case ev, ok := <-tg_events:
if !ok { if !ok {
return break loop
} }
// Collect all messages to send them at once // Collect all messages to send them at once
_, messageBuilderExists := messagesToSend[ev.chat_id] _, messageBuilderExists := messagesToSend[ev.chat_id]
@ -52,13 +53,15 @@ func tg_sender_worker(tg_events <-chan GenericMessage, s Sender, wg *sync.WaitGr
} }
delete(messagesToSend, chat_id) delete(messagesToSend, chat_id)
} }
if tg_events == nil {
close(timeoutEvents)
}
} }
}
if tg_events == nil && timeoutEvents == nil { // If anything is left to be sent, send it now
return for chat_id, msgBuilder := range messagesToSend {
err := s.Send(GenericMessage{chat_id, msgBuilder.String()})
if err != nil {
// TODO: handle it better
panic(err)
} }
} }
} }

View File

@ -27,12 +27,9 @@ func TestMessageThrottling(t *testing.T) {
testEvents <- GenericMessage{124, "test4"} testEvents <- GenericMessage{124, "test4"}
time.Sleep(time.Millisecond * 10) time.Sleep(time.Millisecond * 10)
testEvents <- GenericMessage{123, "test5"} testEvents <- GenericMessage{123, "test5"}
time.Sleep(time.Millisecond * 10)
close(testEvents) close(testEvents)
wg.Wait()
assert.Len(t, mockSender.messages, 3) assert.Len(t, mockSender.messages, 3)
assert.Contains(t, mockSender.messages, GenericMessage{123, "test1\ntest2\n"}) assert.Contains(t, mockSender.messages, GenericMessage{123, "test1\ntest2\n"})
wg.Wait()
} }