all repos — honk @ c822a66ae25ec3e1638b620a074d756c022f0906

my fork of honk

deliverator.go (view raw)

  1//
  2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
  3//
  4// Permission to use, copy, modify, and distribute this software for any
  5// purpose with or without fee is hereby granted, provided that the above
  6// copyright notice and this permission notice appear in all copies.
  7//
  8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 15
 16package main
 17
 18import (
 19	"log"
 20	notrand "math/rand"
 21	"sync"
 22	"time"
 23)
 24
 25func init() {
 26	notrand.Seed(time.Now().Unix())
 27}
 28
 29type Doover struct {
 30	ID   int64
 31	When time.Time
 32}
 33
 34func sayitagain(goarounds int, username string, rcpt string, msg []byte) {
 35	var drift time.Duration
 36	switch goarounds {
 37	case 1:
 38		drift = 5 * time.Minute
 39	case 2:
 40		drift = 1 * time.Hour
 41	case 3:
 42		drift = 4 * time.Hour
 43	case 4:
 44		drift = 12 * time.Hour
 45	case 5:
 46		drift = 24 * time.Hour
 47	default:
 48		log.Printf("he's dead jim: %s", rcpt)
 49		return
 50	}
 51	drift += time.Duration(notrand.Int63n(int64(drift / 10)))
 52	when := time.Now().UTC().Add(drift)
 53	_, err := stmtAddDoover.Exec(when.Format(dbtimeformat), goarounds, username, rcpt, msg)
 54	if err != nil {
 55		log.Printf("error saving doover: %s", err)
 56	}
 57	select {
 58	case pokechan <- 0:
 59	default:
 60	}
 61}
 62
 63var trucksout = 0
 64var maxtrucksout = 20
 65var garagelock sync.Mutex
 66var garagebell = sync.NewCond(&garagelock)
 67
 68func truckgoesout() {
 69	garagelock.Lock()
 70	for trucksout >= maxtrucksout {
 71		garagebell.Wait()
 72	}
 73	trucksout++
 74	garagelock.Unlock()
 75}
 76
 77func truckcomesin() {
 78	garagelock.Lock()
 79	trucksout--
 80	garagebell.Broadcast()
 81	garagelock.Unlock()
 82}
 83
 84func deliverate(goarounds int, username string, rcpt string, msg []byte) {
 85	truckgoesout()
 86	defer truckcomesin()
 87
 88	keyname, key := ziggy(username)
 89	var inbox string
 90	// already did the box indirection
 91	if rcpt[0] == '%' {
 92		inbox = rcpt[1:]
 93	} else {
 94		box, err := getboxes(rcpt)
 95		if err != nil {
 96			log.Printf("error getting inbox %s: %s", rcpt, err)
 97			sayitagain(goarounds+1, username, rcpt, msg)
 98			return
 99		}
100		inbox = box.In
101	}
102	err := PostMsg(keyname, key, inbox, msg)
103	if err != nil {
104		log.Printf("failed to post json to %s: %s", inbox, err)
105		sayitagain(goarounds+1, username, rcpt, msg)
106		return
107	}
108}
109
110var pokechan = make(chan int)
111
112func redeliverator() {
113	sleeper := time.NewTimer(0)
114	for {
115		select {
116		case <-pokechan:
117			if !sleeper.Stop() {
118				<-sleeper.C
119			}
120			time.Sleep(5 * time.Second)
121		case <-sleeper.C:
122		}
123
124		rows, err := stmtGetDoovers.Query()
125		if err != nil {
126			log.Printf("wat?")
127			time.Sleep(1 * time.Minute)
128			continue
129		}
130		var doovers []Doover
131		for rows.Next() {
132			var d Doover
133			var dt string
134			err := rows.Scan(&d.ID, &dt)
135			if err != nil {
136				log.Printf("error scanning dooverid: %s", err)
137				continue
138			}
139			d.When, _ = time.Parse(dbtimeformat, dt)
140			doovers = append(doovers, d)
141		}
142		rows.Close()
143		now := time.Now().UTC()
144		nexttime := now.Add(24 * time.Hour)
145		for _, d := range doovers {
146			if d.When.Before(now) {
147				var goarounds int
148				var username, rcpt string
149				var msg []byte
150				row := stmtLoadDoover.QueryRow(d.ID)
151				err := row.Scan(&goarounds, &username, &rcpt, &msg)
152				if err != nil {
153					log.Printf("error scanning doover: %s", err)
154					continue
155				}
156				_, err = stmtZapDoover.Exec(d.ID)
157				if err != nil {
158					log.Printf("error deleting doover: %s", err)
159					continue
160				}
161				log.Printf("redeliverating %s try %d", rcpt, goarounds)
162				deliverate(goarounds, username, rcpt, msg)
163			} else if d.When.Before(nexttime) {
164				nexttime = d.When
165			}
166		}
167		dur := nexttime.Sub(now).Round(time.Second) + 5*time.Second
168		sleeper.Reset(dur)
169	}
170}