manager.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. package manager
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "html/template"
  7. "log"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/knadh/listmonk/internal/messenger"
  12. "github.com/knadh/listmonk/models"
  13. )
  14. const (
  15. // BaseTPL is the name of the base template.
  16. BaseTPL = "base"
  17. // ContentTpl is the name of the compiled message.
  18. ContentTpl = "content"
  19. )
  20. // DataSource represents a data backend, such as a database,
  21. // that provides subscriber and campaign records.
  22. type DataSource interface {
  23. NextCampaigns(excludeIDs []int64) ([]*models.Campaign, error)
  24. NextSubscribers(campID, limit int) ([]models.Subscriber, error)
  25. GetCampaign(campID int) (*models.Campaign, error)
  26. UpdateCampaignStatus(campID int, status string) error
  27. CreateLink(url string) (string, error)
  28. }
  29. // Manager handles the scheduling, processing, and queuing of campaigns
  30. // and message pushes.
  31. type Manager struct {
  32. cfg Config
  33. src DataSource
  34. messengers map[string]messenger.Messenger
  35. notifCB models.AdminNotifCallback
  36. logger *log.Logger
  37. // Campaigns that are currently running.
  38. camps map[int]*models.Campaign
  39. campsMutex sync.RWMutex
  40. // Links generated using Track() are cached here so as to not query
  41. // the database for the link UUID for every message sent. This has to
  42. // be locked as it may be used externally when previewing campaigns.
  43. links map[string]string
  44. linksMutex sync.RWMutex
  45. subFetchQueue chan *models.Campaign
  46. campMsgQueue chan CampaignMessage
  47. campMsgErrorQueue chan msgError
  48. campMsgErrorCounts map[int]int
  49. msgQueue chan Message
  50. }
  51. // CampaignMessage represents an instance of campaign message to be pushed out,
  52. // specific to a subscriber, via the campaign's messenger.
  53. type CampaignMessage struct {
  54. Campaign *models.Campaign
  55. Subscriber models.Subscriber
  56. from string
  57. to string
  58. subject string
  59. body []byte
  60. unsubURL string
  61. }
  62. // Message represents a generic message to be pushed to a messenger.
  63. type Message struct {
  64. From string
  65. To []string
  66. Subject string
  67. Body []byte
  68. Messenger string
  69. }
  70. // Config has parameters for configuring the manager.
  71. type Config struct {
  72. // Number of subscribers to pull from the DB in a single iteration.
  73. BatchSize int
  74. Concurrency int
  75. MessageRate int
  76. MaxSendErrors int
  77. RequeueOnError bool
  78. FromEmail string
  79. LinkTrackURL string
  80. UnsubURL string
  81. OptinURL string
  82. MessageURL string
  83. ViewTrackURL string
  84. }
  85. type msgError struct {
  86. camp *models.Campaign
  87. err error
  88. }
  89. // New returns a new instance of Mailer.
  90. func New(cfg Config, src DataSource, notifCB models.AdminNotifCallback, l *log.Logger) *Manager {
  91. if cfg.BatchSize < 1 {
  92. cfg.BatchSize = 1000
  93. }
  94. if cfg.Concurrency < 1 {
  95. cfg.Concurrency = 1
  96. }
  97. if cfg.MessageRate < 1 {
  98. cfg.MessageRate = 1
  99. }
  100. return &Manager{
  101. cfg: cfg,
  102. src: src,
  103. notifCB: notifCB,
  104. logger: l,
  105. messengers: make(map[string]messenger.Messenger),
  106. camps: make(map[int]*models.Campaign),
  107. links: make(map[string]string),
  108. subFetchQueue: make(chan *models.Campaign, cfg.Concurrency),
  109. campMsgQueue: make(chan CampaignMessage, cfg.Concurrency*2),
  110. msgQueue: make(chan Message, cfg.Concurrency),
  111. campMsgErrorQueue: make(chan msgError, cfg.MaxSendErrors),
  112. campMsgErrorCounts: make(map[int]int),
  113. }
  114. }
  115. // NewCampaignMessage creates and returns a CampaignMessage that is made available
  116. // to message templates while they're compiled. It represents a message from
  117. // a campaign that's bound to a single Subscriber.
  118. func (m *Manager) NewCampaignMessage(c *models.Campaign, s models.Subscriber) CampaignMessage {
  119. return CampaignMessage{
  120. Campaign: c,
  121. Subscriber: s,
  122. subject: c.Subject,
  123. from: c.FromEmail,
  124. to: s.Email,
  125. unsubURL: fmt.Sprintf(m.cfg.UnsubURL, c.UUID, s.UUID),
  126. }
  127. }
  128. // AddMessenger adds a Messenger messaging backend to the manager.
  129. func (m *Manager) AddMessenger(msg messenger.Messenger) error {
  130. id := msg.Name()
  131. if _, ok := m.messengers[id]; ok {
  132. return fmt.Errorf("messenger '%s' is already loaded", id)
  133. }
  134. m.messengers[id] = msg
  135. return nil
  136. }
  137. // PushMessage pushes a Message to be sent out by the workers.
  138. func (m *Manager) PushMessage(msg Message) error {
  139. select {
  140. case m.msgQueue <- msg:
  141. case <-time.After(time.Second * 3):
  142. m.logger.Println("message push timed out: %'s'", msg.Subject)
  143. return errors.New("message push timed out")
  144. }
  145. return nil
  146. }
  147. // GetMessengerNames returns the list of registered messengers.
  148. func (m *Manager) GetMessengerNames() []string {
  149. names := make([]string, 0, len(m.messengers))
  150. for n := range m.messengers {
  151. names = append(names, n)
  152. }
  153. return names
  154. }
  155. // HasMessenger checks if a given messenger is registered.
  156. func (m *Manager) HasMessenger(id string) bool {
  157. _, ok := m.messengers[id]
  158. return ok
  159. }
  160. // Run is a blocking function (that should be invoked as a goroutine)
  161. // that scans the data source at regular intervals for pending campaigns,
  162. // and queues them for processing. The process queue fetches batches of
  163. // subscribers and pushes messages to them for each queued campaign
  164. // until all subscribers are exhausted, at which point, a campaign is marked
  165. // as "finished".
  166. func (m *Manager) Run(tick time.Duration) {
  167. go m.scanCampaigns(tick)
  168. // Spawn N message workers.
  169. for i := 0; i < m.cfg.Concurrency; i++ {
  170. go m.messageWorker()
  171. }
  172. // Fetch the next set of subscribers for a campaign and process them.
  173. for c := range m.subFetchQueue {
  174. has, err := m.nextSubscribers(c, m.cfg.BatchSize)
  175. if err != nil {
  176. m.logger.Printf("error processing campaign batch (%s): %v", c.Name, err)
  177. continue
  178. }
  179. if has {
  180. // There are more subscribers to fetch.
  181. m.subFetchQueue <- c
  182. } else if m.isCampaignProcessing(c.ID) {
  183. // There are no more subscribers. Either the campaign status
  184. // has changed or all subscribers have been processed.
  185. newC, err := m.exhaustCampaign(c, "")
  186. if err != nil {
  187. m.logger.Printf("error exhausting campaign (%s): %v", c.Name, err)
  188. continue
  189. }
  190. m.sendNotif(newC, newC.Status, "")
  191. }
  192. }
  193. }
  194. // messageWorker is a blocking function that listens to the message queue
  195. // and pushes out incoming messages on it to the messenger.
  196. func (m *Manager) messageWorker() {
  197. // Counter to keep track of the message / sec rate limit.
  198. numMsg := 0
  199. for {
  200. select {
  201. // Campaign message.
  202. case msg := <-m.campMsgQueue:
  203. // Pause on hitting the message rate.
  204. if numMsg >= m.cfg.MessageRate {
  205. time.Sleep(time.Second)
  206. numMsg = 0
  207. }
  208. numMsg++
  209. err := m.messengers[msg.Campaign.MessengerID].Push(
  210. msg.from, []string{msg.to}, msg.subject, msg.body, nil)
  211. if err != nil {
  212. m.logger.Printf("error sending message in campaign %s: %v", msg.Campaign.Name, err)
  213. select {
  214. case m.campMsgErrorQueue <- msgError{camp: msg.Campaign, err: err}:
  215. default:
  216. }
  217. }
  218. // Arbitrary message.
  219. case msg := <-m.msgQueue:
  220. err := m.messengers[msg.Messenger].Push(
  221. msg.From, msg.To, msg.Subject, msg.Body, nil)
  222. if err != nil {
  223. m.logger.Printf("error sending message '%s': %v", msg.Subject, err)
  224. }
  225. }
  226. }
  227. }
  228. // TemplateFuncs returns the template functions to be applied into
  229. // compiled campaign templates.
  230. func (m *Manager) TemplateFuncs(c *models.Campaign) template.FuncMap {
  231. return template.FuncMap{
  232. "TrackLink": func(url string, msg *CampaignMessage) string {
  233. return m.trackLink(url, msg.Campaign.UUID, msg.Subscriber.UUID)
  234. },
  235. "TrackView": func(msg *CampaignMessage) template.HTML {
  236. return template.HTML(fmt.Sprintf(`<img src="%s" alt="" />`,
  237. fmt.Sprintf(m.cfg.ViewTrackURL, msg.Campaign.UUID, msg.Subscriber.UUID)))
  238. },
  239. "UnsubscribeURL": func(msg *CampaignMessage) string {
  240. return msg.unsubURL
  241. },
  242. "OptinURL": func(msg *CampaignMessage) string {
  243. // Add list IDs.
  244. // TODO: Show private lists list on optin e-mail
  245. return fmt.Sprintf(m.cfg.OptinURL, msg.Subscriber.UUID, "")
  246. },
  247. "MessageURL": func(msg *CampaignMessage) string {
  248. return fmt.Sprintf(m.cfg.MessageURL, c.UUID, msg.Subscriber.UUID)
  249. },
  250. "Date": func(layout string) string {
  251. if layout == "" {
  252. layout = time.ANSIC
  253. }
  254. return time.Now().Format(layout)
  255. },
  256. }
  257. }
  258. // scanCampaigns is a blocking function that periodically scans the data source
  259. // for campaigns to process and dispatches them to the manager.
  260. func (m *Manager) scanCampaigns(tick time.Duration) {
  261. t := time.NewTicker(tick)
  262. for {
  263. select {
  264. // Periodically scan the data source for campaigns to process.
  265. case <-t.C:
  266. campaigns, err := m.src.NextCampaigns(m.getPendingCampaignIDs())
  267. if err != nil {
  268. m.logger.Printf("error fetching campaigns: %v", err)
  269. continue
  270. }
  271. for _, c := range campaigns {
  272. if err := m.addCampaign(c); err != nil {
  273. m.logger.Printf("error processing campaign (%s): %v", c.Name, err)
  274. continue
  275. }
  276. m.logger.Printf("start processing campaign (%s)", c.Name)
  277. // If subscriber processing is busy, move on. Blocking and waiting
  278. // can end up in a race condition where the waiting campaign's
  279. // state in the data source has changed.
  280. select {
  281. case m.subFetchQueue <- c:
  282. default:
  283. }
  284. }
  285. // Aggregate errors from sending messages to check against the error threshold
  286. // after which a campaign is paused.
  287. case e := <-m.campMsgErrorQueue:
  288. if m.cfg.MaxSendErrors < 1 {
  289. continue
  290. }
  291. // If the error threshold is met, pause the campaign.
  292. m.campMsgErrorCounts[e.camp.ID]++
  293. if m.campMsgErrorCounts[e.camp.ID] >= m.cfg.MaxSendErrors {
  294. m.logger.Printf("error counted exceeded %d. pausing campaign %s",
  295. m.cfg.MaxSendErrors, e.camp.Name)
  296. if m.isCampaignProcessing(e.camp.ID) {
  297. m.exhaustCampaign(e.camp, models.CampaignStatusPaused)
  298. }
  299. delete(m.campMsgErrorCounts, e.camp.ID)
  300. // Notify admins.
  301. m.sendNotif(e.camp, models.CampaignStatusPaused, "Too many errors")
  302. }
  303. }
  304. }
  305. }
  306. // addCampaign adds a campaign to the process queue.
  307. func (m *Manager) addCampaign(c *models.Campaign) error {
  308. // Validate messenger.
  309. if _, ok := m.messengers[c.MessengerID]; !ok {
  310. m.src.UpdateCampaignStatus(c.ID, models.CampaignStatusCancelled)
  311. return fmt.Errorf("unknown messenger %s on campaign %s", c.MessengerID, c.Name)
  312. }
  313. // Load the template.
  314. if err := c.CompileTemplate(m.TemplateFuncs(c)); err != nil {
  315. return err
  316. }
  317. // Add the campaign to the active map.
  318. m.campsMutex.Lock()
  319. m.camps[c.ID] = c
  320. m.campsMutex.Unlock()
  321. return nil
  322. }
  323. // getPendingCampaignIDs returns the IDs of campaigns currently being processed.
  324. func (m *Manager) getPendingCampaignIDs() []int64 {
  325. // Needs to return an empty slice in case there are no campaigns.
  326. m.campsMutex.RLock()
  327. ids := make([]int64, 0, len(m.camps))
  328. for _, c := range m.camps {
  329. ids = append(ids, int64(c.ID))
  330. }
  331. m.campsMutex.RUnlock()
  332. return ids
  333. }
  334. // nextSubscribers processes the next batch of subscribers in a given campaign.
  335. // If returns a bool indicating whether there any subscribers were processed
  336. // in the current batch or not. This can happen when all the subscribers
  337. // have been processed, or if a campaign has been paused or cancelled abruptly.
  338. func (m *Manager) nextSubscribers(c *models.Campaign, batchSize int) (bool, error) {
  339. // Fetch a batch of subscribers.
  340. subs, err := m.src.NextSubscribers(c.ID, batchSize)
  341. if err != nil {
  342. return false, fmt.Errorf("error fetching campaign subscribers (%s): %v", c.Name, err)
  343. }
  344. // There are no subscribers.
  345. if len(subs) == 0 {
  346. return false, nil
  347. }
  348. // Push messages.
  349. for _, s := range subs {
  350. msg := m.NewCampaignMessage(c, s)
  351. if err := msg.Render(); err != nil {
  352. m.logger.Printf("error rendering message (%s) (%s): %v", c.Name, s.Email, err)
  353. continue
  354. }
  355. // Push the message to the queue while blocking and waiting until
  356. // the queue is drained.
  357. m.campMsgQueue <- msg
  358. }
  359. return true, nil
  360. }
  361. // isCampaignProcessing checks if the campaign is bing processed.
  362. func (m *Manager) isCampaignProcessing(id int) bool {
  363. m.campsMutex.RLock()
  364. _, ok := m.camps[id]
  365. m.campsMutex.RUnlock()
  366. return ok
  367. }
  368. func (m *Manager) exhaustCampaign(c *models.Campaign, status string) (*models.Campaign, error) {
  369. m.campsMutex.Lock()
  370. delete(m.camps, c.ID)
  371. m.campsMutex.Unlock()
  372. // A status has been passed. Change the campaign's status
  373. // without further checks.
  374. if status != "" {
  375. if err := m.src.UpdateCampaignStatus(c.ID, status); err != nil {
  376. m.logger.Printf("error updating campaign (%s) status to %s: %v", c.Name, status, err)
  377. } else {
  378. m.logger.Printf("set campaign (%s) to %s", c.Name, status)
  379. }
  380. return c, nil
  381. }
  382. // Fetch the up-to-date campaign status from the source.
  383. cm, err := m.src.GetCampaign(c.ID)
  384. if err != nil {
  385. return nil, err
  386. }
  387. // If a running campaign has exhausted subscribers, it's finished.
  388. if cm.Status == models.CampaignStatusRunning {
  389. cm.Status = models.CampaignStatusFinished
  390. if err := m.src.UpdateCampaignStatus(c.ID, models.CampaignStatusFinished); err != nil {
  391. m.logger.Printf("error finishing campaign (%s): %v", c.Name, err)
  392. } else {
  393. m.logger.Printf("campaign (%s) finished", c.Name)
  394. }
  395. } else {
  396. m.logger.Printf("stop processing campaign (%s)", c.Name)
  397. }
  398. return cm, nil
  399. }
  400. // trackLink register a URL and return its UUID to be used in message templates
  401. // for tracking links.
  402. func (m *Manager) trackLink(url, campUUID, subUUID string) string {
  403. m.linksMutex.RLock()
  404. if uu, ok := m.links[url]; ok {
  405. m.linksMutex.RUnlock()
  406. return fmt.Sprintf(m.cfg.LinkTrackURL, uu, campUUID, subUUID)
  407. }
  408. m.linksMutex.RUnlock()
  409. // Register link.
  410. uu, err := m.src.CreateLink(url)
  411. if err != nil {
  412. m.logger.Printf("error registering tracking for link '%s': %v", url, err)
  413. // If the registration fails, fail over to the original URL.
  414. return url
  415. }
  416. m.linksMutex.Lock()
  417. m.links[url] = uu
  418. m.linksMutex.Unlock()
  419. return fmt.Sprintf(m.cfg.LinkTrackURL, uu, campUUID, subUUID)
  420. }
  421. // sendNotif sends a notification to registered admin e-mails.
  422. func (m *Manager) sendNotif(c *models.Campaign, status, reason string) error {
  423. var (
  424. subject = fmt.Sprintf("%s: %s", strings.Title(status), c.Name)
  425. data = map[string]interface{}{
  426. "ID": c.ID,
  427. "Name": c.Name,
  428. "Status": status,
  429. "Sent": c.Sent,
  430. "ToSend": c.ToSend,
  431. "Reason": reason,
  432. }
  433. )
  434. return m.notifCB(subject, data)
  435. }
  436. // Render takes a Message, executes its pre-compiled Campaign.Tpl
  437. // and applies the resultant bytes to Message.body to be used in messages.
  438. func (m *CampaignMessage) Render() error {
  439. out := bytes.Buffer{}
  440. // Render the subject if it's a template.
  441. if m.Campaign.SubjectTpl != nil {
  442. if err := m.Campaign.SubjectTpl.ExecuteTemplate(&out, models.ContentTpl, m); err != nil {
  443. return err
  444. }
  445. m.subject = out.String()
  446. out.Reset()
  447. }
  448. if err := m.Campaign.Tpl.ExecuteTemplate(&out, models.BaseTpl, m); err != nil {
  449. return err
  450. }
  451. m.body = out.Bytes()
  452. return nil
  453. }
  454. // Subject returns a copy of the message subject
  455. func (m *CampaignMessage) Subject() string {
  456. return m.subject
  457. }
  458. // Body returns a copy of the message body.
  459. func (m *CampaignMessage) Body() []byte {
  460. out := make([]byte, len(m.body))
  461. copy(out, m.body)
  462. return out
  463. }