Skip to content

Commit

Permalink
Use SendAsync+Flush instead of SendSync
Browse files Browse the repository at this point in the history
Signed-off-by: Maxim Zhiburt <zhiburt@gmail.com>
  • Loading branch information
zhiburt committed Oct 19, 2020
1 parent f5a108d commit 5b5f8c5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 25 deletions.
29 changes: 8 additions & 21 deletions cmd/mailer.go
Expand Up @@ -7,11 +7,9 @@ package cmd
import (
"errors"
"fmt"
"sync"
"sync/atomic"
"time"

"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/services/mailer"

"github.com/urfave/cli"
Expand Down Expand Up @@ -57,27 +55,16 @@ func runSendMail(c *cli.Context) error {
fmt.Printf("Sending %d emails", len(emails))

mailer.NewContext()
var ops uint64
var wg sync.WaitGroup

for _, email := range emails {
wg.Add(1)
go func(email, subject, content string) {
defer wg.Done()
msg := mailer.NewMessage([]string{email}, subject, body)
err = mailer.SendSync(msg)
if err != nil {
log.Error("Failed to send email %s: %v", email, err)
} else {
atomic.AddUint64(&ops, 1)
}
}(email, subject, body)
msg := mailer.NewMessage([]string{email}, subject, body)
mailer.SendAsync(msg)
}

wg.Wait()

opsFinal := atomic.LoadUint64(&ops)

fmt.Printf("Was sent %d emails from %d", opsFinal, len(emails))
err = mailer.FlushMessages(time.Minute * 60)
if err != nil {
return err
}

return nil
}
9 changes: 5 additions & 4 deletions services/mailer/mailer.go
Expand Up @@ -335,10 +335,11 @@ func NewContext() {
go graceful.GetManager().RunWithShutdownFns(mailQueue.Run)
}

// SendSync uses default sender to send a message with blocking
func SendSync(msg *Message) error {
gomailMsg := msg.ToMessage()
return gomail.Send(Sender, gomailMsg)
// FlushMessages a messages which were published to the mailQueue
//
// Function blocks untill the queue become empty or an operation exceed timeout duration.
func FlushMessages(timeout time.Duration) error {
return mailQueue.Flush(timeout)
}

// SendAsync send mail asynchronously
Expand Down

0 comments on commit 5b5f8c5

Please sign in to comment.