forked from 7574-sistemas-distribuidos/tp0-base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
123 lines (103 loc) · 2.33 KB
/
server.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package main
import (
"context"
"errors"
"fmt"
"net"
"sync"
"github.com/juliangcalderon-fiuba/distribuidos-tp0/common"
"github.com/juliangcalderon-fiuba/distribuidos-tp0/server/lottery"
)
const MAX_AGENCIES = 5
type server struct {
listener net.Listener
storageLock *sync.RWMutex
lotteryFinish *sync.WaitGroup
activeHandlers *sync.WaitGroup
}
func newServer(port int, listenBacklog int) (*server, error) {
_ = listenBacklog
address := fmt.Sprintf("0.0.0.0:%v", port)
listener, err := net.Listen("tcp", address)
if err != nil {
return nil, err
}
lotteryFinish := &sync.WaitGroup{}
lotteryFinish.Add(MAX_AGENCIES)
return &server{
listener: listener,
lotteryFinish: lotteryFinish,
storageLock: &sync.RWMutex{},
activeHandlers: &sync.WaitGroup{},
}, nil
}
func (s *server) run(ctx context.Context) (err error) {
listenerCloser := common.SpawnCloser(ctx, s.listener, closeListener)
defer func() {
closeErr := listenerCloser.Close()
err = errors.Join(err, closeErr)
}()
handlerCtx, cancelHandlerCtx := context.WithCancel(ctx)
defer func() {
cancelHandlerCtx()
s.activeHandlers.Wait()
}()
for {
h, err := s.acceptClient()
if err != nil {
return err
}
if h != nil {
s.activeHandlers.Add(1)
go func(h *handler) {
err := h.run(handlerCtx)
if err != nil {
if !errors.Is(err, net.ErrClosed) {
log.Error(common.FmtLog("handle_client", err))
}
}
s.activeHandlers.Done()
}(h)
}
}
}
func (s *server) acceptClient() (*handler, error) {
for {
conn, err := s.listener.Accept()
if err != nil {
return nil, err
}
h, err := createHandler(s, conn)
if err != nil {
log.Error(common.FmtLog("handshake", err))
continue
}
log.Info(common.FmtLog("handshake", nil,
"agency_id", h.agencyId,
))
return h, nil
}
}
func closeListener(listener net.Listener) error {
err := listener.Close()
if err != nil {
log.Error(common.FmtLog("close_listener", err))
return err
}
return nil
}
func (s *server) getWinners() (map[int][]int, error) {
s.storageLock.RLock()
allBets, err := lottery.LoadBets()
s.storageLock.RUnlock()
if err != nil {
return nil, err
}
winners := make(map[int][]int)
for _, bet := range allBets {
if bet.HasWon() {
winners[bet.Agency] = append(winners[bet.Agency], bet.Document)
}
}
return winners, nil
}