This repository has been archived by the owner on Jan 26, 2023. It is now read-only.
forked from hyperjumptech/grule-rule-engine
/
JsonResource.go
375 lines (351 loc) · 9.47 KB
/
JsonResource.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
// Copyright hyperjumptech/grule-rule-engine 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 pkg
import (
"encoding/json"
"fmt"
"strconv"
"strings"
)
// GruleJSON represents a rule in JSON format
type GruleJSON struct {
Name string `json:"name"`
Description string `json:"desc"`
Salience int `json:"salience"`
When interface{} `json:"when"`
Then []interface{} `json:"then"`
}
// JSONResource will parse rules in JSON fromat from underlying resource provider.
type JSONResource struct {
subRes Resource
}
// JSONResourceBundle will parse a set of rules in JSON format from an underlying bundle resource provider.
type JSONResourceBundle struct {
subRes ResouceBundle
}
// NewJSONResourceFromResource innstantiates a new JSON resource parser from an underlying Resource.
func NewJSONResourceFromResource(res Resource) Resource {
if _, ok := res.(*JSONResource); ok {
panic("cannot create JSON resource from JSON resource")
}
return &JSONResource{
subRes: res,
}
}
// Load will load the underlying Resource and parse the JSON rules into standard GRule syntax.
func (jr *JSONResource) Load() ([]byte, error) {
data, err := jr.subRes.Load()
if err != nil {
return nil, err
}
rs, err := ParseJSONRuleset(data)
if err != nil {
return nil, err
}
return []byte(rs), nil
}
// String will state the resource source.
func (jr *JSONResource) String() string {
return "JSON Resource, underlying resource: " + jr.subRes.String()
}
// NewJSONResourceBundleFromBundle innstantiates a new bundled JSON resource parser from an underlying ResourceBundle.
func NewJSONResourceBundleFromBundle(bundle ResouceBundle) ResouceBundle {
if _, ok := bundle.(*JSONResourceBundle); ok {
panic("cannot create JSON resource bundle from JSON resource bundle")
}
return &JSONResourceBundle{
subRes: bundle,
}
}
// Load will load the underlying ResourceBundle and parse the JSON rules into standard GRule syntax.
func (jrb *JSONResourceBundle) Load() ([]Resource, error) {
ress, err := jrb.subRes.Load()
if err != nil {
return nil, err
}
nress := make([]Resource, len(ress))
for i := 0; i < len(ress); i++ {
nress[i] = NewJSONResourceFromResource(ress[i])
}
return nress, nil
}
// MustLoad operates the same as load except it will panic in the event of an error.
func (jrb *JSONResourceBundle) MustLoad() []Resource {
ress := jrb.subRes.MustLoad()
nress := make([]Resource, len(ress))
for i := 0; i < len(ress); i++ {
nress[i] = NewJSONResourceFromResource(ress[i])
}
return nress
}
// ParseJSONRuleset accepts a byte array containing an array of rules in JSON format to be parsed into GRule syntax.
func ParseJSONRuleset(data []byte) (rs string, err error) {
defer func() {
if x := recover(); x != nil {
err = fmt.Errorf("%v", x)
}
}()
var rules []GruleJSON
err = json.Unmarshal(data, &rules)
if err != nil {
return
}
var sb strings.Builder
for i := 0; i < len(rules); i++ {
sb.WriteString(parseRule(&rules[i]))
}
rs = sb.String()
return
}
// ParseRule Accepts a struct of GruleJSON rule and returns the parsed string of GRule.
func ParseRule(rule *GruleJSON) (r string, err error) {
defer func() {
if x := recover(); x != nil {
err = fmt.Errorf("%v", x)
}
}()
r = parseRule(rule)
return
}
func parseRule(rule *GruleJSON) string {
if len(rule.Name) == 0 {
panic("rule name cannot be blank")
}
if rule.When == nil {
panic("rule when condition cannot be nil")
}
if rule.Then == nil {
panic("rule thenn condition cannot be nil")
}
var sb strings.Builder
sb.WriteString("rule ")
sb.WriteString(rule.Name)
sb.WriteString(" ")
sb.WriteString(strconv.Quote(rule.Description))
sb.WriteString(" salience ")
sb.WriteString(strconv.Itoa(rule.Salience))
sb.WriteString(" {\n when\n ")
sb.WriteString(parseWhen(rule.When))
sb.WriteString("\n then\n")
thens := parseThen(rule.Then)
for i := 0; i < len(thens); i++ {
sb.WriteString(" ")
sb.WriteString(thens[i])
sb.WriteString("\n")
}
sb.WriteString("}\n")
return sb.String()
}
func parseThen(ts []interface{}) []string {
thens := make([]string, len(ts))
for i := 0; i < len(ts); i++ {
switch x := ts[i].(type) {
case string:
thens[i] = x
if !strings.HasSuffix(thens[i], ";") {
thens[i] += ";"
}
case map[string]interface{}:
thens[i] = buildExpression(x, 0) + ";"
default:
panic("invalid then type, must be a string or an array of action objects")
}
}
return thens
}
func parseWhen(w interface{}) string {
switch x := w.(type) {
case string:
return x
case map[string]interface{}:
return buildExpression(x, 0)
default:
panic("invalid when type, must be a string or an array of condition objects")
}
}
func buildExpression(input map[string]interface{}, depth int) string {
exp, _ := buildExpressionEx(input, depth)
return exp
}
func buildExpressionEx(input map[string]interface{}, depth int) (string, bool) {
if depth > 1024 {
panic("JSON nesting exceeded 1024 levels, aborting")
}
if len(input) > 1 {
panic("expression objects can only contain a single operation type")
}
for k, v := range input {
switch k {
case "and":
return buildCompoundOperator(v, depth, " && ")
case "or":
return buildCompoundOperator(v, depth, " || ")
case "eq":
return joinOperator(v, " == "), false
case "not":
return joinOperator(v, " != "), false
case "gt":
return joinOperator(v, " > "), false
case "gte":
return joinOperator(v, " >= "), false
case "lt":
return joinOperator(v, " < "), false
case "lte":
return joinOperator(v, " <= "), false
case "bor":
return joinOperator(v, " | "), false
case "band":
return joinOperator(v, " & "), false
case "plus":
return joinOperator(v, " + "), false
case "minus":
return joinOperator(v, " - "), false
case "div":
return joinOperator(v, " / "), false
case "mul":
return joinOperator(v, " * "), false
case "mod":
return joinOperator(v, " % "), false
case "set":
return joinSet(v, " = "), true
case "call":
return joinCall(v), true
case "obj":
if s, ok := v.(string); ok {
return s, true
}
panic("object must be a string")
case "const":
switch x := v.(type) {
case string:
return strconv.Quote(x), true
case float64:
return strconv.FormatFloat(x, 'f', -1, 64), true
case bool:
if x {
return "true", true
}
return "false", true
}
panic("constant must be a string or a numeric value")
default:
panic("unknown operator type: " + k)
}
}
panic("boolean expression cannot be empty")
}
func buildCompoundOperator(o interface{}, depth int, op string) (string, bool) {
if andarr, ok := o.([]interface{}); ok {
var ands []string
if len(andarr) < 2 {
panic("and operator must have at least 2 operands")
}
for i := 0; i < len(andarr); i++ {
if subVal, ok := andarr[i].(map[string]interface{}); ok {
ands = append(ands, buildExpression(subVal, depth+1))
} else {
panic("and operands must be an array of objects")
}
}
if depth > 0 {
return "(" + strings.Join(ands, op) + ")", false
}
return strings.Join(ands, op), false
}
panic("compound operator must be an array")
}
func joinCall(v interface{}) string {
if arr, ok := v.([]interface{}); ok {
if len(arr) == 0 {
panic("call operator must have at least one operand")
}
var f string
var ok bool
if f, ok = arr[0].(string); !ok {
panic("first call operand must be a string")
}
if len(arr) > 1 {
sars := make([]string, len(arr)-1)
for i := 1; i < len(arr); i++ {
sars[i-1] = parseCallOperand(arr[i])
}
return f + "(" + strings.Join(sars, ", ") + ")"
}
return f + "()"
}
panic("operator has an unexpected type")
}
func parseCallOperand(o interface{}) string {
switch x := o.(type) {
case string:
if len(x) == 0 {
panic("operand cannnot be empty")
}
return x
case float64:
return fmt.Sprint(x)
case bool:
if x {
return "true"
}
return "false"
case map[string]interface{}:
return buildExpression(x, 0)
default:
panic("operand has an invalid type")
}
}
func joinOperator(v interface{}, op string) string {
if arr, ok := v.([]interface{}); ok {
if len(arr) == 0 {
panic("operator cannot have 0 operands")
}
ops := make([]string, len(arr))
for i := 0; i < len(arr); i++ {
ops[i] = parseOperand(arr[i], false)
}
return strings.Join(ops, op)
}
panic("operator has an unexpected type")
}
func joinSet(v interface{}, op string) string {
if arr, ok := v.([]interface{}); ok {
if len(arr) != 2 {
panic("set operand count must be 2")
}
return parseOperand(arr[0], true) + op + parseOperand(arr[1], true)
}
panic("operator has an unexpected type")
}
func parseOperand(o interface{}, noWrap bool) string {
switch x := o.(type) {
case string:
return x
case float64:
return fmt.Sprint(x)
case bool:
if x {
return "true"
}
return "false"
case map[string]interface{}:
expr, expNoWrap := buildExpressionEx(x, 0)
if expNoWrap || noWrap {
return expr
}
return "(" + expr + ")"
default:
panic("operand has an invalid type")
}
}