-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.go
99 lines (87 loc) · 2.08 KB
/
encode.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
package main
import (
"encoding/base64"
"encoding/binary"
"encoding/json"
"fmt"
"os"
v1 "google.golang.org/grpc/binarylog/grpc_binarylog_v1"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
type EncodeCmd struct {
CmdCommon
CallID uint64 `optional:""`
}
func (cmd *EncodeCmd) Run(cli *Context) error {
f, err := openFile(cmd.LogInputFile, cli.Follow)
if err != nil {
return err
}
defer f.Close()
dec := json.NewDecoder(f)
conversations := map[uint64]conversation{}
w := os.Stdout
for dec.More() {
var mangled map[string]any
if err := dec.Decode(&mangled); err != nil {
return err
}
if _, hasMessage := mangled["message"]; hasMessage {
msg := mangled["message"].(map[string]any)
if _, hasDecoded := msg["decoded"]; hasDecoded {
var callId uint64
if err := json.Unmarshal([]byte(mangled["callId"].(string)), &callId); err != nil {
return err
}
conv, found := conversations[callId]
if !found {
return fmt.Errorf("cannot find headers for call ID %d", callId)
}
messageType, err := conv.RequestMessageType(cli)
if err != nil {
return err
}
dataMessage, err := newDynamicMessage(messageType)
if err != nil {
return err
}
decoded, err := json.Marshal(msg["decoded"])
if err != nil {
return err
}
delete(msg, "decoded")
if err := protojson.Unmarshal([]byte(decoded), dataMessage); err != nil {
return err
}
encoded, err := proto.Marshal(dataMessage)
if err != nil {
return err
}
msg["data"] = base64.StdEncoding.EncodeToString(encoded)
}
}
mb, err := json.Marshal(&mangled)
if err != nil {
return nil
}
var e v1.GrpcLogEntry
if err := protojson.Unmarshal(mb, &e); err != nil {
return err
}
conv := conversations[e.CallId]
conv.Record(&e)
conversations[e.CallId] = conv
b, err := proto.Marshal(&e)
if err != nil {
return err
}
if err := binary.Write(w, binary.BigEndian, uint32(len(b))); err != nil {
return err
}
if _, err := w.Write(b); err != nil {
return err
}
}
return nil
}