/
responder.go
74 lines (63 loc) · 2.44 KB
/
responder.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
// Copyright 2022 IBM Corp. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package request
import (
"sync"
"github.com/JeffXiesk/cerberus/log"
"github.com/JeffXiesk/cerberus/messenger"
pb "github.com/JeffXiesk/cerberus/protobufs"
"github.com/JeffXiesk/cerberus/tracing"
logger "github.com/rs/zerolog/log"
)
// Represents a responder to client requests
type Responder struct {
// Channel through which the log will push entries to the responder in sequence number order.
// The responder reads from this channel and responds to the corresponding client for each entry.
entriesChan chan *log.Entry
}
// Creates a new responder.
// A responder must be created before any protocol messages can be received from the network.
// Otherwise some responses to the client could be missed (in case entries are committed to the log before
// the responder has been created).
func NewResponder() *Responder {
return &Responder{
entriesChan: log.Entries(),
}
}
// Observes the log and responds to clients in commit order.
// Meant to be run as a separate goroutine.
// Decrements the provided wait group when done.
func (r *Responder) Start(wg *sync.WaitGroup) {
defer wg.Done()
// Read log entries (containing ordered batches) from
// the entries channel until the channel is closed.
for e := <-r.entriesChan; e != nil; e = <-r.entriesChan {
// For each ClientRequest in the ordered batch
if e.Batch != nil { ///1205
for _, req := range e.Batch.Requests {
logger.Trace().
Int32("clientId", req.RequestId.ClientId).
Int32("clientSn", req.RequestId.ClientSn).
Int32("sn", e.Sn).
Msg("Sending response to client.")
// Respond to the corresponding client.
tracing.MainTrace.Event(tracing.RESP_SEND, int64(req.RequestId.ClientId), int64(req.RequestId.ClientSn))
messenger.RespondToClient(req.RequestId.ClientId, &pb.ClientResponse{
OrderSn: e.Sn,
ClientSn: req.RequestId.ClientSn,
})
}
}
}
}