-
Notifications
You must be signed in to change notification settings - Fork 16
/
cel.go
369 lines (324 loc) · 8.41 KB
/
cel.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
// Copyright The HTNN Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package expr
import (
"fmt"
"net"
"reflect"
"strconv"
"strings"
"sync"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/checker/decls"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/ref"
"github.com/google/cel-go/common/types/traits"
exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
"mosn.io/htnn/pkg/filtermanager/api"
"mosn.io/htnn/pkg/log"
)
var (
logger = log.DefaultLogger.WithName("cel")
celEnv *cel.Env
initCelEnv = sync.OnceFunc(func() {
options := []cel.EnvOption{
cel.CustomTypeAdapter(&customTypeAdapter{}),
defineRequest(),
defineSource(),
}
var err error
celEnv, err = cel.NewEnv(
options...,
)
if err != nil {
panic(err)
}
})
)
type CelScript struct {
program cel.Program
}
func compile(env *cel.Env, expr string, celType *cel.Type) (*cel.Ast, error) {
ast, iss := env.Compile(expr)
if iss.Err() != nil {
return nil, iss.Err()
}
// the celType must be built type
if ast.OutputType() != celType {
return nil, fmt.Errorf("got %v, wanted %v", ast.OutputType(), celType)
}
return ast, nil
}
func CompileCel(expr string, returnType *cel.Type) (Script, error) {
initCelEnv()
ast, err := compile(celEnv, expr, returnType)
if err != nil {
return nil, err
}
program, _ := celEnv.Program(ast)
s := &CelScript{
program: program,
}
return s, nil
}
var varsPool = sync.Pool{
New: func() any {
return map[string]any{
"request": &request{},
"source": &source{},
}
},
}
func (s *CelScript) EvalWithRequest(cb api.FilterCallbackHandler, headers api.RequestHeaderMap) (any, error) {
vars := varsPool.Get().(map[string]any)
r := vars["request"].(*request)
r.headers = headers
r.callback = cb
so := vars["source"].(*source)
so.callback = cb
res, _, err := s.program.Eval(vars)
r.headers = nil
r.callback = nil
so.callback = nil
varsPool.Put(vars)
if err != nil {
return nil, err
}
return res.Value(), nil
}
type request struct {
customType
headers api.RequestHeaderMap
callback api.FilterCallbackHandler
}
var requestType = cel.ObjectType("htnn.request", traits.ReceiverType)
var requestExprType = decls.NewObjectType("htnn.request")
func defineRequest() cel.EnvOption {
cls := "request"
declarations := []*exprpb.Decl{
decls.NewConst(cls, requestExprType, nil),
}
// The methods come from https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/advanced/attributes
for _, dec := range []struct {
method string
parameterTypes []*exprpb.Type
returnType *exprpb.Type
}{
{
method: "path",
parameterTypes: []*exprpb.Type{},
returnType: decls.String,
},
{
method: "url_path",
parameterTypes: []*exprpb.Type{},
returnType: decls.String,
},
{
method: "host",
parameterTypes: []*exprpb.Type{},
returnType: decls.String,
},
{
method: "scheme",
parameterTypes: []*exprpb.Type{},
returnType: decls.String,
},
{
method: "method",
parameterTypes: []*exprpb.Type{},
returnType: decls.String,
},
{
method: "header",
parameterTypes: []*exprpb.Type{decls.String},
returnType: decls.String,
},
{
method: "query_path",
parameterTypes: []*exprpb.Type{},
returnType: decls.String,
},
{
method: "query",
parameterTypes: []*exprpb.Type{decls.String},
returnType: decls.String,
},
{
method: "id",
parameterTypes: []*exprpb.Type{},
returnType: decls.String,
},
} {
declarations = append(declarations,
decls.NewFunction(dec.method,
decls.NewInstanceOverload(fmt.Sprintf("%s_%s", cls, dec.method),
append([]*exprpb.Type{requestExprType}, dec.parameterTypes...), dec.returnType)),
)
}
return cel.Declarations(declarations...)
}
func fromProperty(cb api.FilterCallbackHandler, property string) ref.Val {
s, err := cb.GetProperty(property)
if err != nil {
logger.Error(err, "failed to get property", "property", property)
return types.String("")
}
return types.String(s)
}
func (r *request) Receive(function string, overload string, args []ref.Val) ref.Val {
switch function {
case "path":
return types.String(r.headers.Path())
case "url_path":
return types.String(r.headers.Url().Path)
case "host":
return types.String(r.headers.Host())
case "scheme":
return types.String(r.headers.Scheme())
case "method":
return types.String(r.headers.Method())
case "header":
name := args[0].Value().(string)
return types.String(r.Header(name))
case "query_path":
return types.String(r.headers.Url().RawQuery)
case "query":
name := args[0].Value().(string)
return types.String(r.Query(name))
case "id":
return fromProperty(r.callback, "request.id")
}
return types.NewErr("no such function - %s", function)
}
func (r *request) Header(name string) string {
v := r.headers.Values(name)
n := len(v)
if n == 1 {
return v[0]
} else if n == 0 {
return ""
}
// Return []string may be inconvenient in a small one-line script.
// So we join them into a string with comma, which is the same as Envoy's behavior.
return strings.Join(v, ",")
}
func (r *request) Query(name string) string {
query := r.headers.Url().Query()
v := query[name]
n := len(v)
if n == 1 {
return v[0]
} else if n == 0 {
return ""
}
return strings.Join(v, ",")
}
func (r *request) TypeName() string {
return requestType.TypeName()
}
type source struct {
customType
callback api.FilterCallbackHandler
}
var sourceType = cel.ObjectType("htnn.source", traits.ReceiverType)
var sourceExprType = decls.NewObjectType("htnn.source")
func defineSource() cel.EnvOption {
cls := "source"
declarations := []*exprpb.Decl{
decls.NewConst(cls, sourceExprType, nil),
}
for _, dec := range []struct {
method string
parameterTypes []*exprpb.Type
returnType *exprpb.Type
}{
{
method: "ip",
parameterTypes: []*exprpb.Type{},
returnType: decls.String,
},
{
method: "address",
parameterTypes: []*exprpb.Type{},
returnType: decls.String,
},
{
method: "port",
parameterTypes: []*exprpb.Type{},
returnType: decls.Int,
},
} {
declarations = append(declarations,
decls.NewFunction(dec.method,
decls.NewInstanceOverload(fmt.Sprintf("%s_%s", cls, dec.method),
append([]*exprpb.Type{sourceExprType}, dec.parameterTypes...), dec.returnType)),
)
}
return cel.Declarations(declarations...)
}
func (s *source) Receive(function string, overload string, args []ref.Val) ref.Val {
switch function {
case "ip":
addr := s.callback.StreamInfo().DownstreamRemoteParsedAddress()
return types.String(addr.IP)
case "address":
ipport := s.callback.StreamInfo().DownstreamRemoteAddress()
return types.String(ipport)
case "port":
ipport := s.callback.StreamInfo().DownstreamRemoteAddress()
// the IPPort given by Envoy must be valid
_, port, _ := net.SplitHostPort(ipport)
n, _ := strconv.Atoi(port)
return types.Int(n)
}
return types.NewErr("no such function - %s", function)
}
func (s *source) TypeName() string {
return sourceType.TypeName()
}
type customType struct {
}
// implement ref.Val
func (t *customType) ConvertToNative(typeDesc reflect.Type) (interface{}, error) {
panic("not required")
}
func (t *customType) ConvertToType(typeVal ref.Type) ref.Val {
panic("not required")
}
func (t *customType) Equal(other ref.Val) ref.Val {
o, ok := other.Value().(*customType)
if !ok {
return types.False
}
return types.Bool(o == t)
}
func (t *customType) Type() ref.Type {
return requestType
}
func (t *customType) Value() interface{} {
return t
}
func (t *customType) HasTrait(trait int) bool {
return trait == traits.ReceiverType
}
type customTypeAdapter struct {
}
func (customTypeAdapter) NativeToValue(value interface{}) ref.Val {
val, ok := value.(*customType)
if ok {
return val
}
return types.DefaultTypeAdapter.NativeToValue(value)
}