diff --git a/assets/templates/middleware/log.tmpl b/assets/templates/middleware/log.tmpl index ab91909fb61f1044fe74810390a64d469a6cb614..10066fbe69dda8db64ac02ceeb73d814fc5fd2ca 100644 --- a/assets/templates/middleware/log.tmpl +++ b/assets/templates/middleware/log.tmpl @@ -35,7 +35,7 @@ func {{ $funcName }} (logger *zap.Logger) Middleware { return func(next {{ .Interface.Type }}) {{ .Interface.Type }} { return &{{ $decorator }}{ next: next, - logger: logger.With(logzap.Component("{{ (lower $serviceName ) }}")), + logger: logger.With(logzap.Component("{{ $serviceName }}")), } } } diff --git a/id/organization.go b/id/organization.go index 5aedfb709ef6ff5bde9fd7f06bcba49f07fbd643..a3a9d7e8031d467e6594bc8f7629fba2bec7220c 100644 --- a/id/organization.go +++ b/id/organization.go @@ -35,13 +35,13 @@ func (id *OrganizationId) FromParts(parts []string) error { func (id *OrganizationId) Map() map[string]any { return map[string]any{ - "organization_id": id.OrganizationID, - "type": id.Type(), + "org_id": id.OrganizationID, + "type": id.Type(), } } func (id *OrganizationId) FromMap(m map[string]any) error { - id.OrganizationID, _ = m["organization_id"].(string) + id.OrganizationID, _ = m["org_id"].(string) if id.OrganizationID == "" { return fmt.Errorf("%w: OrganizationId required", ErrInvalidID) } diff --git a/id/test/object_id_test.go b/id/test/object_id_test.go index f97e50e49068173b5aa1968de33abc4d8a44817b..ec2cd931d54b47696b9b3a4d76218e27448f3c64 100644 --- a/id/test/object_id_test.go +++ b/id/test/object_id_test.go @@ -38,7 +38,7 @@ func Test_OrganizationId(t *testing.T) { }, { name: "valid map", - in: map[string]any{"type": "organization", "organization_id": "<org_id>"}, + in: map[string]any{"type": "organization", "org_id": "<org_id>"}, out: "/orgs/<org_id>", result: &id.ObjectId{Descriptor: &id.OrganizationId{OrganizationID: "<org_id>"}}, }, diff --git a/logs/log.go b/logs/log.go index 2bc9dedf82c450e54d46363fbe63eceb44b1a50d..4277ce8a211e02a56229ca93b5489e69c1ec5c83 100644 --- a/logs/log.go +++ b/logs/log.go @@ -29,7 +29,7 @@ func (l Level) String() string { type Entry struct { ID string `json:"id" bson:"id" mapstructure:"id"` Timestamp time.Time `json:"timestamp,omitempty" bson:"timestamp,omitempty" mapstructure:"timestamp,omitempty"` - LogLevel Level `json:"log_level,omitempty" bson:"log_level,omitempty" mapstructure:"log_level,omitempty"` + Level Level `json:"level,omitempty" bson:"level,omitempty" mapstructure:"level,omitempty"` Message string `json:"message,omitempty" bson:"message,omitempty" mapstructure:"message,omitempty"` Category string `json:"category,omitempty" bson:"category,omitempty" mapstructure:"category,omitempty"` Component string `json:"component,omitempty" bson:"component,omitempty" mapstructure:"component,omitempty"` @@ -54,7 +54,7 @@ func EntryToPB(entry *Entry) *pb.LogEntry { logEntry := &pb.LogEntry{ Id: entry.ID, Timestamp: timestamppb.New(entry.Timestamp), - Level: pb.LogLevel(entry.LogLevel), + Level: pb.LogLevel(entry.Level), Message: entry.Message, Category: entry.Category, Component: entry.Component, @@ -76,7 +76,7 @@ func EntryFromPB(request *pb.LogEntry) *Entry { logEntry := &Entry{ ID: request.Id, Timestamp: request.Timestamp.AsTime(), - LogLevel: Level(request.Level), + Level: Level(request.Level), Message: request.Message, Category: request.Category, Component: request.Component, @@ -103,7 +103,7 @@ func (e *Entry) ToMap() map[string]any { res := map[string]any{ "id": e.ID, "timestamp": e.Timestamp, - "log_level": e.LogLevel, + "level": e.Level, "message": e.Message, "category": e.Category, "component": e.Component, diff --git a/logs/log_test.go b/logs/log_test.go index 9ccb7e7065cccf5b3945339b6085a108e6b0fae2..1816cb9ff8e9222784623acd87593c6ef0bb3acf 100644 --- a/logs/log_test.go +++ b/logs/log_test.go @@ -42,7 +42,7 @@ func TestEntry_ToMap(t *testing.T) { nil, nil, }, - map[string]interface{}{"caller": map[string]interface{}{"type": "user", "user_id": "<user_id>"}, "caller_id": "/users/<user_id>", "category": "", "component": "", "event": "", "id": "1", "log_level": Level(0), "message": "message", "object": map[string]interface{}{"env_id": "<env_id>", "space_id": "<space_id>", "type": "environment"}, "object_id": "/spaces/<space_id>/envs/<env_id>", "timestamp": time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC)}, + map[string]interface{}{"caller": map[string]interface{}{"type": "user", "user_id": "<user_id>"}, "caller_id": "/users/<user_id>", "category": "", "component": "", "event": "", "id": "1", "level": Level(0), "message": "message", "object": map[string]interface{}{"env_id": "<env_id>", "space_id": "<space_id>", "type": "environment"}, "object_id": "/spaces/<space_id>/envs/<env_id>", "timestamp": time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC)}, }, } for _, tt := range tests { @@ -50,7 +50,7 @@ func TestEntry_ToMap(t *testing.T) { e := &Entry{ ID: tt.fields.ID, Timestamp: tt.fields.Timestamp, - LogLevel: tt.fields.LogLevel, + Level: tt.fields.LogLevel, Message: tt.fields.Message, Category: tt.fields.Category, Component: tt.fields.Component, diff --git a/logs/zap/example_test.go b/logs/zap/example_test.go index 9dfd0aaa2f33820c72bffcdd6ecae965672ad838..e0db8954ffa3346acf55446342fb3bc80fca2e98 100644 --- a/logs/zap/example_test.go +++ b/logs/zap/example_test.go @@ -26,7 +26,7 @@ func TestExample(t *testing.T) { wantEntries := []*logs.Entry{ { - LogLevel: logs.Level(zapcore.InfoLevel), + Level: logs.Level(zapcore.InfoLevel), Message: "Successfully created", Component: "Items", Event: items.EventCreateItem, @@ -35,7 +35,7 @@ func TestExample(t *testing.T) { Tags: []string{"tag1", "tag2", "tag3"}, }, { - LogLevel: logs.Level(zapcore.WarnLevel), + Level: logs.Level(zapcore.WarnLevel), Message: "Successfully updated", Component: "Items", Event: items.EventUpdateItem, diff --git a/pkg/collections/middleware/logging_middleware.go b/pkg/collections/middleware/logging_middleware.go index bf04a4aac6e1f5304e982dac0b6c77662715a1cc..fb12be9fa3a0b7e05603cc418b5ec7505048a7f9 100644 --- a/pkg/collections/middleware/logging_middleware.go +++ b/pkg/collections/middleware/logging_middleware.go @@ -19,7 +19,7 @@ func LoggingMiddleware(logger *zap.Logger) Middleware { return func(next collections.Collections) collections.Collections { return &loggingMiddleware{ next: next, - logger: logger.With(logzap.Component("collections")), + logger: logger.With(logzap.Component("Collections")), } } } diff --git a/pkg/expr/expr.go b/pkg/expr/expr.go index 1969b58c6bec892b05f8eff38eec86f3d4099e01..42588c2b9b03cb28be7f52a6edcb18561271d347 100644 --- a/pkg/expr/expr.go +++ b/pkg/expr/expr.go @@ -1,21 +1,12 @@ package expr import ( - "regexp" - "strings" - - "git.perx.ru/perxis/perxis-go/pkg/data" exprcompiler "github.com/expr-lang/expr/compiler" "github.com/expr-lang/expr/parser" "github.com/expr-lang/expr/vm" "golang.org/x/net/context" ) -var ( - additionalFunctions = []string{"contains", "startsWith", "endsWith", "and", "or", "in", "not"} - isExpression = regexp.MustCompile(`[()}{<>=|&%*+\-\/\]\[\\]`).MatchString -) - const EnvContextKey = "$context" func Eval(ctx context.Context, input string, env map[string]interface{}) (interface{}, error) { @@ -65,17 +56,3 @@ func EvalKV(ctx context.Context, input string, kv ...interface{}) (interface{}, return Eval(ctx, input, m) } - -func IsExpression(input string) bool { - if isExpression(input) { - return true - } - - for _, s := range strings.Fields(input) { - if data.Contains(s, additionalFunctions) { - return true - } - } - - return false -} \ No newline at end of file diff --git a/pkg/expr/expr_test.go b/pkg/expr/expr_test.go index 35153da271daace9f9acb6c7a02411f948f47054..b3db1b232571a99a31cb2dfbf19f109e4d479951 100644 --- a/pkg/expr/expr_test.go +++ b/pkg/expr/expr_test.go @@ -2,56 +2,11 @@ package expr import ( "context" - "fmt" "testing" - "time" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestIsExpression(t *testing.T) { - now := time.Now() - - tests := []struct { - name string - eval string - want bool - }{ - {"equal", "i == 3", true}, - {"in array", "i in [1,2,3]", true}, - {"contains", "value contains 'some'", true}, - {"contains with . + () $ {} ^", "value contains 'something with . + () $ {} ^'", true}, - {"startsWith", "value startsWith 'some'", true}, - {"startsWith . + () $ {} ^", "value startsWith '. + () $ {} ^'", true}, - {"endsWith", "value endsWith 'some'", true}, - {"endsWith . + () $ {} ^", "value endsWith '. + () $ {} ^'", true}, - {"icontains", "icontains(value, 'some')", true}, - {"icontains with . + () $ {} ^", "icontains (value, 'something with . + () $ {} ^')", true}, - {"istartsWith", "istartsWith(value, 'Some')", true}, - {"istartsWith . + () $ {} ^ . + () $ {} ^", "istartsWith(value, '. + () $ {} ^')", true}, - {"iendsWith", "iendsWith(value, 'some')", true}, - {"iendsWith . + () $ {} ^", "iendsWith(value,'. + () $ {} ^')", true}, - {"or", "i == 2 || i > 10", true}, - {"search", "search('some') || i > 10", true}, - {"vars:or", "i == a + 2 || i > a + 10", true}, - {"near", "near(a, [55.5, 37.5], 1000)", true}, - {"within", "within(a, 'box', [[54.54, 36.36], [55.55, 37.37]])", true}, - {"time", "d > Time.Date('2021-08-31')", true}, - {"time", fmt.Sprintf("d > Time.Time('%s')", now.Format(time.RFC3339)), true}, - {"in", "In(s, [1,2,3])", true}, - {"in", "In(s, 1)", true}, - {"text search or id", "id", false}, - {"numbers", "3", false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - got := IsExpression(tt.eval) - assert.Equal(t, tt.want, got) - }) - } -} - type testEnvStruct struct { ID string `expr:"id"` Size int `expr:"size"` diff --git a/pkg/expr/mongo.go b/pkg/expr/mongo.go index f0e335786bdad0ecdc0baa7c0cb86b0d1ab32484..bb4187dda74adce707798781b77d23a648db0eb1 100644 --- a/pkg/expr/mongo.go +++ b/pkg/expr/mongo.go @@ -358,6 +358,8 @@ func (c *compiler) SliceNode(node *ast.SliceNode) interface{} { func (c *compiler) CallNode(node *ast.CallNode) interface{} { switch node.Callee.String() { + case "try": + return c.handleTryNode(node) case "search", "q": val := c.compile(node.Arguments[0]) return bson.M{"$text": bson.M{"$search": val}} @@ -710,3 +712,26 @@ func (c *compiler) handleLenNode(node *ast.BinaryNode) bson.M { panic("invalid comparison operator with len()") } } + +// handleTryNode получает узел AST с двумя выражениями и пытается выполнить первое +// в случае успеха - возвращает его +// в случае ошибки - пытается выполнить второе и вернуть его результат +func (c *compiler) handleTryNode(node *ast.CallNode) (result interface{}) { + if len(node.Arguments) != 2 { + panic("try() expects exactly 2 arguments") + } + + defer func() { + if r := recover(); r != nil { + result = c.compile(node.Arguments[1]) + } + }() + + tree, err := parser.Parse(node.Arguments[0].(*ast.StringNode).Value) + if err != nil { + panic(err) + } + subcompiler := &compiler{tree: tree, env: c.env, config: c.config, identifierRenameFn: c.identifierRenameFn} + result = subcompiler.compile(tree.Node).(bson.M) + return +} diff --git a/pkg/expr/mongo_test.go b/pkg/expr/mongo_test.go index bbe42465e9a3e46a36430e918c31c81d22c7eb4a..9a7df77d00a8c006327b5b2645818a014d86d9b7 100644 --- a/pkg/expr/mongo_test.go +++ b/pkg/expr/mongo_test.go @@ -79,6 +79,10 @@ func TestConvertToMongo(t *testing.T) { {"in", "In(s, 1)", nil, bson.M{"s": bson.M{"$in": []interface{}{1}}}, false}, {"text search or id", "id", nil, nil, true}, {"struct env", "db_item.id == env_item.id", map[string]interface{}{"env_item": &testEnvStruct{ID: "id1"}}, bson.M{"db_item.id": "id1"}, false}, + {"try#1", "try('s == 1', s == 2)", nil, bson.M{"s": 1}, false}, + {"try#2", "try('some-slug', search('some-slug') || _id contains 'some-slug')", nil, bson.M{"$or": bson.A{bson.M{"$text": bson.M{"$search": "some-slug"}}, bson.M{"_id": bson.M{"$regex": "some-slug"}}}}, false}, + {"try#3", "try('bad-expr', bad-expr)", nil, nil, true}, + {"try#4", "try('3', s == 1)", nil, bson.M{"s": 1}, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { diff --git a/pkg/items/middleware/logging_middleware.go b/pkg/items/middleware/logging_middleware.go index fe7870a831d9b90a6145ad20f4c55cb602e8ed98..e2829a4261b42dbbc8ce7a52bcdcf0d3dd21ff05 100644 --- a/pkg/items/middleware/logging_middleware.go +++ b/pkg/items/middleware/logging_middleware.go @@ -19,7 +19,7 @@ func LoggingMiddleware(logger *zap.Logger) Middleware { return func(next items.Items) items.Items { return &loggingMiddleware{ next: next, - logger: logger.With(logzap.Component("items")), + logger: logger.With(logzap.Component("Items")), } } }