Repository: vanus-labs/vanus (go)

Issue:
[Good First Issues]: implement function "unfold_array" - 7 points
# Motivation
Vanus Functions are a series of pre-built functions worked within Vanus transformer. By choosing a function, users can specify the way that events will be changed.

It will be a good start if you decide to contribute to Vanus codes.

# Details

Function name: **unfold_array**

Args

- sourceJsonPath - This value must be of array type.
- targetPathPrefix

## Description

The function is used to unfold the source JSON path array into multiple JSON elements with names  "targetPathPrefix-0", "targetPathPrefix-1", "targetPathPrefix-2" ...
The function should throw an error if the value of source JSON path is not an array.

## Example

```
{
    "specversion" : "1.0",
    "type" : "com.example.someevent",
    "source" : "/mycontext",
    "subject": null,
    "id" : "C234-1234-1234",
    "time" : "2018-04-05T17:31:00Z",
    "comexampleextension1" : "value",
    "comexampleothervalue" : 5,
    "datacontenttype" : "application/json",
    "data": {
        "appinfoA" : ["string-0", "string-1", "string-2"]
      

    }
}
```

After the function.

```
"pipeline":[
    {"command":["unfold_array", "$.data.appinfoA", "$.data. appinfoB"]}
]
```

The transformed event should look like this:

```
{
    "specversion" : "1.0",
    "type" : "com.example.someevent",
    "source" : "/mycontext",
    "subject": null,
    "id" : "C234-1234-1234",
    "time" : "2018-04-05T17:31:00Z",
    "comexampleextension1" : "value",
    "comexampleothervalue" : 5,
    "datacontenttype" : "application/json",
    "data" : {
        "appinfoA" : ["string-0", "string-1", "string-2"],
         "appinfoB-0" : "string-0",
         "appinfoB-1" : "string-1",
         "appinfoB-2" : "string-2"
   }
}

```
# How to implement

1. Fork the vanus repository.
2. Create a branch `function-unfold_array`
3. Create `unfold_array.go` under `internal/primitive/transform/action/array`, and then implement the function.
4. Create `unfold_array_test.go` under `internal/primitive/transform/action/array` for unit test.
5. Register your function in `internal/primitive/transform/runtime/init.go`.
6. Submit your PR

# Contribution points

Each issue counts specific points based on its difficulty. Contributors earn the corresponding points if they solve that issue. Contribution points are used to describe the contributions contributors have made.  They can also be used to get rewards when there are community events.

This issue counts **7 points**.

# How to claim to solve the issue

If you want to implement this function, please leave a comment in this issue like:

> I'd like to implement this function, please assign this issue to me.

Vanus community will assign the issue to you on time.

Pull request:
feat: implement function "unfold_array"
<!--

Thank you for contributing to Vanus!

PR Title Format: 

feat/fix/refactor/docs/...: what's changed

Note: see https://github.com/linkall-labs/vanus/blob/main/CONTRIBUTING.md to know details about title format
-->

### What problem does this PR solve?
<!--

Please create an issue first to describe the problem

There MUST be one line starting with "Issue Number:  ".

-->

Issue Number: close #461 

### Problem Summary

### What is changed and how does it work?

### Check List

<!-- At least one of them must be included. -->

#### Tests

- [x] Unit test
- [ ] Integration test
- [ ] Manual test (add detailed scripts or steps below)
- [ ] No code


Patch:
diff --git a/internal/primitive/transform/action/array/unfold_array.go b/internal/primitive/transform/action/array/unfold_array.go
new file mode 100644
index 0000000..7ff09db
--- /dev/null
+++ b/internal/primitive/transform/action/array/unfold_array.go
@@ -0,0 +1,75 @@
+// Copyright 2023 Linkall Inc.
+//
+// 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 array
+
+import (
+	"errors"
+	"fmt"
+	"strconv"
+	"strings"
+
+	"github.com/linkall-labs/vanus/internal/primitive/transform/action"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/arg"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/common"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/context"
+)
+
+// ["unfold_array","sourceJsonPath", "targetPathPrefix"].
+type unfoldArrayAction struct {
+	action.CommonAction
+	targetPathPrefix string
+}
+
+func NewUnfoldArrayAction() action.Action {
+	a := &unfoldArrayAction{}
+	a.CommonAction = action.CommonAction{
+		ActionName: "UNFOLD_ARRAY",
+		FixedArgs:  []arg.TypeList{[]arg.Type{arg.EventData}, []arg.Type{arg.EventData}},
+	}
+	return a
+}
+
+func (a *unfoldArrayAction) Init(args []arg.Arg) error {
+	a.targetPathPrefix = args[1].Original()
+	a.Args = args[:1]
+	a.ArgTypes = []common.Type{common.Array}
+	return nil
+}
+
+func (a *unfoldArrayAction) Execute(ceCtx *context.EventContext) error {
+	args, err := a.RunArgs(ceCtx)
+	if err != nil {
+		return err
+	}
+	arrayValue, _ := args[0].([]interface{})
+	errs := make([]string, 0, len(arrayValue))
+	for i, v := range arrayValue {
+		argument := a.targetPathPrefix + "-" + strconv.Itoa(i)
+		targetArg, err := arg.NewArg(argument)
+		if err != nil {
+			errs = append(errs, fmt.Sprintf("failed to NewArg, arg: %v, err: %v", argument, err))
+			continue
+		}
+		err = targetArg.SetValue(ceCtx, v)
+		if err != nil {
+			errs = append(errs, fmt.Sprintf("failed to SetValue, v: %v, err: %v", v, err))
+			continue
+		}
+	}
+	if len(errs) > 0 {
+		return errors.New(strings.Join(errs, ";"))
+	}
+	return nil
+}
diff --git a/internal/primitive/transform/runtime/init.go b/internal/primitive/transform/runtime/init.go
index 390cd85..d9d775f 100644
--- a/internal/primitive/transform/runtime/init.go
+++ b/internal/primitive/transform/runtime/init.go
@@ -60,6 +60,7 @@ func init() {
 		// array
 		array.NewRenderArrayAction,
 		array.NewArrayForeachAction,
+		array.NewUnfoldArrayAction,
 		// common
 		common.NewLengthAction,
 		// source


Test patch:
diff --git a/internal/primitive/transform/action/array/unfold_array_test.go b/internal/primitive/transform/action/array/unfold_array_test.go
new file mode 100644
index 0000000..5d73963
--- /dev/null
+++ b/internal/primitive/transform/action/array/unfold_array_test.go
@@ -0,0 +1,63 @@
+// Copyright 2023 Linkall Inc.
+//
+// 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 array_test
+
+import (
+	"testing"
+
+	cetest "github.com/cloudevents/sdk-go/v2/test"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/action/array"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/context"
+	"github.com/linkall-labs/vanus/internal/primitive/transform/runtime"
+	. "github.com/smartystreets/goconvey/convey"
+)
+
+func TestUnfoldArrayAction(t *testing.T) {
+	funcName := array.NewUnfoldArrayAction().Name()
+	Convey("test unfold array valid", t, func() {
+		a, err := runtime.NewAction([]interface{}{funcName, "$.data.array", "$.data.target"})
+		So(err, ShouldBeNil)
+
+		e := cetest.MinEvent()
+		data := map[string]interface{}{
+			"array": []interface{}{"one", 2, []string{"three"}},
+		}
+		err = a.Execute(&context.EventContext{
+			Event: &e,
+			Data:  data,
+		})
+		So(err, ShouldBeNil)
+		So(data, ShouldHaveLength, 4)
+		So(data["target-0"], ShouldEqual, "one")
+		So(data["target-1"], ShouldEqual, 2)
+		So(data["target-2"], ShouldResemble, []interface{}{"three"})
+	})
+	Convey("test unfold array string input", t, func() {
+		a, err := runtime.NewAction([]interface{}{funcName, "$.data.array", "$.data.target"})
+		So(err, ShouldBeNil)
+
+		e := cetest.MinEvent()
+		data := map[string]interface{}{
+			"array": "one",
+		}
+		err = a.Execute(&context.EventContext{
+			Event: &e,
+			Data:  data,
+		})
+		So(err, ShouldBeNil)
+		So(data, ShouldHaveLength, 2)
+		So(data["target-0"], ShouldEqual, "one")
+	})
+}
diff --git a/internal/primitive/transform/runtime/action_bench_test.go b/internal/primitive/transform/runtime/action_bench_test.go
index 0ba903b..ae8c9f5 100644
--- a/internal/primitive/transform/runtime/action_bench_test.go
+++ b/internal/primitive/transform/runtime/action_bench_test.go
@@ -80,4 +80,5 @@ func BenchmarkAction(b *testing.B) {
 	b.Run("capitalize_sentence", actionBenchmark([]interface{}{"capitalize_sentence", "$.data.str"}))
 	b.Run("check_custom_values", actionBenchmark([]interface{}{"check_custom_values", "$.data.str", "value", "$.data.target", "true", "false"}))
 	b.Run("split_with_delimiter", actionBenchmark([]interface{}{"split_with_delimiter", "$.data.str", "a", "$.data.target"}))
+	b.Run("unfold_array", actionBenchmark([]interface{}{"unfold_array", "$.data.str", "$.data.target"}))
 }