meowlib/server/router.go

103 lines
2.3 KiB
Go

package server
import (
"context"
"time"
"forge.redroom.link/yves/meowlib"
"github.com/go-redis/redis"
"google.golang.org/protobuf/proto"
)
type RedisRouter struct {
Name string
ServerIdentity *Identity
Client *redis.Client
Context context.Context
}
func NewRedisRouter(server *Identity, url string, password string, db int) *RedisRouter {
var r RedisRouter
r.ServerIdentity = server
r.Name = "Redis"
r.Client = redis.NewClient(&redis.Options{
Addr: url,
Password: password,
DB: db,
})
r.Context = context.Background()
return &r
}
func (r *RedisRouter) Route(msg *meowlib.ToServerMessage) (*meowlib.FromServerMessage, error) {
var from_server meowlib.FromServerMessage
if len(msg.Messages) > 0 { // user message
for _, usrmsg := range msg.Messages {
// serialize the message to store it as byte array into redis
out, err := proto.Marshal(usrmsg)
if err != nil {
return nil, err
}
r.Client.ZAdd(usrmsg.Destination, redis.Z{Score: float64(time.Now().Unix()), Member: out})
}
from_server.UuidAck = msg.Uuid
}
if len(msg.PullRequest) > 0 {
for _, rq := range msg.PullRequest {
msgcnt, err := r.Client.ZCount(rq.LookupKey, "-inf", "+inf").Result()
if err != nil {
return nil, err
}
res, err := r.Client.ZPopMin(rq.LookupKey, msgcnt).Result()
if err != nil {
return nil, err
}
for _, redismsg := range res {
//println(redismsg.Score)
val := redismsg.Member
test := val.(string)
var usrmsg meowlib.PackedUserMessage
err := proto.Unmarshal([]byte(test), &usrmsg)
if err != nil {
return nil, err
}
// add server timestamp
usrmsg.ServerTimestamp = append(usrmsg.ServerTimestamp, int64(redismsg.Score))
from_server.Chat = append(from_server.Chat, &usrmsg)
}
}
}
if msg.MatriochkaMessage != nil {
out, err := proto.Marshal(msg)
if err != nil {
return nil, err
}
r.Client.ZAdd("mtk", redis.Z{Score: float64(time.Now().Unix()), Member: out})
if msg.MatriochkaMessage.LookupKey != "" {
//r.Client.ZAdd("trk:" + msg.MatriochkaMessage.Next.Uuid,{})
}
from_server.UuidAck = msg.Uuid
}
if len(msg.KnownServers) > 0 {
}
/*
case "s": // servers list
breakmsgs
case "m": // matriochka
break
case "b": // broadcast
break
case "a": // admin
break
}
*/
return &from_server, nil
}