-
Notifications
You must be signed in to change notification settings - Fork 2
/
rpc.go
905 lines (780 loc) · 24.6 KB
/
rpc.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
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
package raiden
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"regexp"
"strings"
"github.com/sev-2/raiden/pkg/logger"
"github.com/sev-2/raiden/pkg/supabase/client/net"
"github.com/sev-2/raiden/pkg/utils"
"github.com/valyala/fasthttp"
)
var RpcLogger = logger.HcLog().Named("raiden.rpc")
// ---- Define rpc data type -----
type RpcParamDataType string
type RpcReturnDataType string
// Define constants for rpc input data type
const (
RpcParamDataTypeInteger RpcParamDataType = "INTEGER"
RpcParamDataTypeNumeric RpcParamDataType = "NUMERIC"
RpcParamDataTypeBigInt RpcParamDataType = "BIGINT"
RpcParamDataTypeReal RpcParamDataType = "REAL"
RpcParamDataTypeDoublePreci RpcParamDataType = "DOUBLE PRECISION"
RpcParamDataTypeText RpcParamDataType = "TEXT"
RpcParamDataTypeVarchar RpcParamDataType = "CHARACTER VARYING"
RpcParamDataTypeVarcharAlias RpcParamDataType = "VARCHAR"
RpcParamDataTypeBoolean RpcParamDataType = "BOOLEAN"
RpcParamDataTypeBytea RpcParamDataType = "BYTEA"
RpcParamDataTypeTimestamp RpcParamDataType = "TIMESTAMP WITHOUT TIME ZONE"
RpcParamDataTypeTimestampAlias RpcParamDataType = "TIMESTAMP"
RpcParamDataTypeTimestampTZ RpcParamDataType = "TIMESTAMP WITH TIME ZONE"
RpcParamDataTypeTimestampTZAlias RpcParamDataType = "TIMESTAMPZ"
RpcParamDataTypeJSON RpcParamDataType = "JSON"
RpcParamDataTypeJSONB RpcParamDataType = "JSONB"
RpcParamDataTypeUuid RpcParamDataType = "UUID"
)
// Define constants for rpc return data type
const (
RpcReturnDataTypeInteger RpcReturnDataType = "INTEGER"
RpcReturnDataTypeBigInt RpcReturnDataType = "BIGINT"
RpcReturnDataTypeReal RpcReturnDataType = "REAL"
RpcReturnDataTypeDoublePreci RpcReturnDataType = "DOUBLE PRECISION"
RpcReturnDataTypeText RpcReturnDataType = "TEXT"
RpcReturnDataTypeVarchar RpcReturnDataType = "CHARACTER VARYING"
RpcReturnDataTypeVarcharAlias RpcReturnDataType = "VARCHAR"
RpcReturnDataTypeBoolean RpcReturnDataType = "BOOLEAN"
RpcReturnDataTypeBytea RpcReturnDataType = "BYTEA"
RpcReturnDataTypeTimestamp RpcReturnDataType = "TIMESTAMP WITHOUT TIME ZONE"
RpcReturnDataTypeTimestampAlias RpcReturnDataType = "TIMESTAMP"
RpcReturnDataTypeTimestampTZ RpcReturnDataType = "TIMESTAMP WITH TIME ZONE"
RpcReturnDataTypeTimestampTZAlias RpcReturnDataType = "TIMESTAMPZ"
RpcReturnDataTypeJSON RpcReturnDataType = "JSON"
RpcReturnDataTypeJSONB RpcReturnDataType = "JSONB"
RpcReturnDataTypeRecord RpcReturnDataType = "RECORD" // like tuple
RpcReturnDataTypeTable RpcReturnDataType = "TABLE"
RpcReturnDataTypeSetOf RpcReturnDataType = "SETOF"
RpcReturnDataTypeVoid RpcReturnDataType = "VOID"
RpcReturnDataTypeTrigger RpcReturnDataType = "TRIGGER"
)
func RpcParamToGoType(dataType RpcParamDataType) string {
switch dataType {
case RpcParamDataTypeInteger, RpcParamDataTypeBigInt:
return "int64"
case RpcParamDataTypeReal:
return "float32"
case RpcParamDataTypeDoublePreci, RpcParamDataTypeNumeric:
return "float64"
case RpcParamDataTypeText, RpcParamDataTypeVarchar, RpcParamDataTypeVarcharAlias:
return "string"
case RpcParamDataTypeBoolean:
return "bool"
case RpcParamDataTypeBytea:
return "[]byte"
case RpcParamDataTypeTimestamp, RpcParamDataTypeTimestampTZ, RpcParamDataTypeTimestampAlias, RpcParamDataTypeTimestampTZAlias:
return "time.Time"
case RpcParamDataTypeJSON, RpcParamDataTypeJSONB:
return "map[string]interface{}"
case RpcParamDataTypeUuid:
return "uuid.UUID"
default:
return "interface{}" // Return interface{} for unknown types
}
}
func GetValidRpcParamType(pType string, returnAlias bool) (RpcParamDataType, error) {
pCheckType := RpcParamDataType(strings.ToUpper(pType))
switch pCheckType {
case RpcParamDataTypeInteger:
return RpcParamDataTypeInteger, nil
case RpcParamDataTypeBigInt:
return RpcParamDataTypeBigInt, nil
case RpcParamDataTypeReal:
return RpcParamDataTypeReal, nil
case RpcParamDataTypeDoublePreci:
return RpcParamDataTypeDoublePreci, nil
case RpcParamDataTypeNumeric:
return RpcParamDataTypeNumeric, nil
case RpcParamDataTypeText:
return RpcParamDataTypeText, nil
case RpcParamDataTypeVarchar, RpcParamDataTypeVarcharAlias:
if returnAlias {
return RpcParamDataTypeVarcharAlias, nil
}
return RpcParamDataTypeVarchar, nil
case RpcParamDataTypeBoolean:
return RpcParamDataTypeBoolean, nil
case RpcParamDataTypeBytea:
return RpcParamDataTypeBytea, nil
case RpcParamDataTypeTimestamp, RpcParamDataTypeTimestampAlias:
if returnAlias {
return RpcParamDataTypeTimestampAlias, nil
}
return RpcParamDataTypeTimestamp, nil
case RpcParamDataTypeTimestampTZ, RpcParamDataTypeTimestampTZAlias:
if returnAlias {
return RpcParamDataTypeTimestampTZAlias, nil
}
return RpcParamDataTypeTimestampTZ, nil
case RpcParamDataTypeJSON:
return RpcParamDataTypeJSON, nil
case RpcParamDataTypeJSONB:
return RpcParamDataTypeJSONB, nil
case RpcParamDataTypeUuid:
return RpcParamDataTypeUuid, nil
default:
return "", fmt.Errorf("unsupported rpc param type : %s", pCheckType)
}
}
func RpcReturnToGoType(dataType RpcReturnDataType) string {
switch dataType {
case RpcReturnDataTypeInteger, RpcReturnDataTypeBigInt:
return "int64"
case RpcReturnDataTypeReal:
return "float32"
case RpcReturnDataTypeDoublePreci:
return "float64"
case RpcReturnDataTypeText, RpcReturnDataTypeVarchar:
return "string"
case RpcReturnDataTypeBoolean:
return "bool"
case RpcReturnDataTypeBytea:
return "[]byte"
case RpcReturnDataTypeTimestamp, RpcReturnDataTypeTimestampTZ:
return "time.Time"
case RpcReturnDataTypeJSON, RpcReturnDataTypeJSONB:
return "map[string]interface{}"
default:
return "interface{}" // Return interface{} for unknown types
}
}
func GetValidRpcReturnType(pType string, returnAlias bool) (RpcReturnDataType, error) {
pCheckType := RpcReturnDataType(strings.ToUpper(pType))
switch pCheckType {
case RpcReturnDataTypeInteger:
return RpcReturnDataTypeInteger, nil
case RpcReturnDataTypeBigInt:
return RpcReturnDataTypeBigInt, nil
case RpcReturnDataTypeReal:
return RpcReturnDataTypeReal, nil
case RpcReturnDataTypeDoublePreci:
return RpcReturnDataTypeDoublePreci, nil
case RpcReturnDataTypeText:
return RpcReturnDataTypeText, nil
case RpcReturnDataTypeVarchar, RpcReturnDataTypeVarcharAlias:
if returnAlias {
return RpcReturnDataTypeVarcharAlias, nil
}
return RpcReturnDataTypeVarchar, nil
case RpcReturnDataTypeBoolean:
return RpcReturnDataTypeBoolean, nil
case RpcReturnDataTypeBytea:
return RpcReturnDataTypeBytea, nil
case RpcReturnDataTypeTimestamp, RpcReturnDataTypeTimestampAlias:
if returnAlias {
return RpcReturnDataTypeTimestampAlias, nil
}
return RpcReturnDataTypeTimestamp, nil
case RpcReturnDataTypeTimestampTZ, RpcReturnDataTypeTimestampTZAlias:
if returnAlias {
return RpcReturnDataTypeTimestampTZAlias, nil
}
return RpcReturnDataTypeTimestampTZ, nil
case RpcReturnDataTypeJSON:
return RpcReturnDataTypeJSON, nil
case RpcReturnDataTypeJSONB:
return RpcReturnDataTypeJSONB, nil
case RpcReturnDataTypeSetOf:
return RpcReturnDataTypeSetOf, nil
case RpcReturnDataTypeTable:
return RpcReturnDataTypeTable, nil
case RpcReturnDataTypeVoid:
return RpcReturnDataTypeVoid, nil
case RpcReturnDataTypeTrigger:
return RpcReturnDataTypeTrigger, nil
default:
return "", fmt.Errorf("unsupported rpc return type : %s", pCheckType)
}
}
func GetValidRpcReturnNameDecl(pType RpcReturnDataType, returnAlias bool) (string, error) {
switch pType {
case RpcReturnDataTypeInteger:
return "RpcReturnDataTypeInteger", nil
case RpcReturnDataTypeBigInt:
return "RpcReturnDataTypeBigInt", nil
case RpcReturnDataTypeReal:
return "RpcReturnDataTypeReal", nil
case RpcReturnDataTypeDoublePreci:
return "RpcReturnDataTypeDoublePreci", nil
case RpcReturnDataTypeText:
return "RpcReturnDataTypeText", nil
case RpcReturnDataTypeVarchar, RpcReturnDataTypeVarcharAlias:
if returnAlias {
return "RpcReturnDataTypeVarcharAlias", nil
}
return "RpcReturnDataTypeVarchar", nil
case RpcReturnDataTypeBoolean:
return "RpcReturnDataTypeBoolean", nil
case RpcReturnDataTypeBytea:
return "RpcReturnDataTypeBytea", nil
case RpcReturnDataTypeTimestamp:
if returnAlias {
return "RpcReturnDataTypeTimestampAlias", nil
}
return "RpcReturnDataTypeTimestamp", nil
case RpcReturnDataTypeTimestampTZ:
if returnAlias {
return "RpcReturnDataTypeTimestampTZAlias", nil
}
return "RpcReturnDataTypeTimestampTZ", nil
case RpcReturnDataTypeJSON:
return "RpcReturnDataTypeJSON", nil
case RpcReturnDataTypeJSONB:
return "RpcReturnDataTypeJSONB", nil
case RpcReturnDataTypeSetOf:
return "RpcReturnDataTypeSetOf", nil
case RpcReturnDataTypeTable:
return "RpcReturnDataTypeTable", nil
case RpcReturnDataTypeVoid:
return "RpcReturnDataTypeVoid", nil
case RpcReturnDataTypeTrigger:
return "RpcReturnDataTypeTrigger", nil
default:
return "", fmt.Errorf("unsupported rpc return name declaration : %s", pType)
}
}
// ----- Define type, variable and constant -----
type (
RpcSecurityType string
RpcBehaviorType string
RpcParam struct {
Name string
Type RpcParamDataType
Default *string
Value any
}
RpcParams []RpcParam
RpcModel struct {
Alias string
Model any
}
Rpc interface {
BindModels()
BindModel(model any, alias string) Rpc
GetModels() map[string]RpcModel
SetName(name string)
GetName() string
SetParams(params []RpcParam)
GetParams() []RpcParam
UseParamPrefix() bool
SetSchema(schema string)
GetSchema() string
SetSecurity(security RpcSecurityType)
GetSecurity() RpcSecurityType
SetBehavior(behavior RpcBehaviorType)
GetBehavior() RpcBehaviorType
SetReturnType(returnType RpcReturnDataType)
GetReturnType() RpcReturnDataType
SetReturnTypeStmt(returnTypeStmt string)
GetReturnTypeStmt() string
SetRawDefinition(definition string)
GetRawDefinition() string
SetCompleteStmt(stmt string)
GetCompleteStmt() string
}
RpcBase struct {
Name string
Schema string
Params []RpcParam
Definition string
SecurityType RpcSecurityType
ReturnType RpcReturnDataType
ReturnTypeStmt string
Behavior RpcBehaviorType
CompleteStatement string
Models map[string]RpcModel
}
RpcParamTag struct {
Name string
Type string
DefaultValue string
}
)
var (
DefaultRpcParamPrefix = "in_"
DefaultRpcSchema = "public"
)
const (
RpcBehaviorVolatile RpcBehaviorType = "VOLATILE"
RpcBehaviorStable RpcBehaviorType = "STABLE"
RpcBehaviorImmutable RpcBehaviorType = "IMMUTABLE"
RpcSecurityTypeDefiner RpcSecurityType = "DEFINER"
RpcSecurityTypeInvoker RpcSecurityType = "INVOKER"
RpcTemplate = `CREATE OR REPLACE FUNCTION :function_name(:params) RETURNS :return_type LANGUAGE plpgsql :behavior :security set search_path = '' AS $function$ :definition $function$`
)
func MarshalRpcParamTag(paramTag *RpcParamTag) (string, error) {
if paramTag == nil {
return "", nil
}
var tagArr []string
if paramTag.Name != "" {
tagArr = append(tagArr, fmt.Sprintf("name:%s", paramTag.Name))
}
if paramTag.Type != "" {
tagArr = append(tagArr, fmt.Sprintf("type:%s", strings.ToLower(paramTag.Type)))
}
if paramTag.DefaultValue != "" {
tagArr = append(tagArr, fmt.Sprintf("default:%s", paramTag.DefaultValue))
}
return strings.Join(tagArr, ";"), nil
}
func UnmarshalRpcParamTag(tag string) (RpcParamTag, error) {
paramTag := RpcParamTag{}
// Regular expression to match key-value pairs
re := regexp.MustCompile(`(\w+):([^;]+);?`)
// Find all matches in the tag string
matches := re.FindAllStringSubmatch(tag, -1)
for _, match := range matches {
key := match[1]
value := match[2]
switch key {
case "name":
paramTag.Name = value
case "type":
pType, err := GetValidRpcParamType(value, true)
if err != nil {
return paramTag, err
}
paramTag.Type = string(pType)
case "default":
paramTag.DefaultValue = value
}
}
return paramTag, nil
}
// ----- Rpc base functionality -----
func (r *RpcBase) initModel() {
if r.Models == nil {
r.Models = make(map[string]RpcModel)
}
}
func (r *RpcBase) SetName(name string) {
r.Name = name
}
func (r *RpcBase) GetName() string {
return r.Name
}
func (r *RpcBase) BindModel(model any, alias string) Rpc {
r.initModel()
reflectType := reflect.TypeOf(model)
if reflectType.Kind() == reflect.Ptr {
reflectType = reflectType.Elem()
}
r.Models[utils.ToSnakeCase(reflectType.Name())] = RpcModel{
Alias: alias,
Model: model,
}
return r
}
func (r *RpcBase) BindModels() {}
func (r *RpcBase) GetModels() map[string]RpcModel {
return r.Models
}
func (r *RpcBase) SetReturnTypeStmt(returnTypeStmt string) {
r.ReturnTypeStmt = returnTypeStmt
}
func (r *RpcBase) GetReturnTypeStmt() string {
return r.ReturnTypeStmt
}
func (r *RpcBase) SetParams(params []RpcParam) {
r.Params = append(r.Params, params...)
}
func (r *RpcBase) GetParams() []RpcParam {
return r.Params
}
func (r *RpcBase) UseParamPrefix() bool {
return true
}
func (r *RpcBase) GetReturnType() (rt RpcReturnDataType) {
RpcLogger.Error("Rpc return type is not implemented, use GetReturnType for set it")
return
}
func (r *RpcBase) SetSchema(schema string) {
r.Schema = schema
}
func (r *RpcBase) GetSchema() string {
return r.Schema
}
func (r *RpcBase) SetSecurity(security RpcSecurityType) {
r.SecurityType = security
}
func (r *RpcBase) GetSecurity() RpcSecurityType {
return r.SecurityType
}
func (r *RpcBase) SetBehavior(behavior RpcBehaviorType) {
r.Behavior = behavior
}
func (r *RpcBase) GetBehavior() RpcBehaviorType {
return RpcBehaviorVolatile
}
func (r *RpcBase) SetReturnType(returnType RpcReturnDataType) {
r.ReturnType = returnType
}
func (r *RpcBase) SetRawDefinition(definition string) {
r.Definition = definition
}
func (r *RpcBase) GetRawDefinition() (d string) {
RpcLogger.Error("Rpc definition type is not implemented, use GetRawDefinition for set it")
return
}
func (r *RpcBase) SetCompleteStmt(stmt string) {
r.CompleteStatement = stmt
}
func (r *RpcBase) GetCompleteStmt() string {
return strings.ReplaceAll(r.CompleteStatement, "search_path to ", "search_path = ")
}
// ----- Rpc Param Functionality -----
func (p RpcParams) ToQuery(userPrefix bool) (string, error) {
var qArr []string
for i := range p {
pi := p[i]
var prefix string
if userPrefix {
prefix = DefaultRpcParamPrefix
}
pt, err := GetValidRpcParamType(string(pi.Type), false)
if err != nil {
return "", err
}
pStr := fmt.Sprintf("%s%s %s", prefix, pi.Name, pt)
if pi.Default != nil {
pStr += fmt.Sprintf(" default '%s'::%s", *pi.Default, string(pt))
}
qArr = append(qArr, pStr)
}
return strings.Join(qArr, ", "), nil
}
func BuildRpc(rpc Rpc) (err error) {
rpc.BindModels()
// init value from template
q := RpcTemplate
// set rpc type and value
rpcType := reflect.TypeOf(rpc)
if rpcType.Kind() == reflect.Ptr {
rpcType = rpcType.Elem()
}
// set rpc name
rpcName := rpc.GetName()
if rpcName == "" {
rpcName = utils.ToSnakeCase(rpcType.Name())
}
rpc.SetName(rpcName)
// replace enhance rpcName and set rpc base schema
if rpc.GetSchema() == "" {
rpc.SetSchema(DefaultRpcSchema)
}
rpcName = fmt.Sprintf("%s.%s", rpc.GetSchema(), rpcName)
// replace definition and set rpc base name
q = strings.ReplaceAll(q, ":function_name", rpcName)
// build Param
pt, found := rpcType.FieldByName("Params")
if !found {
return fmt.Errorf("field Params is not found in struct : %s", rpcType.Name())
}
if p, err := extractRpcParam(pt.Type); err != nil {
return err
} else {
pq, ep := p.ToQuery(rpc.UseParamPrefix())
if ep != nil {
return ep
}
// replace param definition and set rpc base param
rpc.SetParams(p)
q = strings.ReplaceAll(q, ":params", strings.ToLower(pq))
}
// build return data
rt, found := rpcType.FieldByName("Return")
if !found {
return fmt.Errorf("field Return is not found in struct : %s", rpcType.Name())
}
if rType, err := extractRpcResult(rt.Type, rpc); err != nil {
return err
} else {
// replace return type definition and set rpc base return type
rpc.SetReturnType(rpc.GetReturnType())
rpc.SetReturnTypeStmt(strings.ToLower(rType))
q = strings.ReplaceAll(q, ":return_type", strings.ToLower(rType))
}
// build security
if rpc.GetSecurity() == "" {
rpc.SetSecurity(RpcSecurityTypeInvoker)
}
if rpc.GetSecurity() == RpcSecurityTypeDefiner {
rpc.SetSecurity(RpcSecurityTypeDefiner)
q = strings.ReplaceAll(q, ":security", "SECURITY DEFINER")
} else {
q = strings.ReplaceAll(q, ":security", "")
}
// set behavior
if rpc.GetBehavior() == "" {
rpc.SetBehavior(RpcBehaviorVolatile)
} else {
rpc.SetBehavior(rpc.GetBehavior())
}
if rpc.GetBehavior() == RpcBehaviorVolatile {
q = strings.ReplaceAll(q, ":behavior", "")
} else {
q = strings.ReplaceAll(q, ":behavior", string(rpc.GetBehavior()))
}
// build definitions
definition := buildRpcDefinition(rpc)
rpc.SetRawDefinition(definition)
q = strings.ReplaceAll(q, ":definition", definition)
// cleanup
re := regexp.MustCompile(`\s+`)
q = re.ReplaceAllString(q, " ")
q = strings.ToLower(q)
rpc.SetCompleteStmt(q)
return
}
func extractRpcParam(paramType reflect.Type) (params RpcParams, err error) {
if paramType.Kind() == reflect.Pointer {
paramType = paramType.Elem()
}
for i := 0; i < paramType.NumField(); i++ {
field := paramType.Field(i)
columnTagStr := field.Tag.Get("column")
if len(columnTagStr) == 0 {
continue
}
ct, err := UnmarshalRpcParamTag(columnTagStr)
if err != nil {
return params, err
}
p := RpcParam{
Name: ct.Name,
Type: RpcParamDataType(ct.Type),
}
if ct.DefaultValue != "" {
p.Default = &ct.DefaultValue
}
params = append(params, p)
}
return
}
func extractRpcResult(returnReflectType reflect.Type, rpc Rpc) (q string, err error) {
switch rpc.GetReturnType() {
case RpcReturnDataTypeSetOf:
return buildRpcReturnSetOf(returnReflectType)
case RpcReturnDataTypeTable:
return buildRpcReturnTable(returnReflectType)
default:
return string(rpc.GetReturnType()), nil
}
}
func buildRpcReturnSetOf(returnReflectType reflect.Type) (q string, err error) {
st, err := findStruct(returnReflectType)
if err != nil {
return "", err
}
return fmt.Sprintf("setof %s", st.Name()), nil
}
func buildRpcReturnTable(returnReflectType reflect.Type) (q string, err error) {
st, e := findStruct(returnReflectType)
if e != nil {
err = e
return
}
p, e := extractRpcParam(st)
if e != nil {
err = e
return
}
pq, ep := p.ToQuery(false)
if ep != nil {
return q, ep
}
if len(pq) == 0 {
return
}
return fmt.Sprintf("table(%s)", pq), nil
}
func buildRpcDefinition(rpc Rpc) string {
definition := rpc.GetRawDefinition()
dFields := strings.Fields(utils.CleanUpString(definition))
for i := range dFields {
d := dFields[i]
if strings.HasSuffix(d, ";") && strings.ToLower(d) != "end;" {
dFields[i] = strings.ReplaceAll(d, ";", " ;")
}
}
definition = strings.Join(dFields, " ")
for k, v := range rpc.GetModels() {
definition = utils.MatchReplacer(definition, ":"+v.Alias, k)
}
params := rpc.GetParams()
for i := range params {
p := params[i]
key := p.Name
replaceKey := key
if rpc.UseParamPrefix() {
replaceKey = DefaultRpcParamPrefix + key
}
definition = utils.MatchReplacer(definition, ":"+key, replaceKey)
}
return definition
}
func findStruct(returnReflectType reflect.Type) (reflect.Type, error) {
switch returnReflectType.Kind() {
case reflect.Ptr:
return findStruct(returnReflectType.Elem())
case reflect.Array, reflect.Slice:
return findStruct(returnReflectType.Elem())
case reflect.Struct:
return returnReflectType, nil
default:
return nil, fmt.Errorf("%s is not struct", returnReflectType.Name())
}
}
// ----- Execute Rpc -----
func ExecuteRpc(ctx Context, rpc Rpc) (any, error) {
rpcType := reflect.TypeOf(rpc).Elem()
rpcValue := reflect.ValueOf(rpc).Elem()
if rpcType.Kind() == reflect.Pointer {
rpcType = rpcType.Elem()
rpcValue = rpcValue.Elem()
}
// set params
paramsFields, found := rpcType.FieldByName("Params")
if !found {
return nil, &ErrorResponse{
StatusCode: fasthttp.StatusInternalServerError,
Details: fmt.Sprintf("Struct %s doesn`t have Params field, define first because this attribute need for send parameter to server", rpcType.Name()),
Message: fmt.Sprintf("Undefined field Params in struct %s", rpcType.Name()),
Hint: "Invalid Rpc",
Code: fasthttp.StatusMessage(fasthttp.StatusInternalServerError),
}
}
paramsType := paramsFields.Type
paramValue := rpcValue.FieldByName("Params")
if paramsType.Kind() == reflect.Ptr {
paramsType = paramsType.Elem()
paramValue = paramValue.Elem()
}
returnField, found := rpcType.FieldByName("Return")
if !found {
return nil, &ErrorResponse{
StatusCode: fasthttp.StatusInternalServerError,
Details: fmt.Sprintf("Struct %s doesn`t have Return field, define first because this attribute need for receive data from server", rpcType.Name()),
Message: fmt.Sprintf("Undefined field Return in struct %s", rpcType.Name()),
Hint: "Invalid Rpc",
Code: fasthttp.StatusMessage(fasthttp.StatusInternalServerError),
}
}
if err := BuildRpc(rpc); err != nil {
return nil, err
}
mapParams := map[string]any{}
for i := 0; i < paramsType.NumField(); i++ {
if paramValue.IsValid() {
fieldType, fieldValue := paramsType.Field(i), paramValue.Field(i)
key := utils.SnakeCaseToPascalCase(fieldType.Name)
if rpc.UseParamPrefix() {
key = fmt.Sprintf("%s%s", DefaultRpcParamPrefix, key)
}
mapParams[strings.ToLower(key)] = fieldValue.Interface()
}
}
pByte, err := json.Marshal(mapParams)
if err != nil {
return nil, &ErrorResponse{
StatusCode: fasthttp.StatusBadRequest,
Details: err.Error(),
Message: "Invalid request data",
Hint: "Invalid params",
Code: fasthttp.StatusMessage(fasthttp.StatusBadRequest),
}
}
apiUrl := fmt.Sprintf("%s/%s/%s", ctx.Config().SupabasePublicUrl, "rest/v1/rpc", rpc.GetName())
if string(ctx.RequestContext().QueryArgs().QueryString()) != "" {
apiUrl = fmt.Sprintf("%s?%s", apiUrl, string(ctx.RequestContext().QueryArgs().QueryString()))
}
httpReq, err := ConvertRequestCtxToHTTPRequest(ctx.RequestContext())
if err != nil {
return nil, err
}
resData, err := rpcSendRequest(apiUrl, pByte, rpcAttachAuthHeader(httpReq))
if err != nil {
return nil, err
}
// sample data
returnObject := reflect.New(returnField.Type).Interface()
if err := json.Unmarshal(resData, returnObject); err != nil {
return nil, &ErrorResponse{
StatusCode: fasthttp.StatusInternalServerError,
Details: err,
Message: "invalid marshall response data",
}
}
returnValue := reflect.ValueOf(returnObject)
if returnValue.Kind() == reflect.Ptr {
returnValue = returnValue.Elem()
}
rv := rpcValue.FieldByName("Return")
rv.Set(returnValue)
return returnValue.Interface(), nil
}
func rpcAttachAuthHeader(inReq *http.Request) net.RequestInterceptor {
return func(outReq *http.Request) error {
if authHeader := inReq.Header.Get("Authorization"); len(authHeader) > 0 {
outReq.Header.Set("Authorization", authHeader)
}
if apiKey := inReq.Header.Get("apiKey"); len(apiKey) > 0 {
outReq.Header.Set("apiKey", apiKey)
}
return nil
}
}
func rpcSendRequest(apiUrl string, body []byte, reqInterceptor net.RequestInterceptor) ([]byte, error) {
resData, err := net.SendRequest(fasthttp.MethodPost, apiUrl, body, net.DefaultTimeout, reqInterceptor, nil)
if err != nil {
sendErr, isHaveData := err.(utils.SendRequestError)
if isHaveData {
var errResponse ErrorResponse
if err := json.Unmarshal(sendErr.Body, &errResponse); err == nil {
return nil, &errResponse
}
}
return nil, &ErrorResponse{
StatusCode: fasthttp.StatusInternalServerError,
Details: err.Error(),
Message: fmt.Sprintf("fail request to upstream. Reason: %v", err),
}
}
return resData, nil
}
func ConvertRequestCtxToHTTPRequest(ctx *fasthttp.RequestCtx) (*http.Request, error) {
url, err := url.ParseRequestURI(string(ctx.RequestURI()))
if err != nil {
return nil, err
}
// Create a new http.Request based on the data in RequestCtx
req := &http.Request{
Method: string(ctx.Method()),
URL: url,
Proto: "HTTP/1.1", // You may need to adjust this based on your requirements
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
}
// Copy headers from RequestCtx to http.Request
ctx.Request.Header.VisitAll(func(key, value []byte) {
req.Header.Add(string(key), string(value))
})
// Copy body from RequestCtx to http.Request
req.Body = io.NopCloser(bytes.NewReader(ctx.Request.Body()))
return req, nil
}