meowlib/server/router.go

88 lines
2.0 KiB
Go
Raw Normal View History

package server
import (
"context"
"time"
"forge.redroom.link/yves/meowlib"
"github.com/go-redis/redis"
2022-10-22 22:40:03 +02:00
"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
}
2022-10-22 22:40:03 +02:00
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 {
2022-10-22 22:40:03 +02:00
// serialize the message to store it as byte array into redis
out, err := proto.Marshal(msg)
if err != nil {
return nil, err
}
r.Client.ZAdd(usrmsg.Destination, redis.Z{float64(time.Now().Unix()), out})
}
from_server.UuidAck = msg.Uuid
}
if len(msg.PullRequest) > 0 {
for _, rq := range msg.PullRequest {
2022-10-22 22:40:03 +02:00
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.([]byte)
var usrmsg meowlib.PackedUserMessage
err := proto.Unmarshal(val, &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)
}
}
}
/*
case "q": // query messages
break
case "s": // servers list
2022-10-22 22:40:03 +02:00
breakmsgs
case "m": // matriochka
break
case "b": // broadcast
break
case "a": // admin
break
}
*/
2022-10-22 22:40:03 +02:00
return &from_server, nil
}