-
Notifications
You must be signed in to change notification settings - Fork 61
/
messaging.go
144 lines (122 loc) · 3.56 KB
/
messaging.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
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"context"
"crypto/sha256"
"encoding/base64"
"math/rand"
"time"
"github.com/eapache/channels"
"github.com/prometheus/client_golang/prometheus"
"github.com/redis/go-redis/v9"
"google.golang.org/protobuf/proto"
)
const lockExpiration = time.Second * 5
var (
PromMessageBusCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "livekit",
Subsystem: "messagebus",
Name: "messages",
},
[]string{"type", "status"},
)
)
func init() {
prometheus.MustRegister(PromMessageBusCounter)
}
type MessageBus interface {
Subscribe(ctx context.Context, channel string) (PubSub, error)
// SubscribeQueue is like subscribe, but ensuring only a single instance gets to process the message
SubscribeQueue(ctx context.Context, channel string) (PubSub, error)
Publish(ctx context.Context, channel string, msg proto.Message) error
}
type PubSub interface {
Channel() <-chan interface{}
Payload(msg interface{}) []byte
Close() error
}
type RedisMessageBus struct {
rc redis.UniversalClient
}
func NewRedisMessageBus(rc redis.UniversalClient) MessageBus {
return &RedisMessageBus{rc: rc}
}
func (r *RedisMessageBus) Lock(ctx context.Context, key string, expiration time.Duration) (bool, error) {
return r.rc.SetNX(ctx, key, rand.Int(), expiration).Result()
}
func (r *RedisMessageBus) Subscribe(ctx context.Context, channel string) (PubSub, error) {
ps := r.rc.Subscribe(ctx, channel)
return &RedisPubSub{
ps: ps,
c: channels.Wrap(ps.Channel()).Out(),
done: make(chan struct{}, 1),
}, nil
}
func (r *RedisMessageBus) SubscribeQueue(ctx context.Context, channel string) (PubSub, error) {
sub := r.rc.Subscribe(ctx, channel)
c := make(chan *redis.Message, 100) // same chan size as redis pubsub
ps := &RedisPubSub{
ps: sub,
c: channels.Wrap(c).Out(),
done: make(chan struct{}, 1),
}
go func() {
for {
select {
case <-ps.done:
return
case msg := <-sub.Channel():
sha := sha256.Sum256([]byte(msg.Payload))
hash := base64.StdEncoding.EncodeToString(sha[:])
acquired, _ := r.Lock(ctx, hash, lockExpiration)
if acquired {
PromMessageBusCounter.WithLabelValues("in", "success").Add(1)
c <- msg
}
}
}
}()
return ps, nil
}
func (r *RedisMessageBus) Publish(ctx context.Context, channel string, msg proto.Message) error {
b, err := proto.Marshal(msg)
if err != nil {
PromMessageBusCounter.WithLabelValues("out", "failure").Add(1)
return err
}
err = r.rc.Publish(ctx, channel, b).Err()
if err == nil {
PromMessageBusCounter.WithLabelValues("out", "success").Add(1)
} else {
PromMessageBusCounter.WithLabelValues("out", "failure").Add(1)
}
return err
}
type RedisPubSub struct {
ps *redis.PubSub
c <-chan interface{}
done chan struct{}
}
func (r *RedisPubSub) Channel() <-chan interface{} {
return r.c
}
func (r *RedisPubSub) Payload(msg interface{}) []byte {
return []byte(msg.(*redis.Message).Payload)
}
func (r *RedisPubSub) Close() error {
r.done <- struct{}{}
return r.ps.Close()
}