forked from siderolabs/grpc-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodec.go
81 lines (64 loc) · 1.99 KB
/
codec.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
// Copyright 2024 Siderolabs. All Rights Reserved.
// See LICENSE for licensing terms.
package proxy
import (
"errors"
"fmt"
"google.golang.org/grpc/encoding"
gproto "google.golang.org/grpc/encoding/proto"
"google.golang.org/grpc/mem"
)
// Codec returns a proxying [encoding.CodecV2] with the default protobuf codec as parent.
//
// See [CodecWithParent].
func Codec() encoding.CodecV2 {
if c := encoding.GetCodecV2(gproto.Name); c != nil {
return CodecWithParent(c)
}
panic(errors.New(`no codec named "proto" found`))
}
// CodecWithParent returns a proxying [encoding.CodecV2] with a user provided codec as parent.
//
// This codec is *crucial* to the functioning of the proxy. It allows the proxy server to be oblivious
// to the schema of the forwarded messages. It basically treats a gRPC message frame as raw bytes.
// However, if the server handler, or the client caller are not proxy-internal functions it will fall back
// to trying to decode the message using a fallback codec.
func CodecWithParent(fallback encoding.CodecV2) encoding.CodecV2 {
return &rawCodec{parentCodec: fallback}
}
type rawCodec struct {
parentCodec encoding.CodecV2
}
type frame struct {
payload []byte
}
// NewFrame constructs a frame for raw codec.
func NewFrame(payload []byte) any {
return &frame{payload: payload}
}
func (c *rawCodec) Marshal(v any) (data mem.BufferSlice, err error) {
f, ok := v.(*frame)
if !ok {
return c.parentCodec.Marshal(v)
}
if mem.IsBelowBufferPoolingThreshold(len(f.payload)) {
data = append(data, mem.SliceBuffer(f.payload))
} else {
pool := mem.DefaultBufferPool()
buf := pool.Get(len(f.payload))
copy(*buf, f.payload)
data = append(data, mem.NewBuffer(buf, pool))
}
return data, nil
}
func (c *rawCodec) Unmarshal(data mem.BufferSlice, v any) error {
dst, ok := v.(*frame)
if !ok {
return c.parentCodec.Unmarshal(data, v)
}
dst.payload = data.Materialize()
return nil
}
func (c *rawCodec) Name() string {
return fmt.Sprintf("proxy>%s", c.parentCodec.Name())
}