/
server.go
213 lines (187 loc) · 4.99 KB
/
server.go
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package mocktwilio
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pkg/errors"
"github.com/target/goalert/notification/twilio"
"github.com/target/goalert/validation/validate"
)
// Config is used to configure the mock server.
type Config struct {
// The SID and token should match values given to the backend
// as the mock server will send and validate signatures.
AccountSID string
AuthToken string
// MinQueueTime determines the minimum amount of time an SMS or voice
// call will sit in the queue before being processed/delivered.
MinQueueTime time.Duration
}
// Server implements the Twilio API for SMS and Voice calls
// via the http.Handler interface.
type Server struct {
mx sync.RWMutex
callbacks map[string]string
smsCh chan *SMS
callCh chan *VoiceCall
errs chan error
cfg Config
messages map[string]*SMS
calls map[string]*VoiceCall
mux *http.ServeMux
sidSeq uint64
}
// NewServer creates a new Server.
func NewServer(cfg Config) *Server {
if cfg.MinQueueTime == 0 {
cfg.MinQueueTime = 100 * time.Millisecond
}
s := &Server{
cfg: cfg,
callbacks: make(map[string]string),
mux: http.NewServeMux(),
messages: make(map[string]*SMS),
calls: make(map[string]*VoiceCall),
smsCh: make(chan *SMS),
callCh: make(chan *VoiceCall),
errs: make(chan error, 10000),
}
base := "/Accounts/" + cfg.AccountSID
s.mux.HandleFunc(base+"/Calls.json", s.serveNewCall)
s.mux.HandleFunc(base+"/Messages.json", s.serveNewMessage)
s.mux.HandleFunc(base+"/Calls/", s.serveCallStatus)
s.mux.HandleFunc(base+"/Messages/", s.serveMessageStatus)
go s.loop()
return s
}
// Errors returns a channel that gets fed all errors when calling
// the backend.
func (s *Server) Errors() chan error {
return s.errs
}
func (s *Server) post(url string, v url.Values) ([]byte, error) {
req, err := http.NewRequest("POST", url, strings.NewReader(v.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("X-Twilio-Signature", string(twilio.Signature(s.cfg.AuthToken, url, v)))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode/100 != 2 {
return nil, errors.Errorf("non-2xx response: %s", resp.Status)
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if len(data) == 0 && resp.StatusCode != 204 {
return nil, errors.Errorf("non-204 response on empty body: %s", resp.Status)
}
return data, nil
}
func (s *Server) processMessages() {
s.mx.Lock()
for _, sms := range s.messages {
if time.Since(sms.start) < s.cfg.MinQueueTime {
continue
}
switch sms.msg.Status {
case twilio.MessageStatusAccepted:
defer sms.updateStatus(twilio.MessageStatusQueued)
case twilio.MessageStatusQueued:
// move to sending once it's been pulled from the channel
select {
case s.smsCh <- sms:
sms.msg.Status = twilio.MessageStatusSending
default:
}
}
}
s.mx.Unlock()
}
func (s *Server) id(prefix string) string {
return fmt.Sprintf("%s%032d", prefix, atomic.AddUint64(&s.sidSeq, 1))
}
func (s *Server) processCalls() {
for _, vc := range s.calls {
if time.Since(vc.start) < s.cfg.MinQueueTime {
continue
}
switch vc.call.Status {
case twilio.CallStatusQueued:
vc.updateStatus(twilio.CallStatusInitiated)
case twilio.CallStatusInitiated:
// move to ringing once it's been pulled from the channel
s.mx.Lock()
select {
case s.callCh <- vc:
vc.call.Status = twilio.CallStatusRinging
default:
}
s.mx.Unlock()
case twilio.CallStatusInProgress:
s.mx.Lock()
if vc.hangup || vc.needsProcessing {
select {
case s.callCh <- vc:
vc.needsProcessing = false
if vc.hangup {
vc.call.Status = twilio.CallStatusCompleted
}
default:
}
}
s.mx.Unlock()
}
}
}
func (s *Server) loop() {
sendT := time.NewTicker(10 * time.Millisecond)
for range sendT.C {
s.processMessages()
s.processCalls()
}
}
func apiError(status int, w http.ResponseWriter, e *twilio.Exception) {
w.WriteHeader(status)
err := json.NewEncoder(w).Encode(e)
if err != nil {
panic(err)
}
}
// ServeHTTP implements the http.Handler interface for serving [mock] API requests.
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
s.mux.ServeHTTP(w, req)
}
// RegisterSMSCallback will set/update a callback URL for SMS calls made to the given number.
func (s *Server) RegisterSMSCallback(number, url string) error {
err := validate.URL("URL", url)
if err != nil {
return err
}
s.mx.Lock()
defer s.mx.Unlock()
s.callbacks["SMS:"+number] = url
return nil
}
// RegisterVoiceCallback will set/update a callback URL for voice calls made to the given number.
func (s *Server) RegisterVoiceCallback(number, url string) error {
err := validate.URL("URL", url)
if err != nil {
return err
}
s.mx.Lock()
defer s.mx.Unlock()
s.callbacks["VOICE:"+number] = url
return nil
}