-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathcompiler.go
More file actions
1524 lines (1251 loc) · 45.3 KB
/
compiler.go
File metadata and controls
1524 lines (1251 loc) · 45.3 KB
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package grpcdatasource
import (
"context"
"errors"
"fmt"
"slices"
"strings"
"github.com/bufbuild/protocompile"
"github.com/tidwall/gjson"
protoref "google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/dynamicpb"
"github.com/wundergraph/graphql-go-tools/v2/pkg/ast"
"github.com/wundergraph/graphql-go-tools/v2/pkg/pool"
)
const (
// InvalidRef is a constant used to indicate that a reference is invalid.
InvalidRef = -1
)
func fromGraphQLType(s []byte) DataType {
switch string(s) {
case "ID", "String":
return DataTypeString
case "Int":
// https://spec.graphql.org/October2021/#sec-Int
// Fields returning the type Int expect to encounter 32-bit integer internal values.
return DataTypeInt32
case "Float":
// https://spec.graphql.org/October2021/#sec-Float
// Fields returning the type Float expect to encounter double-precision floating-point internal values.
return DataTypeDouble
case "Boolean":
return DataTypeBool
default:
// Fallback to bytes for unknown types to handle raw data.
return DataTypeBytes
}
}
// parseDataType converts a string type name to a DataType constant.
// Returns DataTypeUnknown if the type is not recognized.
func parseDataType(kind protoref.Kind) DataType {
if _, ok := dataTypeMap[kind]; !ok {
return DataTypeUnknown
}
return dataTypeMap[kind]
}
type NodeKind int
const (
NodeKindMessage NodeKind = iota + 1
NodeKindEnum
NodeKindService
NodeKindUnknown
)
type node struct {
ref int
kind NodeKind
}
// Document represents a compiled protobuf document with all its services, messages, and methods.
type Document struct {
nodes map[uint64]node
Package string // The package name of the protobuf document
Imports []string // The imports of the protobuf document
Services []Service // All services defined in the document
Enums []Enum // All enums defined in the document
Messages []Message // All messages defined in the document
Methods []Method // All methods from all services in the document
}
// newNode creates a new node in the document.
func (d *Document) newNode(ref int, name string, kind NodeKind) {
digest := pool.Hash64.Get()
defer pool.Hash64.Put(digest)
_, _ = digest.WriteString(name)
d.nodes[digest.Sum64()] = node{
ref: ref,
kind: kind,
}
}
// nodeByName returns a node by its name.
// Returns false if the node does not exist.
func (d *Document) nodeByName(name string) (node, bool) {
digest := pool.Hash64.Get()
defer pool.Hash64.Put(digest)
_, _ = digest.WriteString(name)
node, exists := d.nodes[digest.Sum64()]
return node, exists
}
// appendMessage appends a message to the document and returns the reference index.
func (d *Document) appendMessage(message Message) int {
d.Messages = append(d.Messages, message)
return len(d.Messages) - 1
}
// appendEnum appends an enum to the document and returns the reference index.
func (d *Document) appendEnum(enum Enum) int {
d.Enums = append(d.Enums, enum)
return len(d.Enums) - 1
}
// appendService appends a service to the document and returns the reference index.
func (d *Document) appendService(service Service) int {
d.Services = append(d.Services, service)
return len(d.Services) - 1
}
// Service represents a gRPC service with methods.
type Service struct {
Name string // The name of the service
FullName string // The full name of the service
MethodsRefs []int // References to methods in the Document.Methods slice
}
// Method represents a gRPC method with input and output message types.
type Method struct {
Name string // The name of the method
InputName string // The name of the input message type
InputRef int // Reference to the input message in the Document.Messages slice
OutputName string // The name of the output message type
OutputRef int // Reference to the output message in the Document.Messages slice
}
// Message represents a protobuf message type with its fields.
type Message struct {
Fields map[uint64]Field
Name string // The name of the message
Desc protoref.MessageDescriptor // The protobuf descriptor for the message
}
// GetField returns a field by its name.
// Returns nil if no field with the given name exists.
func (m *Message) GetField(name string) *Field {
digest := pool.Hash64.Get()
defer pool.Hash64.Put(digest)
_, _ = digest.WriteString(name)
field, found := m.Fields[digest.Sum64()]
if !found {
return nil
}
return &field
}
func (m *Message) SetField(f Field) {
digest := pool.Hash64.Get()
defer pool.Hash64.Put(digest)
_, _ = digest.WriteString(f.Name)
if m.Fields == nil {
m.Fields = make(map[uint64]Field)
}
m.Fields[digest.Sum64()] = f
}
// AllocFields allocates a new map of fields with the given count.
func (m *Message) AllocFields(count int) {
m.Fields = make(map[uint64]Field, count)
}
// Field represents a field in a protobuf message.
type Field struct {
Name string // The name of the field
Type DataType // The data type of the field
Number int32 // The field number in the protobuf message
Ref int // Reference to the field (used for complex types)
Repeated bool // Whether the field is a repeated field (array/list)
Optional bool // Whether the field is optional
MessageRef int // If the field is a message type, this points to the message definition
}
func (f *Field) IsMessage() bool {
return f.Type == DataTypeMessage
}
func (f *Field) ResolveUnderlyingMessage(doc *Document) *Message {
if f.MessageRef >= 0 {
return &doc.Messages[f.MessageRef]
}
return nil
}
// Enum represents a protobuf enum type with its values.
type Enum struct {
Name string // The name of the enum
Values []EnumValue // The values in the enum
}
// EnumValue represents a single value in a protobuf enum.
type EnumValue struct {
Name string // The name of the enum value
GraphqlValue string // The target value of the enum value
Number int32 // The numeric value of the enum value
}
// RPCCompiler compiles protobuf schema strings into a Document and can
// build protobuf messages from JSON data based on the schema.
type RPCCompiler struct {
doc *Document // The compiled Document
runtime *runtimeSchema // The compiled runtime schema
}
// ServiceByName returns a Service by its name.
// Returns an empty Service if no service with the given name exists.
func (d *Document) ServiceByName(name string) *Service {
node, found := d.nodeByName(name)
if !found || node.kind != NodeKindService {
return nil
}
return &d.Services[node.ref]
}
// MessageByName returns a Message by its name.
// Returns an empty Message if no message with the given name exists.
// We only expect this function to return false if either the message name was provided incorrectly,
// or the schema and mapping was not properly configured.
func (d *Document) MessageByName(name string) (Message, bool) {
node, found := d.nodeByName(name)
if !found || node.kind != NodeKindMessage {
return Message{}, false
}
return d.Messages[node.ref], true
}
// MessageRefByName returns the index of a Message in the Messages slice by its name.
// Returns -1 if no message with the given name exists.
func (d *Document) MessageRefByName(name string) int {
node, found := d.nodeByName(name)
if !found || node.kind != NodeKindMessage {
return InvalidRef
}
return node.ref
}
// MessageByRef returns a Message by its reference index.
func (d *Document) MessageByRef(ref int) Message {
return d.Messages[ref]
}
// EnumByName returns an Enum by its name.
// Returns false if the enum does not exist.
func (d *Document) EnumByName(name string) (Enum, bool) {
node, found := d.nodeByName(name)
if !found || node.kind != NodeKindEnum {
return Enum{}, false
}
return d.Enums[node.ref], true
}
// NewProtoCompiler compiles the protobuf schema into a Document structure.
// It extracts information about services, methods, messages, and enums
// from the protobuf schema.
func NewProtoCompiler(schema string, mapping *GRPCMapping) (*RPCCompiler, error) {
// Create a protocompile compiler with standard imports
c := protocompile.Compiler{
Resolver: protocompile.WithStandardImports(&protocompile.SourceResolver{
Accessor: protocompile.SourceAccessorFromMap(map[string]string{
"": schema,
}),
}),
}
// Compile the schema
fd, err := c.Compile(context.Background(), "")
if err != nil {
return nil, err
}
if len(fd) == 0 {
return nil, fmt.Errorf("no files compiled")
}
schemaFile := fd[0]
pc := &RPCCompiler{
doc: &Document{
nodes: make(map[uint64]node),
Package: string(schemaFile.Package()),
},
}
// Extract information from the compiled file descriptor
pc.doc.Package = string(schemaFile.Package())
// We potentially have imported other files and need to resolve the types first
// before we can parse the schema.
for i := 0; i < schemaFile.Imports().Len(); i++ {
protoImport := schemaFile.Imports().Get(i)
pc.doc.Imports = append(pc.doc.Imports, string(protoImport.Path()))
pc.processFile(protoImport, mapping)
}
// Process the schema file
pc.processFile(schemaFile, mapping)
runtime, err := newSchemaRuntime(pc.doc)
if err != nil {
return nil, err
}
pc.runtime = runtime
return pc, nil
}
func (p *RPCCompiler) processFile(f protoref.FileDescriptor, mapping *GRPCMapping) {
// Process all enums in the schema
for i := 0; i < f.Enums().Len(); i++ {
enum := p.parseEnum(f.Enums().Get(i), mapping)
ref := p.doc.appendEnum(enum)
p.doc.newNode(ref, enum.Name, NodeKindEnum)
}
// Process all messages in the schema
messages := p.parseMessageDefinitions(f.Messages())
for _, message := range messages {
ref := p.doc.appendMessage(message)
p.doc.newNode(ref, message.Name, NodeKindMessage)
}
// We need to reiterate over the messages to handle recursive types.
for ref, message := range p.doc.Messages {
p.enrichMessageData(ref, message.Desc)
}
// Process all services in the schema
for i := 0; i < f.Services().Len(); i++ {
service := p.parseService(f.Services().Get(i))
ref := p.doc.appendService(service)
p.doc.newNode(ref, service.Name, NodeKindService)
}
}
// ServiceCall represents a single gRPC service call with its input and output messages.
type ServiceCall struct {
// ServiceName is the name of the gRPC service to call
ServiceName string
// MethodName is the name of the method on the service to call
MethodName string
// Input is the input message for the gRPC call
Input protoref.Message
// Output is the output message for the gRPC call
Output protoref.Message
// RPC is the call that was made to the gRPC service
RPC *RPCCall
// Skip is true if the service call should not be invoked
Skip bool
}
func (s *ServiceCall) MethodFullName() string {
var builder strings.Builder
builder.Grow(len(s.ServiceName) + len(s.MethodName) + 2)
builder.WriteRune('/')
builder.WriteString(s.ServiceName)
builder.WriteRune('/')
builder.WriteString(s.MethodName)
return builder.String()
}
func (p *RPCCompiler) CompileFetches(graph *DependencyGraph, fetches []FetchItem, inputData gjson.Result) ([]ServiceCall, error) {
serviceCalls := make([]ServiceCall, 0, len(fetches))
for _, node := range fetches {
serviceCall, err := p.CompileNode(graph, node, inputData)
if err != nil {
return nil, err
}
if serviceCall.Skip {
continue
}
graph.SetFetchData(node.ID, &serviceCall)
serviceCalls = append(serviceCalls, serviceCall)
}
return serviceCalls, nil
}
func (p *RPCCompiler) CompileNode(graph *DependencyGraph, fetch FetchItem, inputData gjson.Result) (ServiceCall, error) {
call := fetch.Plan
outputMessage, ok := p.doc.MessageByName(call.Response.Name)
if !ok {
return ServiceCall{}, fmt.Errorf("output message %s not found in document", call.Response.Name)
}
response, err := p.newEmptyMessage(outputMessage)
if err != nil {
return ServiceCall{}, err
}
var request protoref.Message
inputMessage, ok := p.doc.MessageByName(call.Request.Name)
if !ok {
return ServiceCall{}, fmt.Errorf("input message %s not found in document", call.Request.Name)
}
switch call.Kind {
case CallKindStandard, CallKindEntity:
request, err = p.buildProtoMessage(inputMessage, &call.Request, inputData)
if err != nil {
return ServiceCall{}, err
}
case CallKindResolve:
context, err := graph.FetchDependencies(&fetch)
if err != nil {
return ServiceCall{}, err
}
request, err = p.buildProtoMessageWithContext(inputMessage, &call.Request, inputData, context)
if err != nil || request == nil {
return ServiceCall{
Skip: true,
}, err
}
case CallKindRequired:
request, err = p.buildRequiredFieldsMessage(inputMessage, &call.Request, inputData)
if err != nil {
return ServiceCall{}, err
}
}
serviceName, ok := p.resolveServiceName(call)
if !ok {
return ServiceCall{}, fmt.Errorf("failed to resolve service name for method %s from the protobuf definition", call.MethodName)
}
return ServiceCall{
ServiceName: serviceName,
MethodName: call.MethodName,
Input: request,
Output: response,
RPC: call,
}, nil
}
func (p *RPCCompiler) resolveServiceName(call *RPCCall) (string, bool) {
if service := p.doc.ServiceByName(call.ServiceName); service != nil {
return service.FullName, true
}
// Fallback. Try to find the service by the method name.
for _, service := range p.doc.Services {
for _, methodRef := range service.MethodsRefs {
if p.doc.Methods[methodRef].Name == call.MethodName {
return service.FullName, true
}
}
}
return "", false
}
// newEmptyMessage creates a new empty dynamicpb.Message from a Message definition.
func (p *RPCCompiler) newEmptyMessage(message Message) (protoref.Message, error) {
if p.doc.MessageRefByName(message.Name) == InvalidRef {
return nil, fmt.Errorf("message %s not found in document", message.Name)
}
return dynamicpb.NewMessage(message.Desc), nil
}
// buildProtoMessageWithContext builds a protobuf message from an RPCMessage definition
// and JSON data. It handles nested messages and repeated fields.
//
// Example:
//
// message ResolveCategoryProductCountRequest {
// repeated CategoryProductCountContext context = 1;
// CategoryProductCountArgs field_args = 2;
// }
func (p *RPCCompiler) buildProtoMessageWithContext(inputMessage Message, rpcMessage *RPCMessage, data gjson.Result, context []FetchItem) (protoref.Message, error) {
if rpcMessage == nil {
return nil, fmt.Errorf("rpc message is nil")
}
if len(context) == 0 {
return nil, fmt.Errorf("context is required for resolve calls")
}
// If the context is empty, we can skip the invocation
// Currently only one context is supported for resolve calls. This might be extended in the future.
if context[0].ServiceCall == nil || context[0].ServiceCall.Output == nil {
return nil, nil
}
if p.doc.MessageRefByName(rpcMessage.Name) == InvalidRef {
return nil, fmt.Errorf("message %s not found in document", rpcMessage.Name)
}
rootMessage := dynamicpb.NewMessage(inputMessage.Desc)
if len(inputMessage.Fields) < 1 {
return nil, fmt.Errorf("message %s must have at least the context field", inputMessage.Name)
}
contextSchemaField := inputMessage.GetField("context")
if contextSchemaField == nil {
return nil, fmt.Errorf("context field not found in message %s", inputMessage.Name)
}
contextRPCField := rpcMessage.Fields.ByName(contextSchemaField.Name)
if contextRPCField == nil {
return nil, fmt.Errorf("context field not found in message %s", rpcMessage.Name)
}
contextField := rootMessage.Descriptor().Fields().ByNumber(protoref.FieldNumber(contextSchemaField.Number))
if contextField == nil {
return nil, fmt.Errorf("context field not found in message %s", inputMessage.Name)
}
// TODO handle multiple contexts (resolver requires another resolver)
contextData := p.resolveContextData(context[0], contextRPCField)
if len(contextData) == 0 {
return nil, nil
}
contextList := p.newEmptyListMessageByName(rootMessage, contextSchemaField.Name)
for _, contextElement := range contextData {
val := contextList.NewElement()
valMsg := val.Message()
for fieldName, value := range contextElement {
if err := p.setMessageValue(valMsg, fieldName, value); err != nil {
return nil, err
}
}
contextList.Append(val)
}
argsRPCField := rpcMessage.Fields.ByName("field_args")
if argsRPCField != nil {
argsSchemaField := inputMessage.GetField("field_args")
if argsSchemaField == nil {
return nil, fmt.Errorf("field_args field not found in message %s", inputMessage.Name)
}
argsMessage := p.doc.Messages[argsSchemaField.MessageRef]
args, err := p.buildProtoMessage(argsMessage, argsRPCField.Message, data)
if err != nil {
return nil, err
}
// Set the args field
if err := p.setMessageValue(rootMessage, argsRPCField.Name, protoref.ValueOfMessage(args)); err != nil {
return nil, err
}
}
return rootMessage, nil
}
// buildRequiredFieldsMessage builds a protobuf message from an RPCMessage definition
// and JSON data. It handles nested messages and repeated fields.
//
// Example:
//
// message RequireWarehouseStockHealthScoreByIdRequest {
// // RequireWarehouseStockHealthScoreByIdContext provides the context for the required fields method RequireWarehouseStockHealthScoreById.
// repeated RequireWarehouseStockHealthScoreByIdContext context = 1;
// }
//
// message RequireWarehouseStockHealthScoreByIdContext {
// LookupWarehouseByIdRequestKey key = 1;
// RequireWarehouseStockHealthScoreByIdFields fields = 2;
// }
func (p *RPCCompiler) buildRequiredFieldsMessage(inputMessage Message, rpcMessage *RPCMessage, data gjson.Result) (protoref.Message, error) {
if rpcMessage == nil {
return nil, fmt.Errorf("rpc message is nil")
}
if p.doc.MessageRefByName(rpcMessage.Name) == InvalidRef {
return nil, fmt.Errorf("message %s not found in document", rpcMessage.Name)
}
rootMessage := dynamicpb.NewMessage(inputMessage.Desc)
contextSchemaField := inputMessage.GetField("context")
if contextSchemaField == nil {
return nil, fmt.Errorf("context field not found in message %s", inputMessage.Name)
}
contextRPCField := rpcMessage.Fields.ByName(contextSchemaField.Name)
if contextRPCField == nil {
return nil, fmt.Errorf("context field not found in message %s", rpcMessage.Name)
}
contextList := p.newEmptyListMessageByName(rootMessage, contextSchemaField.Name)
contextFieldMessage := contextRPCField.Message
if contextFieldMessage == nil {
return nil, fmt.Errorf("context field message not found in message %s", inputMessage.Name)
}
keyField := contextFieldMessage.Fields.ByName("key")
if keyField == nil {
return nil, fmt.Errorf("key field message not found in message %s", contextFieldMessage.Name)
}
keyMessage, ok := p.doc.MessageByName(keyField.Message.Name)
if !ok {
return nil, fmt.Errorf("message %s not found in document", keyField.Message.Name)
}
requiresSelectionField := contextFieldMessage.Fields.ByName("fields")
if requiresSelectionField == nil {
return nil, fmt.Errorf("fields field not found in message %s", contextFieldMessage.Name)
}
requiresSelectionMessage, ok := p.doc.MessageByName(requiresSelectionField.Message.Name)
if !ok {
return nil, fmt.Errorf("message %s not found in document", requiresSelectionField.Message.Name)
}
representationsValue := data.Get("representations")
if exists, isArray := representationsValue.Exists(), representationsValue.IsArray(); !exists || !isArray {
if !exists {
return nil, errors.New("representations field not found in data")
}
if !isArray {
return nil, errors.New("invalid type for representations element, expected representations to be an array")
}
}
representations := representationsValue.Array()
for _, representation := range representations {
element := contextList.NewElement()
msg := element.Message()
keyMsg, err := p.buildProtoMessage(keyMessage, keyField.Message, representation)
if err != nil {
return nil, err
}
reqMsg, err := p.buildProtoMessage(requiresSelectionMessage, requiresSelectionField.Message, representation)
if err != nil {
return nil, err
}
if err := p.setMessageValue(msg, keyField.Name, protoref.ValueOfMessage(keyMsg)); err != nil {
return nil, err
}
if err := p.setMessageValue(msg, requiresSelectionField.Name, protoref.ValueOfMessage(reqMsg)); err != nil {
return nil, err
}
// build fields message
contextList.Append(element)
}
argsRPCField := rpcMessage.Fields.ByName("field_args")
if argsRPCField == nil {
return rootMessage, nil
}
argsSchemaField := inputMessage.GetField("field_args")
if argsSchemaField == nil {
return nil, fmt.Errorf("field_args field not found in message %s", inputMessage.Name)
}
argsMessage := p.doc.Messages[argsSchemaField.MessageRef]
args, err := p.buildProtoMessage(argsMessage, argsRPCField.Message, data)
if err != nil {
return nil, err
}
if err := p.setMessageValue(rootMessage, argsRPCField.Name, protoref.ValueOfMessage(args)); err != nil {
return nil, err
}
return rootMessage, nil
}
func (p *RPCCompiler) resolveContextData(context FetchItem, contextField *RPCField) []map[string]protoref.Value {
if context.ServiceCall == nil || context.ServiceCall.Output == nil {
return []map[string]protoref.Value{}
}
contextValues := make([]map[string]protoref.Value, 0)
for _, field := range contextField.Message.Fields {
values := p.resolveContextDataForPath(context.ServiceCall.Output, field.ResolvePath)
for index, value := range values {
if index >= len(contextValues) {
contextValues = append(contextValues, make(map[string]protoref.Value))
}
contextValues[index][field.Name] = value
}
}
return contextValues
}
// resolveContextDataForPath resolves the data for a given path in the context message.
func (p *RPCCompiler) resolveContextDataForPath(message protoref.Message, path ast.Path) []protoref.Value {
if path.Len() == 0 {
return nil
}
segment := path[0]
path = path[1:]
msg, fd := p.getMessageField(message, segment.FieldName.String())
if !msg.IsValid() {
return nil
}
if fd.IsList() {
return p.resolveListDataForPath(msg.List(), fd, path)
}
return p.resolveDataForPath(msg.Message(), path)
}
// resolveListDataForPath resolves the data for a given path in a list message.
func (p *RPCCompiler) resolveListDataForPath(message protoref.List, fd protoref.FieldDescriptor, path ast.Path) []protoref.Value {
if !message.IsValid() {
return nil
}
if path.Len() == 0 {
return nil
}
result := make([]protoref.Value, 0, message.Len())
for i := range message.Len() {
item := message.Get(i)
switch fd.Kind() {
case protoref.MessageKind:
values := p.resolveDataForPath(item.Message(), path)
for _, val := range values {
if list, isList := val.Interface().(protoref.List); isList {
values := p.resolveListDataForPath(list, fd, path[1:])
result = append(result, values...)
continue
} else {
result = append(result, val)
}
}
default:
result = append(result, item)
}
}
return result
}
// resolveDataForPath resolves the data for a given path in a message.
func (p *RPCCompiler) resolveDataForPath(message protoref.Message, path ast.Path) []protoref.Value {
if !message.IsValid() {
return nil
}
if path.Len() == 0 {
return nil
}
segment := path[0]
if fn := segment.FieldName.String(); strings.HasPrefix(fn, "@") {
list := p.resolveUnderlyingList(message, fn)
result := make([]protoref.Value, 0, len(list))
for _, item := range list {
result = append(result, p.resolveDataForPath(item.Message(), path[1:])...)
}
return result
}
field, fd := p.getMessageField(message, segment.FieldName.String())
if !field.IsValid() {
return nil
}
switch fd.Kind() {
case protoref.MessageKind:
if fd.IsList() {
if !field.List().IsValid() {
return nil
}
return []protoref.Value{protoref.ValueOfList(field.List())}
}
if !field.Message().IsValid() {
return nil
}
return p.resolveDataForPath(field.Message(), path[1:])
default:
return []protoref.Value{field}
}
}
// getMessageField gets the field from the message by its name.
func (p *RPCCompiler) getMessageField(message protoref.Message, fieldName string) (protoref.Value, protoref.FieldDescriptor) {
fd := message.Descriptor().Fields().ByName(protoref.Name(fieldName))
if fd == nil {
return protoref.Value{}, nil
}
return message.Get(fd), fd
}
// resolveUnderlyingList resolves the underlying list message from a nested list message.
//
// message ListOfFloat {
// message List {
// repeated double items = 1;
// }
// List list = 1;
// }
func (p *RPCCompiler) resolveUnderlyingList(msg protoref.Message, fieldName string) []protoref.Value {
nestingLevel := 0
for _, char := range fieldName {
if char != '@' {
break
}
nestingLevel++
}
listFieldValue := msg.Get(msg.Descriptor().Fields().ByName(protoref.Name(fieldName[nestingLevel:])))
if !listFieldValue.IsValid() {
return nil
}
return p.resolveUnderlyingListItems(listFieldValue, nestingLevel)
}
// resolveUnderlyingListItems resolves the items in a list message.
//
// message ListOfFloat {
// message List {
// repeated double items = 1;
// }
// List list = 1;
// }
func (p *RPCCompiler) resolveUnderlyingListItems(value protoref.Value, nestingLevel int) []protoref.Value {
// The field number of the list and items field in the message
const listAndItemsFieldNumber = 1
msg := value.Message()
fd := msg.Descriptor().Fields().ByNumber(listAndItemsFieldNumber)
if fd == nil {
return nil
}
listMsg := msg.Get(fd)
if !listMsg.IsValid() {
return nil
}
itemsValue := listMsg.Message().Get(listMsg.Message().Descriptor().Fields().ByNumber(listAndItemsFieldNumber))
if !itemsValue.IsValid() {
return nil
}
itemsList := itemsValue.List()
itemsListLen := itemsList.Len()
if itemsListLen == 0 {
return nil
}
if nestingLevel > 1 {
items := make([]protoref.Value, 0, itemsListLen)
for i := 0; i < itemsListLen; i++ {
items = append(items, p.resolveUnderlyingListItems(itemsList.Get(i), nestingLevel-1)...)
}
return items
}
result := make([]protoref.Value, itemsListLen)
for i := 0; i < itemsListLen; i++ {
result[i] = itemsList.Get(i)
}
return result
}
func (p *RPCCompiler) newEmptyListMessageByName(msg protoref.Message, name string) protoref.List {
return msg.Mutable(msg.Descriptor().Fields().ByName(protoref.Name(name))).List()
}
func (p *RPCCompiler) setMessageValue(message protoref.Message, fieldName string, value protoref.Value) error {
fd := message.Descriptor().Fields().ByName(protoref.Name(fieldName))
if fd == nil {
return fmt.Errorf("field %s not found in message %s", fieldName, message.Descriptor().Name())
}
// If we are setting a list value here, we need to create a copy of the list
// because the field descriptor is included in the type check, so we cannot asign it using `Set` directly.
if fd.IsList() {
list := message.Mutable(fd).List()
source, ok := value.Interface().(protoref.List)
if !ok {
return fmt.Errorf("value is not a list")
}
p.copyListValues(source, list)
return nil
}
message.Set(fd, value)
return nil
}
func (p *RPCCompiler) copyListValues(source protoref.List, destination protoref.List) {
for i := range source.Len() {
destination.Append(source.Get(i))
}
}
// buildProtoMessage recursively builds a protobuf message from an RPCMessage definition
// and JSON data. It handles nested messages and repeated fields.
func (p *RPCCompiler) buildProtoMessage(inputMessage Message, rpcMessage *RPCMessage, data gjson.Result) (protoref.Message, error) {
if rpcMessage == nil {
return nil, errors.New("rpc message is nil")
}
inputMessageRef := p.doc.MessageRefByName(inputMessage.Name)
if inputMessageRef == InvalidRef {
return nil, fmt.Errorf("message %s not found in document", inputMessage.Name)
}
// Handle oneof types (interfaces/unions) by populating the correct oneof field
// based on the __typename in the JSON data.
if rpcMessage.IsOneOf() {
return p.buildOneOfMessage(inputMessage, rpcMessage, data)
}
message := dynamicpb.NewMessage(inputMessage.Desc)
for _, rpcField := range rpcMessage.Fields {
fd := inputMessage.Desc.Fields().ByName(protoref.Name(rpcField.Name))
if fd == nil {
continue
}
if err := p.processRPCField(inputMessage, message, fd, &rpcField, data); err != nil {
return nil, err
}
}
return message, nil
}
// processRPCField populates a single field on a protobuf message from JSON data.
// It dispatches to specialized handlers based on the field's type: repeated, message, enum, or scalar.
func (p *RPCCompiler) processRPCField(inputMessage Message, message protoref.Message, fd protoref.FieldDescriptor, rpcField *RPCField, data gjson.Result) error {
field := inputMessage.GetField(rpcField.Name)
if field == nil {
return fmt.Errorf("field %s not found in message %s", rpcField.Name, inputMessage.Name)
}
if field.Repeated {
return p.processRepeatedField(message, fd, field, rpcField, data)
}
if field.MessageRef >= 0 {
return p.processMessageField(inputMessage, message, fd, field, rpcField, data)
}
if field.Type == DataTypeEnum {
return p.processEnumField(message, fd, rpcField, data)
}
return p.setMessageValue(message, field.Name, p.setValueForKind(field.Type, data.Get(rpcField.JSONPath)))