forked from Argus-Labs/world-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.go
More file actions
296 lines (247 loc) · 7.74 KB
/
query.go
File metadata and controls
296 lines (247 loc) · 7.74 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
package cardinal
import (
"encoding/json"
"reflect"
ethereumAbi "github.com/ethereum/go-ethereum/accounts/abi"
"github.com/rotisserie/eris"
"pkg.world.dev/world-engine/cardinal/abi"
"pkg.world.dev/world-engine/cardinal/types"
)
var _ query = &queryType[struct{}, struct{}]{}
var DefaultQueryGroup = "game"
type query interface {
// Name returns the name of the query.
Name() string
// Group returns the group of the query.
Group() string
// IsEVMCompatible reports if the query is able to be sent from the EVM.
IsEVMCompatible() bool
// GetRequestFieldInformation returns a map of the fields of the query's request type and their types.
GetRequestFieldInformation() map[string]any
// handleQuery handles queries with concrete struct types, rather than encoded bytes.
handleQuery(WorldContext, any) (any, error)
// handleQueryJSON handles json-encoded query request and return a json-encoded response.
handleQueryJSON(WorldContext, []byte) ([]byte, error)
// handleQueryEVM handles ABI-encoded query request and return a ABI-encoded response.
handleQueryEVM(WorldContext, []byte) ([]byte, error)
// encodeEVMRequest encodes a go struct in ABI format. Used for testing.
encodeEVMRequest(any) ([]byte, error)
// decodeEVMReply decodes EVM reply bytes, into the concrete go reply type.
decodeEVMReply([]byte) (any, error)
}
type QueryOption[Request, Reply any] func(qt *queryType[Request, Reply])
type queryType[Request any, Reply any] struct {
name string
group string
handler func(wCtx WorldContext, req *Request) (*Reply, error)
requestABI *ethereumAbi.Type
replyABI *ethereumAbi.Type
}
func WithQueryEVMSupport[Request, Reply any]() QueryOption[Request, Reply] {
return func(qt *queryType[Request, Reply]) {
if err := qt.generateABIBindings(); err != nil {
panic(err)
}
}
}
// WithCustomQueryGroup sets a custom group for the query.
// By default, queries are registered under the "game" group which maps it to the /query/game/:queryType route.
// This option allows you to set a custom group, which allow you to register the query
// under /query/<custom_group>/:queryType.
func WithCustomQueryGroup[Request, Reply any](group string) QueryOption[Request, Reply] {
return func(qt *queryType[Request, Reply]) {
qt.group = group
}
}
func newQueryType[Request any, Reply any](
name string,
handler func(wCtx WorldContext, req *Request) (*Reply, error),
opts ...QueryOption[Request, Reply],
) (query, error) {
err := validateQuery[Request, Reply](name, handler)
if err != nil {
return nil, err
}
r := &queryType[Request, Reply]{
name: name,
group: DefaultQueryGroup,
handler: handler,
}
for _, opt := range opts {
opt(r)
}
return r, nil
}
func (r *queryType[Request, Reply]) IsEVMCompatible() bool {
return r.requestABI != nil && r.replyABI != nil
}
// generateABIBindings generates the ABI bindings used for encoding/decoding requests and replies.
func (r *queryType[Request, Reply]) generateABIBindings() error {
var req Request
reqABI, err := abi.GenerateABIType(req)
if err != nil {
return eris.Wrap(err, "error generating request ABI binding")
}
var rep Reply
repABI, err := abi.GenerateABIType(rep)
if err != nil {
return eris.Wrap(err, "error generating reply ABI binding")
}
r.requestABI = reqABI
r.replyABI = repABI
return nil
}
func (r *queryType[Request, Reply]) Name() string {
return r.name
}
func (r *queryType[Request, Reply]) Group() string {
return r.group
}
func (r *queryType[Request, Reply]) handleQuery(wCtx WorldContext, a any) (any, error) {
var request *Request
if reflect.TypeOf(a).Kind() == reflect.Pointer {
ptrRequest, ok := a.(*Request)
if !ok {
return nil, eris.Errorf("cannot cast %T to this query request type %T", a, new(Request))
}
request = ptrRequest
} else {
valueReq, ok := a.(Request)
if !ok {
return nil, eris.Errorf("cannot cast %T to this query request type %T", a, new(Request))
}
request = &valueReq
}
reply, err := r.handler(wCtx, request)
return reply, err
}
func (r *queryType[Request, Reply]) handleQueryJSON(wCtx WorldContext, bz []byte) ([]byte, error) {
request := new(Request)
err := json.Unmarshal(bz, request)
if err != nil {
return nil, eris.Wrapf(err, "unable to unmarshal query request into type %T", *request)
}
res, err := r.handler(wCtx, request)
if err != nil {
return nil, err
}
bz, err = json.Marshal(res)
if err != nil {
return nil, eris.Wrapf(err, "unable to marshal response %T", res)
}
return bz, nil
}
func (r *queryType[Request, Reply]) handleQueryEVM(wCtx WorldContext, bz []byte) ([]byte, error) {
if !r.IsEVMCompatible() {
return nil, eris.Errorf("query %s/%s is not EVM-compatible", r.Group(), r.Name())
}
req, err := r.decodeEVMRequest(bz)
if err != nil {
return nil, err
}
res, err := r.handler(wCtx, req)
if err != nil {
return nil, err
}
bz, err = r.encodeEVMReply(res)
if err != nil {
return nil, err
}
return bz, nil
}
func (r *queryType[Request, Reply]) encodeEVMRequest(req any) ([]byte, error) {
if r.requestABI == nil {
return nil, eris.Wrap(ErrEVMTypeNotSet, "failed to ABI encode request")
}
args := ethereumAbi.Arguments{{Type: *r.requestABI}}
bz, err := args.Pack(req)
if err != nil {
return nil, eris.Wrap(err, "failed to ABI encode request")
}
return bz, nil
}
func (r *queryType[Request, Reply]) decodeEVMRequest(bz []byte) (*Request, error) {
if r.requestABI == nil {
return nil, eris.Wrap(ErrEVMTypeNotSet, "failed to ABI decode request")
}
args := ethereumAbi.Arguments{{Type: *r.requestABI}}
unpacked, err := args.Unpack(bz)
if err != nil {
return nil, eris.Wrap(err, "failed to ABI decode request")
}
if len(unpacked) < 1 {
return nil, eris.New("error decoding EVM bytes: no values could be unpacked")
}
request, err := abi.SerdeInto[Request](unpacked[0])
if err != nil {
return nil, err
}
return &request, nil
}
func (r *queryType[Request, Reply]) encodeEVMReply(a any) ([]byte, error) {
if r.replyABI == nil {
return nil, eris.Wrap(ErrEVMTypeNotSet, "failed to ABI encode reply")
}
args := ethereumAbi.Arguments{{Type: *r.replyABI}}
bz, err := args.Pack(a)
if err != nil {
return nil, eris.Wrap(err, "failed to ABI encode reply")
}
return bz, nil
}
func (r *queryType[Request, Reply]) decodeEVMReply(bz []byte) (any, error) {
if r.replyABI == nil {
return nil, eris.Wrap(ErrEVMTypeNotSet, "")
}
args := ethereumAbi.Arguments{{Type: *r.replyABI}}
unpacked, err := args.Unpack(bz)
if err != nil {
return nil, err
}
if len(unpacked) < 1 {
return nil, eris.New("error decoding EVM bytes: no values could be unpacked")
}
reply, err := abi.SerdeInto[Reply](unpacked[0])
if err != nil {
return nil, err
}
return reply, nil
}
// GetRequestFieldInformation returns the field information for the request struct.
func (r *queryType[Request, Reply]) GetRequestFieldInformation() map[string]any {
return types.GetFieldInformation(reflect.TypeOf(new(Request)).Elem())
}
func validateQuery[Request any, Reply any](
name string,
handler func(wCtx WorldContext, req *Request) (*Reply, error),
) error {
if name == "" {
return eris.New("cannot create query without name")
}
if handler == nil {
return eris.New("cannot create query without handler")
}
var req Request
var rep Reply
reqType := reflect.TypeOf(req)
reqKind := reqType.Kind()
reqValid := false
if (reqKind == reflect.Pointer && reqType.Elem().Kind() == reflect.Struct) ||
reqKind == reflect.Struct {
reqValid = true
}
repType := reflect.TypeOf(rep)
repKind := reqType.Kind()
repValid := false
if (repKind == reflect.Pointer && repType.Elem().Kind() == reflect.Struct) ||
repKind == reflect.Struct {
repValid = true
}
if !repValid || !reqValid {
return eris.Errorf(
"invalid query: %s: the Request and Reply generics must be both structs",
name,
)
}
return nil
}