-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgorpm.go
219 lines (197 loc) · 4.94 KB
/
gorpm.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
package gorpm
import (
"bufio"
"bytes"
"encoding/hex"
"fmt"
"io"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
)
const (
MessageRequest = "1"
MessageResponse = "2"
MessageReply = "3"
)
// GorMessage stores data and parsed information in a incoming request
type GorMessage struct {
ID string
Type string
Meta [][]byte // Meta is an array size of 4, containing: request type, uuid, timestamp, latency
RawMeta []byte //
HTTP []byte // Raw HTTP payload
}
// gorMessagePack is temporary for request/response/reply message, will be clear when timeout or complete
type gorMessagePack struct {
Request *GorMessage
Response *GorMessage
Reply *GorMessage
created time.Time
}
func (pack *gorMessagePack) Ready() bool {
return pack.Request != nil && pack.Response != nil && pack.Reply != nil
}
// Gor is the middleware itself
type Gor struct {
lock *sync.Mutex
msgPackMap map[string]*gorMessagePack
input chan string
parsed chan *GorMessage
stderr io.Writer
//callback when request ok, you can modify replay request body here
onRequestFunc func(req *GorMessage) *GorMessage
//callback when all message complete
onCompleteFunc func(req, resp, reply *GorMessage)
}
// CreateGor creates a Gor object
func CreateGor() *Gor {
gor := &Gor{
lock: new(sync.Mutex),
msgPackMap: make(map[string]*gorMessagePack),
input: make(chan string),
parsed: make(chan *GorMessage),
stderr: os.Stderr,
}
return gor
}
func (gor *Gor) OnRequest(msgReqFunc func(req *GorMessage) *GorMessage) {
gor.onRequestFunc = msgReqFunc
}
func (gor *Gor) OnComplete(msgCompleteFunc func(req, resp, reply *GorMessage)) {
gor.onCompleteFunc = msgCompleteFunc
}
func (gor *Gor) getMsgPack(id string) *gorMessagePack {
gor.lock.Lock()
defer gor.lock.Unlock()
pack, ok := gor.msgPackMap[id]
if ok {
return pack
}
pack = &gorMessagePack{created: time.Now()}
gor.msgPackMap[id] = pack
return pack
}
func (gor *Gor) deleteMsgPack(id string) {
gor.lock.Lock()
defer gor.lock.Unlock()
delete(gor.msgPackMap, id)
}
// emit triggers the registered event callback when receiving certain GorMessage
func (gor *Gor) emit(msg *GorMessage) error {
pack := gor.getMsgPack(msg.ID)
switch msg.Type {
case MessageRequest:
pack.Request = msg
if gor.onRequestFunc != nil {
msg = gor.onRequestFunc(msg)
}
fmt.Fprintf(os.Stdout, gor.hexData(msg))
case MessageResponse:
pack.Response = msg
case MessageReply:
pack.Reply = msg
default:
return fmt.Errorf("invalid message type: %s", msg.Type)
}
if !pack.Ready() {
return nil
}
if gor.onCompleteFunc != nil {
gor.onCompleteFunc(pack.Request, pack.Response, pack.Reply)
}
gor.deleteMsgPack(msg.ID)
return nil
}
// HexData translates a GorMessage into middleware dataflow string
func (gor *Gor) hexData(msg *GorMessage) string {
encodeList := [3][]byte{msg.RawMeta, []byte("\n"), msg.HTTP}
encodedList := make([]string, 3)
for i, val := range encodeList {
encodedList[i] = hex.EncodeToString(val)
}
encodedList = append(encodedList, "\n")
return strings.Join(encodedList, "")
}
// parseMessage parses string middleware dataflow into a GorMessage
func (gor *Gor) parseMessage(line string) (*GorMessage, error) {
payload, err := hex.DecodeString(strings.TrimSpace(line))
if err != nil {
return nil, err
}
metaPos := bytes.Index(payload, []byte("\n"))
metaRaw := payload[:metaPos]
metaArr := bytes.Split(metaRaw, []byte(" "))
msgType, pid := metaArr[0], string(metaArr[1])
httpPayload := payload[metaPos+1:]
return &GorMessage{
ID: pid,
Type: string(msgType),
Meta: metaArr,
RawMeta: metaRaw,
HTTP: httpPayload,
}, nil
}
func (gor *Gor) clearTimeoutMsgPack(interval int) {
ticker := time.NewTicker(time.Second * 1)
for range ticker.C {
gor.lock.Lock()
for id, pack := range gor.msgPackMap {
if time.Since(pack.created) > time.Duration(interval) {
delete(gor.msgPackMap, id)
}
}
gor.lock.Unlock()
}
}
func (gor *Gor) preProcessor() {
for {
line := <-gor.input
if msg, err := gor.parseMessage(line); err != nil {
gor.stderr.Write([]byte(err.Error()))
} else {
gor.parsed <- msg
}
}
}
func (gor *Gor) receiver() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
gor.input <- scanner.Text()
}
}
func (gor *Gor) processor() {
for {
msg := <-gor.parsed
gor.emit(msg)
}
}
func (gor *Gor) shutdown() {
}
func (gor *Gor) handleSignal(sigChan chan os.Signal) {
for {
s := <-sigChan
gor.stderr.Write([]byte(fmt.Sprintf("receive a signal %s\n", s.String())))
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP, syscall.SIGINT:
gor.shutdown()
return
default:
return
}
}
}
// Run is entrypoint of Gor
func (gor *Gor) Run() {
go gor.receiver()
go gor.preProcessor()
go gor.processor()
go gor.clearTimeoutMsgPack(30)
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM,
syscall.SIGINT, syscall.SIGSTOP)
gor.handleSignal(c)
}