-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
grpc.go
837 lines (748 loc) · 20.9 KB
/
grpc.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
package runn
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"time"
"github.com/bufbuild/protocompile"
"github.com/bufbuild/protocompile/linker"
"github.com/goccy/go-json"
"github.com/jhump/protoreflect/v2/grpcreflect"
"github.com/k1LoW/runn/version"
"github.com/mitchellh/copystructure"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/dynamicpb"
)
type GRPCType string
const (
GRPCUnary GRPCType = "unary"
GRPCServerStreaming GRPCType = "server"
GRPCClientStreaming GRPCType = "client"
GRPCBidiStreaming GRPCType = "bidi"
)
type GRPCOp string
const (
GRPCOpMessage GRPCOp = "message"
GRPCOpReceive GRPCOp = "receive"
GRPCOpClose GRPCOp = "close"
)
const (
grpcStoreStatusKey = "status"
grpcStoreHeaderKey = "headers"
grpcStoreTrailerKey = "trailers"
grpcStoreMessageKey = "message"
grpcStoreMessagesKey = "messages"
grpcStoreResponseKey = "res"
)
type grpcRunner struct {
name string
target string
tls *bool
cacert []byte
cert []byte
key []byte
skipVerify bool
importPaths []string
protos []string
cc *grpc.ClientConn
refc *grpcreflect.Client
mds map[string]protoreflect.MethodDescriptor
operator *operator
}
type grpcMessage struct {
op GRPCOp
params map[string]any
}
type grpcRequest struct {
service string
method string
headers metadata.MD
messages []*grpcMessage
timeout time.Duration
}
func newGrpcRunner(name, target string) (*grpcRunner, error) {
return &grpcRunner{
name: name,
target: target,
mds: map[string]protoreflect.MethodDescriptor{},
}, nil
}
func (rnr *grpcRunner) Close() error {
if rnr.cc == nil {
rnr.refc = nil
return nil
}
rnr.refc = nil
return rnr.cc.Close()
}
func (rnr *grpcRunner) Run(ctx context.Context, r *grpcRequest) error {
if err := rnr.connectAndResolve(ctx); err != nil {
return err
}
key := strings.Join([]string{r.service, r.method}, "/")
md, ok := rnr.mds[key]
if !ok {
return fmt.Errorf("cannot find method: %s", key)
}
switch {
case !md.IsStreamingServer() && !md.IsStreamingClient():
rnr.operator.capturers.captureGRPCStart(rnr.name, GRPCUnary, r.service, r.method)
defer rnr.operator.capturers.captureGRPCEnd(rnr.name, GRPCUnary, r.service, r.method)
return rnr.invokeUnary(ctx, md, r)
case md.IsStreamingServer() && !md.IsStreamingClient():
rnr.operator.capturers.captureGRPCStart(rnr.name, GRPCServerStreaming, r.service, r.method)
defer rnr.operator.capturers.captureGRPCEnd(rnr.name, GRPCServerStreaming, r.service, r.method)
return rnr.invokeServerStreaming(ctx, md, r)
case !md.IsStreamingServer() && md.IsStreamingClient():
rnr.operator.capturers.captureGRPCStart(rnr.name, GRPCClientStreaming, r.service, r.method)
defer rnr.operator.capturers.captureGRPCEnd(rnr.name, GRPCClientStreaming, r.service, r.method)
return rnr.invokeClientStreaming(ctx, md, r)
case md.IsStreamingServer() && md.IsStreamingClient():
rnr.operator.capturers.captureGRPCStart(rnr.name, GRPCBidiStreaming, r.service, r.method)
defer rnr.operator.capturers.captureGRPCEnd(rnr.name, GRPCBidiStreaming, r.service, r.method)
return rnr.invokeBidiStreaming(ctx, md, r)
default:
return errors.New("something strange happened")
}
}
func (rnr *grpcRunner) connectAndResolve(ctx context.Context) error {
if rnr.cc == nil {
opts := []grpc.DialOption{
grpc.WithReturnConnectionError(),
grpc.WithUserAgent(fmt.Sprintf("runn/%s", version.Version)),
}
useTLS := true
if strings.HasSuffix(rnr.target, ":80") {
useTLS = false
}
if rnr.tls != nil {
useTLS = *rnr.tls
}
if useTLS {
tlsc := tls.Config{MinVersion: tls.VersionTLS12}
if len(rnr.cert) != 0 {
certificate, err := tls.X509KeyPair(rnr.cert, rnr.key)
if err != nil {
return err
}
tlsc.Certificates = []tls.Certificate{certificate}
}
if rnr.skipVerify {
//#nosec G402
tlsc.InsecureSkipVerify = true
} else if len(rnr.cacert) != 0 {
certpool, err := x509.SystemCertPool()
if err != nil {
// FIXME for Windows
// ref: https://github.com/golang/go/issues/18609
certpool = x509.NewCertPool()
}
if ok := certpool.AppendCertsFromPEM(rnr.cacert); !ok {
return errors.New("failed to append cacert")
}
tlsc.RootCAs = certpool
}
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(&tlsc)))
} else {
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
cctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
cc, err := grpc.DialContext(cctx, rnr.target, opts...)
if err != nil {
return err
}
rnr.cc = cc
}
if len(rnr.importPaths) > 0 || len(rnr.protos) > 0 {
if err := rnr.resolveAllMethodsUsingProtos(ctx); err != nil {
return err
}
}
if len(rnr.mds) == 0 {
// Fallback to reflection
if rnr.refc == nil {
rnr.refc = grpcreflect.NewClientAuto(ctx, rnr.cc)
}
if err := rnr.resolveAllMethodsUsingReflection(ctx); err != nil {
return err
}
}
return nil
}
func (rnr *grpcRunner) invokeUnary(ctx context.Context, md protoreflect.MethodDescriptor, r *grpcRequest) error {
if len(r.messages) != 1 {
return errors.New("unary RPC message should be 1")
}
if r.timeout > 0 {
cctx, cancel := context.WithTimeout(ctx, r.timeout)
ctx = cctx
defer cancel()
}
ctx = setHeaders(ctx, r.headers)
req := dynamicpb.NewMessage(md.Input())
rnr.operator.capturers.captureGRPCRequestHeaders(r.headers)
if err := rnr.setMessage(req, r.messages[0].params); err != nil {
return err
}
var (
resHeaders metadata.MD
resTrailers metadata.MD
)
res := dynamicpb.NewMessage(md.Output())
err := rnr.cc.Invoke(ctx, toEndpoint(md.FullName()), req, res, grpc.Header(&resHeaders), grpc.Trailer(&resTrailers))
stat, ok := status.FromError(err)
if !ok {
return err
}
d := map[string]any{
string(grpcStoreStatusKey): int(stat.Code()),
string(grpcStoreHeaderKey): resHeaders,
string(grpcStoreTrailerKey): resTrailers,
string(grpcStoreMessageKey): nil,
}
rnr.operator.capturers.captureGRPCResponseStatus(stat)
rnr.operator.capturers.captureGRPCResponseHeaders(resHeaders)
rnr.operator.capturers.captureGRPCResponseTrailers(resTrailers)
var messages []map[string]any
if stat.Code() == codes.OK {
b, err := protojson.MarshalOptions{UseProtoNames: true, UseEnumNumbers: true, EmitUnpopulated: true}.Marshal(res)
if err != nil {
return err
}
var msg map[string]any
if err := json.Unmarshal(b, &msg); err != nil {
return err
}
d[grpcStoreMessageKey] = msg
rnr.operator.capturers.captureGRPCResponseMessage(msg)
messages = append(messages, msg)
d[grpcStoreMessagesKey] = messages
} else {
d[grpcStoreMessageKey] = stat.Message()
}
rnr.operator.record(map[string]any{
string(grpcStoreResponseKey): d,
})
return nil
}
func (rnr *grpcRunner) invokeServerStreaming(ctx context.Context, md protoreflect.MethodDescriptor, r *grpcRequest) error {
if len(r.messages) != 1 {
return errors.New("server streaming RPC message should be 1")
}
if r.timeout > 0 {
cctx, cancel := context.WithTimeout(ctx, r.timeout)
ctx = cctx
defer cancel()
}
ctx = setHeaders(ctx, r.headers)
req := dynamicpb.NewMessage(md.Input())
rnr.operator.capturers.captureGRPCRequestHeaders(r.headers)
if err := rnr.setMessage(req, r.messages[0].params); err != nil {
return err
}
streamDesc := &grpc.StreamDesc{
StreamName: string(md.Name()),
ServerStreams: md.IsStreamingServer(),
ClientStreams: md.IsStreamingClient(),
}
stream, err := rnr.cc.NewStream(ctx, streamDesc, toEndpoint(md.FullName()))
if err != nil {
return err
}
if err := stream.SendMsg(req); err != nil {
return err
}
d := map[string]any{
string(grpcStoreHeaderKey): metadata.MD{},
string(grpcStoreTrailerKey): metadata.MD{},
string(grpcStoreMessageKey): nil,
}
var messages []map[string]any
for err == nil {
res := dynamicpb.NewMessage(md.Output())
err = stream.RecvMsg(res)
if err != nil {
if errors.Is(err, context.Canceled) {
break
}
if errors.Is(err, io.EOF) {
break
}
}
stat, ok := status.FromError(err)
if !ok {
return err
}
d[grpcStoreStatusKey] = int64(stat.Code())
rnr.operator.capturers.captureGRPCResponseStatus(stat)
if stat.Code() == codes.OK {
b, err := protojson.MarshalOptions{UseProtoNames: true, UseEnumNumbers: true, EmitUnpopulated: true}.Marshal(res)
if err != nil {
return err
}
var msg map[string]any
if err := json.Unmarshal(b, &msg); err != nil {
return err
}
d[grpcStoreMessageKey] = msg
rnr.operator.capturers.captureGRPCResponseMessage(msg)
messages = append(messages, msg)
} else {
d[grpcStoreMessageKey] = stat.Message()
}
}
d[grpcStoreMessagesKey] = messages
if h, err := stream.Header(); err == nil {
d[grpcStoreHeaderKey] = h
rnr.operator.capturers.captureGRPCResponseHeaders(h)
}
t := stream.Trailer()
d[grpcStoreTrailerKey] = t
rnr.operator.capturers.captureGRPCResponseTrailers(t)
rnr.operator.record(map[string]any{
string(grpcStoreResponseKey): d,
})
return nil
}
func (rnr *grpcRunner) invokeClientStreaming(ctx context.Context, md protoreflect.MethodDescriptor, r *grpcRequest) error {
if r.timeout > 0 {
cctx, cancel := context.WithTimeout(ctx, r.timeout)
ctx = cctx
defer cancel()
}
ctx = setHeaders(ctx, r.headers)
rnr.operator.capturers.captureGRPCRequestHeaders(r.headers)
streamDesc := &grpc.StreamDesc{
StreamName: string(md.Name()),
ServerStreams: md.IsStreamingServer(),
ClientStreams: md.IsStreamingClient(),
}
stream, err := rnr.cc.NewStream(ctx, streamDesc, toEndpoint(md.FullName()))
if err != nil {
return err
}
d := map[string]any{
string(grpcStoreHeaderKey): metadata.MD{},
string(grpcStoreTrailerKey): metadata.MD{},
string(grpcStoreMessageKey): nil,
}
var messages []map[string]any
for _, m := range r.messages {
switch m.op {
case GRPCOpMessage:
req := dynamicpb.NewMessage(md.Input())
if err := rnr.setMessage(req, m.params); err != nil {
return err
}
err := stream.SendMsg(req)
if errors.Is(err, context.Canceled) {
break
}
if errors.Is(err, io.EOF) {
break
}
default:
return fmt.Errorf("invalid op: %v", m.op)
}
}
res := dynamicpb.NewMessage(md.Output())
if err := stream.CloseSend(); err != nil {
return err
}
err = stream.RecvMsg(res)
stat, ok := status.FromError(err)
if !ok {
return err
}
d[grpcStoreStatusKey] = int64(stat.Code())
rnr.operator.capturers.captureGRPCResponseStatus(stat)
if stat.Code() == codes.OK {
b, err := protojson.MarshalOptions{UseProtoNames: true, UseEnumNumbers: true, EmitUnpopulated: true}.Marshal(res)
if err != nil {
return err
}
var msg map[string]any
if err := json.Unmarshal(b, &msg); err != nil {
return err
}
d[grpcStoreMessageKey] = msg
rnr.operator.capturers.captureGRPCResponseMessage(msg)
messages = append(messages, msg)
} else {
d[grpcStoreMessageKey] = stat.Message()
}
d[grpcStoreMessagesKey] = messages
if h, err := stream.Header(); err == nil {
d[grpcStoreHeaderKey] = h
rnr.operator.capturers.captureGRPCResponseHeaders(h)
}
t := stream.Trailer()
d[grpcStoreTrailerKey] = t
rnr.operator.capturers.captureGRPCResponseTrailers(t)
rnr.operator.record(map[string]any{
string(grpcStoreResponseKey): d,
})
return nil
}
func (rnr *grpcRunner) invokeBidiStreaming(ctx context.Context, md protoreflect.MethodDescriptor, r *grpcRequest) error {
if r.timeout > 0 {
return errors.New("unsupported timeout: for bidirectional streaming RPC")
}
ctx = setHeaders(ctx, r.headers)
rnr.operator.capturers.captureGRPCRequestHeaders(r.headers)
streamDesc := &grpc.StreamDesc{
StreamName: string(md.Name()),
ServerStreams: md.IsStreamingServer(),
ClientStreams: md.IsStreamingClient(),
}
stream, err := rnr.cc.NewStream(ctx, streamDesc, toEndpoint(md.FullName()))
if err != nil {
return err
}
d := map[string]any{
string(grpcStoreHeaderKey): metadata.MD{},
string(grpcStoreTrailerKey): metadata.MD{},
string(grpcStoreMessageKey): nil,
}
var messages []map[string]any
clientClose := false
L:
for _, m := range r.messages {
switch m.op {
case GRPCOpMessage:
req := dynamicpb.NewMessage(md.Input())
if err := rnr.setMessage(req, m.params); err != nil {
return err
}
err = stream.SendMsg(req)
if errors.Is(err, context.Canceled) {
break L
}
if errors.Is(err, io.EOF) {
break L
}
req.Reset()
case GRPCOpReceive:
res := dynamicpb.NewMessage(md.Output())
err := stream.RecvMsg(res)
if errors.Is(err, context.Canceled) {
break L
}
if errors.Is(err, io.EOF) {
break L
}
stat, ok := status.FromError(err)
if !ok {
return err
}
d[grpcStoreStatusKey] = int64(stat.Code())
rnr.operator.capturers.captureGRPCResponseStatus(stat)
if h, err := stream.Header(); err == nil {
d[grpcStoreHeaderKey] = h
rnr.operator.capturers.captureGRPCResponseHeaders(h)
}
if stat.Code() == codes.OK {
b, err := protojson.MarshalOptions{UseProtoNames: true, UseEnumNumbers: true, EmitUnpopulated: true}.Marshal(res)
if err != nil {
return err
}
var msg map[string]any
if err := json.Unmarshal(b, &msg); err != nil {
return err
}
d[grpcStoreMessageKey] = msg
rnr.operator.capturers.captureGRPCResponseMessage(msg)
messages = append(messages, msg)
} else {
d[grpcStoreMessageKey] = stat.Message()
}
case GRPCOpClose:
clientClose = true
err = stream.CloseSend()
rnr.operator.capturers.captureGRPCClientClose()
break L
default:
return fmt.Errorf("invalid op: %v", m.op)
}
}
stat, ok := status.FromError(err)
if !ok {
return err
}
if stat.Code() != codes.OK {
d[grpcStoreStatusKey] = int64(stat.Code())
d[grpcStoreMessageKey] = stat.Message()
rnr.operator.capturers.captureGRPCResponseStatus(stat)
}
if clientClose {
for {
res := dynamicpb.NewMessage(md.Output())
if err := stream.RecvMsg(res); err != nil {
if errors.Is(err, context.Canceled) {
break
}
if errors.Is(err, io.EOF) {
break
}
return err
} else {
if err := stream.CloseSend(); err != nil {
return err
}
}
}
} else {
if err == nil {
for {
res := dynamicpb.NewMessage(md.Output())
err := stream.RecvMsg(res)
if errors.Is(err, context.Canceled) {
break
}
if errors.Is(err, io.EOF) {
break
}
stat, ok := status.FromError(err)
if !ok {
return err
}
d[grpcStoreStatusKey] = int64(stat.Code())
rnr.operator.capturers.captureGRPCResponseStatus(stat)
if stat.Code() == codes.OK {
b, err := protojson.MarshalOptions{UseProtoNames: true, UseEnumNumbers: true, EmitUnpopulated: true}.Marshal(res)
if err != nil {
return err
}
var msg map[string]any
if err := json.Unmarshal(b, &msg); err != nil {
return err
}
d[grpcStoreMessageKey] = msg
rnr.operator.capturers.captureGRPCResponseMessage(msg)
messages = append(messages, msg)
} else {
d[grpcStoreMessageKey] = stat.Message()
}
}
}
}
// If the connection is not disconnected here, it will fall into a race condition when retrieving the trailer.
if err := rnr.cc.Close(); err != nil {
return err
}
rnr.cc = nil
rnr.refc = nil
d[grpcStoreMessagesKey] = messages
if h, err := stream.Header(); len(d[grpcStoreHeaderKey].(metadata.MD)) == 0 && err == nil {
d[grpcStoreHeaderKey] = h
}
t, ok := dcopy(stream.Trailer()).(metadata.MD)
if !ok {
return fmt.Errorf("failed to copy trailers: %s", t)
}
d[grpcStoreTrailerKey] = t
rnr.operator.capturers.captureGRPCResponseTrailers(t)
rnr.operator.record(map[string]any{
string(grpcStoreResponseKey): d,
})
return nil
}
func setHeaders(ctx context.Context, h metadata.MD) context.Context {
var kv []string
for k, v := range h {
kv = append(kv, k)
kv = append(kv, v...)
}
ctx = metadata.AppendToOutgoingContext(ctx, kv...)
return ctx
}
func (rnr *grpcRunner) setMessage(req proto.Message, message map[string]any) error {
// Lazy expand due to the possibility of computing variables between multiple messages.
e, err := rnr.operator.expandBeforeRecord(message)
if err != nil {
return err
}
m, ok := e.(map[string]any)
if !ok {
return fmt.Errorf("invalid message: %v", e)
}
rnr.operator.capturers.captureGRPCRequestMessage(m)
b, err := json.Marshal(e)
if err != nil {
return err
}
return protojson.Unmarshal(b, req)
}
func (rnr *grpcRunner) resolveAllMethodsUsingReflection(ctx context.Context) error {
svcs, err := rnr.refc.ListServices()
if err != nil {
return err
}
for _, svc := range svcs {
d, err := rnr.findDescripter(svc)
if err != nil {
return fmt.Errorf("failed to find descriptor: %w", err)
}
sd, ok := d.(protoreflect.ServiceDescriptor)
if !ok {
return fmt.Errorf("invalid descriptor: %v", d)
}
mds := sd.Methods()
for j := 0; j < mds.Len(); j++ {
md := mds.Get(j)
key := strings.Join([]string{string(sd.FullName()), string(md.Name())}, "/")
rnr.mds[key] = md
}
}
return nil
}
func (rnr *grpcRunner) findDescripter(svc protoreflect.FullName) (protoreflect.Descriptor, error) {
d, err := protoregistry.GlobalFiles.FindDescriptorByName(svc)
if err != nil && !errors.Is(err, protoregistry.NotFound) {
return nil, err
}
if err == nil {
return d, nil
}
fd, err := rnr.refc.FileContainingSymbol(svc)
if err != nil {
return nil, err
}
if err := protoregistry.GlobalFiles.RegisterFile(fd); err != nil {
return nil, err
}
return protoregistry.GlobalFiles.FindDescriptorByName(svc)
}
func (rnr *grpcRunner) resolveAllMethodsUsingProtos(ctx context.Context) error {
protos, err := fetchPaths(strings.Join(rnr.protos, string(os.PathListSeparator)))
if err != nil {
return err
}
importPaths, protos, err := resolvePaths(rnr.importPaths, protos...)
if err != nil {
return err
}
comp := protocompile.Compiler{
Resolver: protocompile.WithStandardImports(&protocompile.SourceResolver{
ImportPaths: importPaths,
}),
}
fds, err := comp.Compile(ctx, protos...)
if err != nil {
return err
}
if err := registerFiles(fds); err != nil {
return err
}
for _, fd := range fds {
for i := 0; i < fd.Services().Len(); i++ {
svc := fd.Services().Get(i)
for j := 0; j < svc.Methods().Len(); j++ {
m := svc.Methods().Get(j)
key := fmt.Sprintf("%s/%s", svc.FullName(), m.Name())
rnr.mds[key] = m
}
}
}
return nil
}
func dcopy(in any) any {
return copystructure.Must(copystructure.Copy(in))
}
func toEndpoint(mn protoreflect.FullName) string {
splitted := strings.Split(string(mn), ".")
service := strings.Join(splitted[:len(splitted)-1], ".")
method := splitted[len(splitted)-1]
return fmt.Sprintf("/%s/%s", service, method)
}
func registerFiles(fds linker.Files) (err error) {
for _, fd := range fds {
// Skip registration of already registered descriptors
if _, err := protoregistry.GlobalFiles.FindFileByPath(fd.Path()); !errors.Is(protoregistry.NotFound, err) {
continue
}
// Skip registration of conflicted descriptors
conflict := false
rangeTopLevelDescriptors(fd, func(d protoreflect.Descriptor) {
if _, err := protoregistry.GlobalFiles.FindDescriptorByName(d.FullName()); err == nil {
conflict = true
}
})
if conflict {
continue
}
if err := protoregistry.GlobalFiles.RegisterFile(fd); err != nil {
return err
}
}
return nil
}
// copy from google.golang.org/protobuf/reflect/protoregistry.
func rangeTopLevelDescriptors(fd protoreflect.FileDescriptor, f func(protoreflect.Descriptor)) {
eds := fd.Enums()
for i := eds.Len() - 1; i >= 0; i-- {
f(eds.Get(i))
vds := eds.Get(i).Values()
for i := vds.Len() - 1; i >= 0; i-- {
f(vds.Get(i))
}
}
mds := fd.Messages()
for i := mds.Len() - 1; i >= 0; i-- {
f(mds.Get(i))
}
xds := fd.Extensions()
for i := xds.Len() - 1; i >= 0; i-- {
f(xds.Get(i))
}
sds := fd.Services()
for i := sds.Len() - 1; i >= 0; i-- {
f(sds.Get(i))
}
}
func resolvePaths(importPaths []string, protos ...string) ([]string, []string, error) {
const sep = string(filepath.Separator)
if len(importPaths) == 0 {
return importPaths, protos, nil
}
importPaths = unique(importPaths)
var resolvedIPaths []string
for _, p := range importPaths {
abs, err := filepath.Abs(p)
if err != nil {
return nil, nil, err
}
resolvedIPaths = append(resolvedIPaths, abs)
}
resolvedIPaths = unique(resolvedIPaths)
var resolvedProtos []string
for _, p := range protos {
abs, err := filepath.Abs(p)
if err != nil {
return nil, nil, err
}
for _, ip := range resolvedIPaths {
if strings.HasPrefix(abs, ip+sep) {
resolvedProtos = append(resolvedProtos, strings.TrimPrefix(abs, ip+sep))
}
}
}
resolvedProtos = unique(resolvedProtos)
return resolvedIPaths, resolvedProtos, nil
}