-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstscheduler.go
More file actions
92 lines (81 loc) · 1.93 KB
/
stscheduler.go
File metadata and controls
92 lines (81 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright (c) 2022 Wireleap
package stscheduler
import (
"fmt"
"log"
"sync"
"time"
"github.com/wireleap/common/api/sharetoken"
)
type T struct {
scheduled map[int64][]*sharetoken.T
mu sync.Mutex
tt *time.Ticker
}
func New(dur time.Duration, submit func(*sharetoken.T) error, expire func(*sharetoken.T) error) (t *T) {
t = &T{
tt: time.NewTicker(dur),
scheduled: map[int64][]*sharetoken.T{},
}
// regular submission thread
go func() {
for range t.tt.C {
t.mu.Lock()
n := 0
now := time.Now()
for t0, sts := range t.scheduled {
if t0 <= now.Unix() {
for _, st := range sts {
if err := submit(st); err != nil {
ntime := now.Add(dur)
blurb := ""
if st.IsExpiredAt(ntime.Unix()) {
// next attempt will fail
if errX := expire(st); errX != nil {
log.Printf(
"could not expire failed sharetoken (sig=%s): %s",
st.Signature,
errX,
)
}
blurb = "next submission attempt is past submission window! skipping sharetoken"
} else {
// try again later
t.scheduled[ntime.Unix()] = append(t.scheduled[ntime.Unix()], st)
blurb = fmt.Sprintf("next submission attempt at %s", ntime)
}
log.Printf(
"could not submit sharetoken (sig=%s): %s, %s",
st.Signature,
err,
blurb,
)
} else {
n++
}
}
// submission of all sts complete or postponed, clean up
delete(t.scheduled, t0)
}
}
t.mu.Unlock()
}
}()
log.Printf(
"sharetoken scheduler started, next tick at %s and every %s.",
time.Now().Add(dur),
dur,
)
return
}
func (t *T) Schedule(st *sharetoken.T) {
t.mu.Lock()
when := st.Contract.SettlementOpen + 1
t.scheduled[when] = append(t.scheduled[when], st)
t.mu.Unlock()
log.Printf(
"scheduled sharetoken (sig=%s) submission for %s",
st.Signature,
time.Unix(when, 0),
)
}