mirror of
https://github.com/eosswedenorg/thalos
synced 2026-06-19 04:50:02 +02:00
merge api/redis_common and api/redis_pubsub to api/redis
This commit is contained in:
parent
102045e47e
commit
a8bac16aa9
9 changed files with 10 additions and 15 deletions
19
api/redis/key.go
Normal file
19
api/redis/key.go
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"thalos/api"
|
||||
)
|
||||
|
||||
// Key consists of a namespace and a channel.
|
||||
// And is encoded to a string in this format: `<namespace>::<channel>`
|
||||
|
||||
type Key struct {
|
||||
NS Namespace
|
||||
Channel api.Channel
|
||||
}
|
||||
|
||||
func (k Key) String() string {
|
||||
return fmt.Sprintf("%s::%s", k.NS, k.Channel.Format("/"))
|
||||
}
|
||||
35
api/redis/key_test.go
Normal file
35
api/redis/key_test.go
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"thalos/api"
|
||||
)
|
||||
|
||||
func TestKey_String(t *testing.T) {
|
||||
type fields struct {
|
||||
NS Namespace
|
||||
Channel api.Channel
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
fields fields
|
||||
want string
|
||||
}{
|
||||
{"Empty", fields{NS: Namespace{}, Channel: api.Channel{}}, "ship::0000000000000000000000000000000000000000000000000000000000000000::"},
|
||||
{"Transactions", fields{NS: Namespace{ChainID: "id"}, Channel: api.Channel{"transactions"}}, "ship::id::transactions"},
|
||||
{"Nested", fields{NS: Namespace{ChainID: "id"}, Channel: api.Channel{"one.two"}}, "ship::id::one.two"},
|
||||
{"Action", fields{NS: Namespace{ChainID: "id"}, Channel: api.Action{Contract: "mycontract"}.Channel()}, "ship::id::actions/contract/mycontract"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
k := Key{
|
||||
NS: tt.fields.NS,
|
||||
Channel: tt.fields.Channel,
|
||||
}
|
||||
if got := k.String(); got != tt.want {
|
||||
t.Errorf("Key.String() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
47
api/redis/namespace.go
Normal file
47
api/redis/namespace.go
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"thalos/api"
|
||||
)
|
||||
|
||||
const (
|
||||
// Default prefix to use when none is set.
|
||||
defaultPrefix = "ship"
|
||||
|
||||
// We need to have some chain_id, so if no one is specified.
|
||||
// we use a "null" id that is all zeros.
|
||||
nullChain = "0000000000000000000000000000000000000000000000000000000000000000"
|
||||
)
|
||||
|
||||
// Namespace type.
|
||||
//
|
||||
// Contains a prefix and chain_id to guard keys against collision.
|
||||
// Prefix should be sufficient to not collide with other application using the same redis database.
|
||||
// chain_id should be ok to not let multiple reader with different chains to write to the same channels.
|
||||
|
||||
type Namespace struct {
|
||||
Prefix string
|
||||
ChainID string
|
||||
}
|
||||
|
||||
// Create a new key with this namespace.
|
||||
func (ns Namespace) NewKey(ch api.Channel) Key {
|
||||
return Key{NS: ns, Channel: ch}
|
||||
}
|
||||
|
||||
func (ns Namespace) String() string {
|
||||
// No Chain id, set to "nullChain"
|
||||
if len(ns.ChainID) < 1 {
|
||||
ns.ChainID = nullChain
|
||||
}
|
||||
|
||||
// Set default prefix if empty.
|
||||
if len(ns.Prefix) < 1 {
|
||||
ns.Prefix = defaultPrefix
|
||||
}
|
||||
|
||||
// Otherwise. return both.
|
||||
return strings.Join([]string{ns.Prefix, ns.ChainID}, "::")
|
||||
}
|
||||
23
api/redis/namespace_test.go
Normal file
23
api/redis/namespace_test.go
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
package redis
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestNamespace_String(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ns Namespace
|
||||
want string
|
||||
}{
|
||||
{"Empty", Namespace{}, "ship::0000000000000000000000000000000000000000000000000000000000000000"},
|
||||
{"Prefix Only", Namespace{Prefix: "some.prefix"}, "some.prefix::0000000000000000000000000000000000000000000000000000000000000000"},
|
||||
{"ChainID Only", Namespace{ChainID: "1234"}, "ship::1234"},
|
||||
{"Both", Namespace{Prefix: "my.prefix", ChainID: "1234"}, "my.prefix::1234"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := tt.ns.String(); got != tt.want {
|
||||
t.Errorf("Namespace.String() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
36
api/redis/publisher.go
Normal file
36
api/redis/publisher.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"thalos/api"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
)
|
||||
|
||||
type Publisher struct {
|
||||
pipeline redis.Pipeliner
|
||||
ctx context.Context
|
||||
ns Namespace
|
||||
}
|
||||
|
||||
func NewPublisher(client *redis.Client, ns Namespace) *Publisher {
|
||||
return &Publisher{
|
||||
pipeline: client.Pipeline(),
|
||||
ctx: client.Context(),
|
||||
ns: ns,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Publisher) Write(channel api.Channel, payload []byte) error {
|
||||
return r.pipeline.Publish(r.ctx, r.ns.NewKey(channel).String(), payload).Err()
|
||||
}
|
||||
|
||||
func (r *Publisher) Flush() error {
|
||||
_, err := r.pipeline.Exec(r.ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *Publisher) Close() error {
|
||||
return r.pipeline.Close()
|
||||
}
|
||||
26
api/redis/publisher_test.go
Normal file
26
api/redis/publisher_test.go
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"thalos/api"
|
||||
|
||||
"github.com/go-redis/redismock/v8"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestPublisher_Write(t *testing.T) {
|
||||
client, mock := redismock.NewClientMock()
|
||||
|
||||
pub := NewPublisher(client, Namespace{ChainID: "id"})
|
||||
|
||||
mock.MatchExpectationsInOrder(true)
|
||||
mock.ExpectPublish("ship::id::test", []byte("some string")).SetVal(0)
|
||||
mock.ExpectPublish("ship::id::test2", []byte("some other string")).SetVal(0)
|
||||
|
||||
assert.NoError(t, pub.Write(api.Channel{"test"}, []byte("some string")))
|
||||
assert.NoError(t, pub.Write(api.Channel{"test2"}, []byte("some other string")))
|
||||
assert.NoError(t, pub.Flush())
|
||||
|
||||
assert.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
109
api/redis/subscriber.go
Normal file
109
api/redis/subscriber.go
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"thalos/api"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
)
|
||||
|
||||
type Subscriber struct {
|
||||
client *redis.Client
|
||||
sub *redis.PubSub
|
||||
ctx context.Context
|
||||
mu sync.RWMutex
|
||||
timeout time.Duration
|
||||
channels map[string]chan []byte
|
||||
ns Namespace
|
||||
}
|
||||
|
||||
type SubscriberOption func(*Subscriber)
|
||||
|
||||
func WithTimeout(value time.Duration) SubscriberOption {
|
||||
return func(s *Subscriber) {
|
||||
s.timeout = value
|
||||
}
|
||||
}
|
||||
|
||||
func NewSubscriber(client *redis.Client, ns Namespace, options ...SubscriberOption) *Subscriber {
|
||||
sub := &Subscriber{
|
||||
client: client,
|
||||
ctx: client.Context(),
|
||||
sub: client.PSubscribe(client.Context()),
|
||||
channels: make(map[string]chan []byte),
|
||||
timeout: time.Millisecond * 200,
|
||||
ns: ns,
|
||||
}
|
||||
|
||||
for _, opt := range options {
|
||||
opt(sub)
|
||||
}
|
||||
|
||||
go sub.worker()
|
||||
|
||||
return sub
|
||||
}
|
||||
|
||||
// forward forwards a message to the channel.
|
||||
// as writes to a unbuffered channel will block until it's read.
|
||||
// We run select on it and discard the message if no read happends during timeout
|
||||
func forward(msg redis.Message, ch chan<- []byte, timeout time.Duration) {
|
||||
select {
|
||||
case <-time.After(timeout):
|
||||
case ch <- []byte(msg.Payload):
|
||||
}
|
||||
}
|
||||
|
||||
// worker reads messages from redis pubsub and forwards them to
|
||||
// correct channels.
|
||||
func (s *Subscriber) worker() {
|
||||
for msg := range s.sub.Channel() {
|
||||
// Route message to correct channel.
|
||||
s.mu.RLock()
|
||||
if ch, ok := s.channels[msg.Channel]; ok {
|
||||
go forward(*msg, ch, s.timeout)
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Subscriber) Read(channel api.Channel) ([]byte, error) {
|
||||
var err error
|
||||
|
||||
key := s.ns.NewKey(channel).String()
|
||||
s.mu.RLock()
|
||||
ch, ok := s.channels[key]
|
||||
s.mu.RUnlock()
|
||||
if !ok {
|
||||
// Channel does not exist in the map.
|
||||
// Subscribe and insert it.
|
||||
err = s.sub.Subscribe(s.ctx, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Guard race condition to map with mutex.
|
||||
s.mu.Lock()
|
||||
ch = make(chan []byte)
|
||||
s.channels[key] = ch
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
return <-ch, nil
|
||||
}
|
||||
|
||||
func (s *Subscriber) Close() error {
|
||||
err := s.sub.Close()
|
||||
|
||||
for _, ch := range s.channels {
|
||||
close(ch)
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.channels = make(map[string]chan []byte)
|
||||
s.mu.Unlock()
|
||||
|
||||
return err
|
||||
}
|
||||
57
api/redis/subscriber_test.go
Normal file
57
api/redis/subscriber_test.go
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
package redis
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"thalos/api"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/go-redis/redismock/v8"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestSubscriber_Construct(t *testing.T) {
|
||||
client, _ := redismock.NewClientMock()
|
||||
ns := Namespace{Prefix: "prefix", ChainID: "8f2f6ec19400d372c9b3340b1438e9c805cf9e69be962fa81d055bc037ceed8d"}
|
||||
|
||||
s := NewSubscriber(client, ns)
|
||||
|
||||
assert.Equal(t, s.client, client)
|
||||
assert.Equal(t, s.ctx, client.Context())
|
||||
assert.NotNil(t, s.sub)
|
||||
assert.Equal(t, s.ns, ns)
|
||||
assert.Equal(t, s.timeout, 200*time.Millisecond)
|
||||
|
||||
s = NewSubscriber(client, ns, WithTimeout(4*time.Second))
|
||||
assert.Equal(t, s.timeout, 4*time.Second)
|
||||
}
|
||||
|
||||
func TestSubscriber_Read(t *testing.T) {
|
||||
expectedMessages := []string{"payload", "payload2", "payload3"}
|
||||
|
||||
server := miniredis.RunT(t)
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: server.Addr(),
|
||||
})
|
||||
|
||||
s := NewSubscriber(client, Namespace{Prefix: "prefix", ChainID: "d41dbd2921d5a377325661427090c6c508904d60920d6b7ea771c58da5299754"})
|
||||
|
||||
go func() {
|
||||
time.Sleep(time.Millisecond * 10)
|
||||
|
||||
for _, msg := range expectedMessages {
|
||||
server.Publish("prefix::d41dbd2921d5a377325661427090c6c508904d60920d6b7ea771c58da5299754::test", msg)
|
||||
}
|
||||
}()
|
||||
|
||||
// Redis pubsub does not guarentee that messages are sent in the correct order.
|
||||
for range expectedMessages {
|
||||
msg, err := s.Read(api.Channel{"test"})
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Contains(t, expectedMessages, string(msg))
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue