Nexus/pkg/internal/grpc/stream.go

87 lines
2.3 KiB
Go
Raw Normal View History

2024-10-19 14:36:33 +00:00
package grpc
import (
"context"
"fmt"
2024-10-20 11:04:41 +00:00
"git.solsynth.dev/hypernet/nexus/pkg/http/ws"
2024-10-19 14:36:33 +00:00
"git.solsynth.dev/hypernet/nexus/pkg/proto"
"github.com/samber/lo"
)
2024-10-20 11:04:41 +00:00
func (v *Server) CountStreamConnection(ctx context.Context, request *proto.CountConnectionRequest) (*proto.CountConnectionResponse, error) {
out := ws.ClientCount(uint(request.GetUserId()))
2024-10-19 14:36:33 +00:00
return &proto.CountConnectionResponse{
Count: int64(out),
}, nil
}
2024-10-20 11:04:41 +00:00
func (v *Server) PushStream(ctx context.Context, request *proto.PushStreamRequest) (*proto.PushStreamResponse, error) {
2024-10-19 14:36:33 +00:00
var cnt int
var success int
var errs []error
if request.UserId != nil {
2024-10-20 11:04:41 +00:00
cnt, success, errs = ws.WebsocketPush(uint(request.GetUserId()), request.GetBody())
2024-10-19 14:36:33 +00:00
} else if request.ClientId != nil {
2024-10-20 11:04:41 +00:00
cnt, success, errs = ws.WebsocketPushDirect(request.GetClientId(), request.GetBody())
2024-10-19 14:36:33 +00:00
} else {
return nil, fmt.Errorf("you must give one of the user id or client id")
}
if len(errs) > 0 {
// Partial fail
return &proto.PushStreamResponse{
IsAllSuccess: false,
AffectedCount: int64(success),
FailedCount: int64(cnt - success),
}, nil
} else if cnt > 0 && success == 0 {
// All fail
return nil, fmt.Errorf("all push request failed: %v", errs)
}
return &proto.PushStreamResponse{
IsAllSuccess: true,
AffectedCount: int64(success),
FailedCount: int64(cnt - success),
}, nil
}
2024-10-20 11:04:41 +00:00
func (v *Server) PushStreamBatch(ctx context.Context, request *proto.PushStreamBatchRequest) (*proto.PushStreamResponse, error) {
2024-10-19 14:36:33 +00:00
var cnt int
var success int
var errs []error
if len(request.UserId) != 0 {
2024-10-20 11:04:41 +00:00
cnt, success, errs = ws.WebsocketPushBatch(
2024-10-19 14:36:33 +00:00
lo.Map(request.GetUserId(), func(item uint64, idx int) uint {
return uint(item)
},
), request.GetBody(),
)
}
if len(request.ClientId) != 0 {
2024-10-20 11:04:41 +00:00
cCnt, cSuccess, cErrs := ws.WebsocketPushBatchDirect(request.GetClientId(), request.GetBody())
2024-10-19 14:36:33 +00:00
cnt += cCnt
success += cSuccess
errs = append(errs, cErrs...)
}
if len(errs) > 0 {
// Partial fail
return &proto.PushStreamResponse{
IsAllSuccess: false,
AffectedCount: int64(success),
FailedCount: int64(cnt - success),
}, nil
} else if cnt > 0 && success == 0 {
// All fail
return nil, fmt.Errorf("all push request failed: %v", errs)
}
return &proto.PushStreamResponse{
IsAllSuccess: true,
AffectedCount: int64(success),
FailedCount: int64(cnt - success),
}, nil
}