all repos — honk @ 8c83d43769dcc56c595892bb38d338267492ce8e

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