-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
315 lines (258 loc) · 6.22 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package tt
import (
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/url"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gregoryv/tt/event"
)
// NewServer returns a server ready to run. Configure any settings
// before calling Run.
func NewServer() *Server {
return &Server{
app: make(chan interface{}, 1),
router: newRouter(),
stat: newServerStats(),
incoming: make(chan Connection, 1),
}
}
type Server struct {
// where server listens for connections
binds []*Bind
// before initial connect packet
connectTimeout time.Duration
debug bool
log *log.Logger
// routes publish packets to subscribing clients
router *router
// statistics
stat *serverStats
// sync server initial setup
startup sync.Once
// application server events, see [Server.Events]
app chan interface{}
// listeners feed new connections here
incoming chan Connection
}
// AddBind which to listen on for connections, defaults to
// tcp://localhost:, ie. random port on localhost.
func (s *Server) AddBind(b *Bind) {
s.binds = append(s.binds, b)
}
// Timeout for the initial connect packet from a client before
// disconnecting, default 200ms.
func (s *Server) SetConnectTimeout(v time.Duration) {
s.connectTimeout = v
}
// SetDebug increases log information, default false.
func (s *Server) SetDebug(v bool) {
s.debug = v
}
// SetLogger to use for this server, defaults to no logging.
func (s *Server) SetLogger(v *log.Logger) {
s.log = v
}
// Events returns a channel used by server to inform the application
// layer of events. E.g [event.ServerStop]
func (s *Server) Events() <-chan interface{} {
return s.app
}
// Incoming returns channel on which to feed new connections
func (s *Server) Incoming() chan<- Connection {
return s.incoming
}
func (s *Server) trigger(e any) {
select {
case s.app <- e:
default:
}
}
// Run the server. Use [Server.Events] to listen for progress.
func (s *Server) Run(ctx context.Context) {
s.startup.Do(s.setDefaults)
if err := s.runFeeds(ctx); err != nil {
s.app <- event.ServerStop{err}
return
}
s.trigger(event.ServerUp(0))
for {
select {
case <-ctx.Done():
s.trigger(event.ServerStop{nil})
return
case conn := <-s.incoming:
go s.serveConn(ctx, conn)
}
}
}
func (s *Server) setDefaults() {
// no logging if logger not set
if s.log == nil {
s.log = log.New(ioutil.Discard, "", 0)
}
if s.debug {
s.log.SetFlags(s.log.Flags() | log.Lshortfile)
}
if s.connectTimeout == 0 {
s.connectTimeout = 200 * time.Millisecond
}
if len(s.binds) == 0 {
s.AddBind(&Bind{
URL: "tcp://localhost:",
AcceptTimeout: "500ms",
})
}
}
// runFeeds creates listeners for configured binds and runs them.
func (s *Server) runFeeds(ctx context.Context) error {
for _, b := range s.binds {
u, err := url.Parse(b.URL)
if err != nil {
return err
}
ln, err := net.Listen(u.Scheme, u.Host)
if err != nil {
return err
}
// log configured and actual port
tmp := *u
tmp.Host = ln.Addr().String()
if u.Port() != tmp.Port() {
s.log.Printf("bind %s (configured as %s)", tmp.String(), u.String())
} else {
s.log.Println("bind", u.String())
}
t, err := time.ParseDuration(b.AcceptTimeout)
if err != nil {
return err
}
// run the Connection feed
f := connFeed{
feed: s.incoming,
Listener: ln,
AcceptTimeout: t,
}
go f.Run(ctx)
}
return nil
}
// ----------------------------------------
// Bind holds server listening settings
type Bind struct {
// eg. tcp://localhost[:port]
URL string
// eg. 500ms
AcceptTimeout string
}
// ----------------------------------------
type connFeed struct {
// Listener to watch
net.Listener
AcceptTimeout time.Duration
// serveConn handles new remote connections
feed chan<- Connection
}
// Run blocks until context is cancelled or accepting a connection
// fails. Accepting new Connection can only be interrupted if listener
// has SetDeadline method.
func (f *connFeed) Run(ctx context.Context) error {
l := f.Listener
loop:
for {
if err := ctx.Err(); err != nil {
return nil
}
// set deadline allows to break the loop early should the
// context be done
if l, ok := l.(interface{ SetDeadline(time.Time) error }); ok {
l.SetDeadline(time.Now().Add(f.AcceptTimeout))
}
conn, err := l.Accept()
if errors.Is(err, os.ErrDeadlineExceeded) {
continue loop
}
if err != nil {
return err
}
f.feed <- conn
}
}
// ----------------------------------------
func newServerStats() *serverStats {
return &serverStats{}
}
type serverStats struct {
ConnCount int64
ConnActive int64
}
func (s *serverStats) AddConn() {
atomic.AddInt64(&s.ConnCount, 1)
atomic.AddInt64(&s.ConnActive, 1)
}
func (s *serverStats) RemoveConn() {
atomic.AddInt64(&s.ConnActive, -1)
}
// ----------------------------------------
func newSubscription(handlers ...pubHandler) *subscription {
r := &subscription{
handlers: handlers,
}
return r
}
type subscription struct {
subscriptionID int
filters []string
handlers []pubHandler
}
func (r *subscription) String() string {
switch len(r.filters) {
case 0:
return fmt.Sprintf("sub %v", r.subscriptionID)
case 1:
return fmt.Sprintf("sub %v: %s", r.subscriptionID, r.filters[0])
default:
return fmt.Sprintf("sub %v: %s...", r.subscriptionID, r.filters[0])
}
}
func (s *subscription) addTopicFilter(f string) {
s.filters = append(s.filters, f)
}
// ----------------------------------------
// https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901247
func parseTopicFilter(filter string) error {
if len(filter) == 0 {
return fmt.Errorf("empty filter")
}
for i, r := range filter {
switch r {
case '+':
if i > 0 && filter[i-1] != '/' {
return fmt.Errorf("%q single-level wildcard occupy entire level", filter)
}
case '#':
if i != len(filter)-1 {
// i.e. /a/#/b
return fmt.Errorf("%q multi-level wildcard must be last", filter)
}
if i > 0 && filter[i-1] != '/' {
return fmt.Errorf("%q multi-level wildcard must follow level separator", filter)
}
}
}
return nil
}
func parseTopicName(name string) error {
if i := strings.IndexAny(name, "+#"); i >= 0 {
return ErrMalformedTopicName
}
return nil
}
var ErrMalformedTopicName = fmt.Errorf("malformed topic name")