/
controller_ssgen_service.go
75 lines (62 loc) · 1.55 KB
/
controller_ssgen_service.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
package grpc
import (
"context"
"sync"
"connectrpc.com/connect"
"github.com/samber/lo"
log "github.com/sirupsen/logrus"
"google.golang.org/protobuf/types/known/emptypb"
"github.com/traPtitech/neoshowcase/pkg/domain"
"github.com/traPtitech/neoshowcase/pkg/infrastructure/grpc/pb"
)
type ssGenConnection struct {
reqSender chan<- *pb.SSGenRequest
}
type ControllerSSGenService struct {
ssGenConnections []*ssGenConnection
lock sync.Mutex
}
func NewControllerSSGenService() domain.ControllerSSGenService {
return &ControllerSSGenService{}
}
func (s *ControllerSSGenService) ConnectSSGen(ctx context.Context, _ *connect.Request[emptypb.Empty], st *connect.ServerStream[pb.SSGenRequest]) error {
id := domain.NewID()
log.WithField("id", id).Info("new ssgen connection")
defer log.WithField("id", id).Info("ssgen connection closed")
reqSender := make(chan *pb.SSGenRequest)
conn := &ssGenConnection{reqSender: reqSender}
s.lock.Lock()
s.ssGenConnections = append(s.ssGenConnections, conn)
s.lock.Unlock()
defer func() {
s.lock.Lock()
defer s.lock.Unlock()
s.ssGenConnections = lo.Without(s.ssGenConnections, conn)
}()
loop:
for {
select {
case req, ok := <-reqSender:
if !ok {
break loop
}
err := st.Send(req)
if err != nil {
return err
}
case <-ctx.Done():
break loop
}
}
return nil
}
func (s *ControllerSSGenService) BroadcastSSGen(req *pb.SSGenRequest) {
s.lock.Lock()
defer s.lock.Unlock()
for _, ssgen := range s.ssGenConnections {
select {
case ssgen.reqSender <- req:
default:
}
}
}