all repos — honk @ 8dfa16ccc19e03a5ed5980d993909f69cf359d19

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 getdoovers() []Doover {
113	rows, err := stmtGetDoovers.Query()
114	if err != nil {
115		log.Printf("wat?")
116		time.Sleep(1 * time.Minute)
117		return nil
118	}
119	defer rows.Close()
120	var doovers []Doover
121	for rows.Next() {
122		var d Doover
123		var dt string
124		err := rows.Scan(&d.ID, &dt)
125		if err != nil {
126			log.Printf("error scanning dooverid: %s", err)
127			continue
128		}
129		d.When, _ = time.Parse(dbtimeformat, dt)
130		doovers = append(doovers, d)
131	}
132	return doovers
133}
134
135func redeliverator() {
136	sleeper := time.NewTimer(0)
137	for {
138		select {
139		case <-pokechan:
140			if !sleeper.Stop() {
141				<-sleeper.C
142			}
143			time.Sleep(5 * time.Second)
144		case <-sleeper.C:
145		}
146
147		doovers := getdoovers()
148
149		now := time.Now().UTC()
150		nexttime := now.Add(24 * time.Hour)
151		for _, d := range doovers {
152			if d.When.Before(now) {
153				var goarounds int
154				var username, rcpt string
155				var msg []byte
156				row := stmtLoadDoover.QueryRow(d.ID)
157				err := row.Scan(&goarounds, &username, &rcpt, &msg)
158				if err != nil {
159					log.Printf("error scanning doover: %s", err)
160					continue
161				}
162				_, err = stmtZapDoover.Exec(d.ID)
163				if err != nil {
164					log.Printf("error deleting doover: %s", err)
165					continue
166				}
167				log.Printf("redeliverating %s try %d", rcpt, goarounds)
168				deliverate(goarounds, username, rcpt, msg)
169			} else if d.When.Before(nexttime) {
170				nexttime = d.When
171			}
172		}
173		dur := nexttime.Sub(now).Round(time.Second) + 5*time.Second
174		sleeper.Reset(dur)
175	}
176}