-
Notifications
You must be signed in to change notification settings - Fork 2
/
logs.go
231 lines (195 loc) · 6.86 KB
/
logs.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
220
221
222
223
224
225
226
227
228
229
230
231
package websocket
import (
"context"
"io"
"net"
"net/http"
"sync"
"time"
"github.com/aukilabs/go-tooling/pkg/errors"
"github.com/aukilabs/go-tooling/pkg/logs"
httpcmn "github.com/aukilabs/hagall-common/http"
"github.com/aukilabs/hagall-common/messages/hagallpb"
hwebsocket "github.com/aukilabs/hagall-common/websocket"
"golang.org/x/net/websocket"
)
type Logger func(format string, v ...interface{})
func HandlerWithLogs(h Handler, summaryInterval time.Duration) Handler {
ctx, cancel := context.WithCancel(context.Background())
handler := &handlerWithLogs{
Handler: h,
summaryInterval: summaryInterval,
closeSummaryWorker: cancel,
counter: make(map[string]int),
}
go handler.startSummaryWorker(ctx)
return handler
}
type handlerWithLogs struct {
Handler
originalRequest *http.Request
appKey string
summaryInterval time.Duration
closeSummaryWorker func()
counterMutex sync.Mutex
counter map[string]int
sessionID string
sessionUUID string
participantID uint32
}
func (h *handlerWithLogs) HandleConnect(conn *websocket.Conn) {
h.Handler.HandleConnect(conn)
req := conn.Request()
h.originalRequest = req
h.appKey = httpcmn.GetAppKeyFromHagallUserToken(httpcmn.GetUserTokenFromHTTPRequest(req))
logs.WithClientID(h.GetClientID()).
WithTag(logs.AppKeyTag, h.appKey).
Info("new client is connected")
}
func (h *handlerWithLogs) HandleParticipantJoin(ctx context.Context, handleFrame func(), sender hwebsocket.ResponseSender, msg hwebsocket.Msg) error {
if err := h.Handler.HandleParticipantJoin(ctx, handleFrame, sender, msg); err != nil {
return err
}
if h.CurrentParticipant() == nil {
var req hagallpb.ParticipantJoinRequest
// Check for error here is unecessary since it would never go here
// if the request parsing failed in h.Handler.HandleParticipantJoin.
msg.DataTo(&req)
logs.WithClientID(h.GetClientID()).
WithTag(logs.AppKeyTag, h.appKey).
WithTag(logs.SessionIDTag, req.SessionId).
WithTag("request_id", req.RequestId).
WithTag("http_headers", struct {
UserAgent string `json:"user_agent,omitempty"`
XForwardedFor string `json:"x_forwarded_for,omitempty"`
CloudFrontCountryName string `json:"cloudfront_viewer_country,omitempty"`
CloudFrontViewerAddress string `json:"cloudfront_viewer_address,omitempty"`
}{
UserAgent: h.originalRequest.UserAgent(),
XForwardedFor: h.originalRequest.Header.Get(httpcmn.XForwardedForHeaderKey),
CloudFrontCountryName: h.originalRequest.Header.Get(httpcmn.CloudFrontCountryNameHeaderKey),
CloudFrontViewerAddress: h.originalRequest.Header.Get(httpcmn.CloudFrontViewerAddressHeaderKey),
}).
Info("participant failed to join a session")
return nil
}
h.sessionID = h.GetSessions().GlobalSessionID(h.CurrentSession().ID)
h.sessionUUID = h.CurrentSession().SessionUUID
h.participantID = h.CurrentParticipant().ID
logs.WithClientID(h.GetClientID()).
WithTag(logs.AppKeyTag, h.appKey).
WithTag(logs.SessionIDTag, h.sessionID).
WithTag("session_uuid", h.sessionUUID).
WithTag(logs.ParticipantIDTag, h.participantID).
WithTag("http_headers", struct {
UserAgent string `json:"user_agent,omitempty"`
XForwardedFor string `json:"x_forwarded_for,omitempty"`
CloudFrontCountryName string `json:"cloudfront_viewer_country,omitempty"`
CloudFrontViewerAddress string `json:"cloudfront_viewer_address,omitempty"`
}{
UserAgent: h.originalRequest.UserAgent(),
XForwardedFor: h.originalRequest.Header.Get(httpcmn.XForwardedForHeaderKey),
CloudFrontCountryName: h.originalRequest.Header.Get(httpcmn.CloudFrontCountryNameHeaderKey),
CloudFrontViewerAddress: h.originalRequest.Header.Get(httpcmn.CloudFrontViewerAddressHeaderKey),
}).
Info("participant joined a session")
return nil
}
func (h *handlerWithLogs) HandleDisconnect(err error) {
h.Handler.HandleDisconnect(err)
logs.WithClientID(h.GetClientID()).
WithTag(logs.AppKeyTag, h.appKey).
WithTag(logs.SessionIDTag, h.sessionID).
WithTag(logs.ParticipantIDTag, h.participantID).
Info("client disconnected")
}
func (h *handlerWithLogs) Receiver() hwebsocket.Receiver {
receive := h.Handler.Receiver()
return func() (hwebsocket.Msg, int, error) {
msg, n, err := receive()
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) {
logs.WithClientID(h.GetClientID()).
WithTag(logs.AppKeyTag, h.appKey).
WithTag(logs.SessionIDTag, h.sessionID).
WithTag("session_uuid", h.sessionUUID).
WithTag(logs.ParticipantIDTag, h.participantID).
Error(errors.New("receiving message failed").Wrap(err))
} else if err == nil {
logs.WithClientID(h.GetClientID()).
WithTag(logs.AppKeyTag, h.appKey).
WithTag(logs.SessionIDTag, h.sessionID).
WithTag("session_uuid", h.sessionUUID).
WithTag(logs.ParticipantIDTag, h.participantID).
WithTag("msg_type", msg.TypeString()).
Debug("message received")
h.incCounter(msg.TypeString())
}
return msg, n, err
}
}
func (h *handlerWithLogs) Sender() hwebsocket.Sender {
sender := h.Handler.Sender()
return func(msg hwebsocket.Msg) (int, error) {
msgType := msg.TypeString()
n, err := sender(msg)
if err != nil && !errors.Is(err, net.ErrClosed) {
logs.WithClientID(h.GetClientID()).
WithTag(logs.AppKeyTag, h.appKey).
WithTag(logs.SessionIDTag, h.sessionID).
WithTag("session_uuid", h.sessionUUID).
WithTag(logs.ParticipantIDTag, h.participantID).
WithTag("msg_type", msgType).
Error(errors.New("sending message failed").Wrap(err))
} else if err == nil {
logs.WithClientID(h.GetClientID()).
WithTag(logs.AppKeyTag, h.appKey).
WithTag(logs.SessionIDTag, h.sessionID).
WithTag("session_uuid", h.sessionUUID).
WithTag(logs.ParticipantIDTag, h.participantID).
WithTag("msg_type", msgType).
Debug("message sent")
}
return n, err
}
}
func (h *handlerWithLogs) Close() {
h.Handler.Close()
h.closeSummaryWorker()
h.logSummary()
}
func (h *handlerWithLogs) startSummaryWorker(ctx context.Context) {
ticker := time.NewTicker(h.summaryInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
h.logSummary()
}
}
}
func (h *handlerWithLogs) incCounter(msgType string) {
h.counterMutex.Lock()
defer h.counterMutex.Unlock()
h.counter[msgType]++
}
func (h *handlerWithLogs) logSummary() {
h.counterMutex.Lock()
defer h.counterMutex.Unlock()
if len(h.counter) == 0 {
return
}
entry := logs.
WithClientID(h.GetClientID()).
WithTag(logs.AppKeyTag, h.appKey).
WithTag(logs.ParticipantIDTag, h.participantID).
WithTag(logs.SessionIDTag, h.sessionID).
WithTag("session_uuid", h.sessionUUID).
WithTag("time_interval", h.summaryInterval)
for k, v := range h.counter {
entry = entry.WithTag(k, v)
delete(h.counter, k)
}
entry.Info("inbound message summary")
}