Monorepo for Tangled
tangled.org
1package eventconsumer
2
3import (
4 "net/url"
5 "strconv"
6
7 "tangled.org/core/eventconsumer/cursor"
8 "tangled.org/core/hostutil"
9)
10
11type Kind string
12
13const (
14 KindKnot Kind = "knot"
15 KindSpindle Kind = "spindle"
16)
17
18type Source struct {
19 Kind Kind
20 Host string
21 NoTLS bool // use TLS by default
22}
23
24func NewKnotSource(host string) Source {
25 host, noTLS, _ := hostutil.ParseHostname(host)
26 return Source{Kind: KindKnot, Host: host, NoTLS: noTLS}
27}
28func NewSpindleSource(host string) Source {
29 host, noTLS, _ := hostutil.ParseHostname(host)
30 return Source{Kind: KindSpindle, Host: host, NoTLS: noTLS}
31}
32
33func (s Source) Key() string { return string(s.Kind) + ":" + s.Host }
34
35func MigrateLegacyCursor(store cursor.Store, s Source) {
36 if store.Get(s.Key()) != 0 {
37 return
38 }
39 if legacy := store.Get(s.Host); legacy != 0 {
40 store.Set(s.Key(), legacy)
41 }
42}
43
44func (s Source) URL(cursor int64) (*url.URL, error) {
45 scheme := "wss"
46 if s.NoTLS {
47 scheme = "ws"
48 }
49 u, err := url.Parse(scheme + "://" + s.Host + "/events")
50 if err != nil {
51 return nil, err
52 }
53 if cursor != 0 {
54 q := url.Values{}
55 q.Add("cursor", strconv.FormatInt(cursor, 10))
56 u.RawQuery = q.Encode()
57 }
58 return u, nil
59}