Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🎲 random_once router type #888

Open
wants to merge 22 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
abc59fa
Add random_once router type
rowanseymour Mar 20, 2020
108c071
Merge branch 'master' into random_once
rowanseymour Apr 2, 2020
99db5d4
Merge branch 'master' into random_once
rowanseymour Apr 3, 2020
128a5ba
Merge branch 'master' into random_once
rowanseymour Apr 21, 2020
3314f5c
Merge branch 'master' into random_once
rowanseymour May 5, 2020
08cf3f5
Merge branch 'master' into random_once
rowanseymour Jun 3, 2020
f7d21db
Fix test
rowanseymour Jun 3, 2020
ac7b5ea
Merge branch 'master' into random_once
rowanseymour Jun 5, 2020
e717dc2
Merge branch 'master' into random_once
rowanseymour Jun 10, 2020
a677e70
Merge branch 'master' into random_once
rowanseymour Jul 20, 2020
22500a3
Merge branch 'master' into random_once
rowanseymour Jul 20, 2020
cd0b00f
Merge branch 'master' into random_once
rowanseymour Jul 23, 2020
3c2a2cd
Merge branch 'master' into random_once
rowanseymour Sep 2, 2020
ad0932b
Merge branch 'master' into random_once
rowanseymour Sep 3, 2020
9c227f6
Merge branch 'master' into random_once
rowanseymour Sep 4, 2020
2711d24
Merge branch 'master' into random_once
rowanseymour Sep 10, 2020
f5f7078
Merge branch 'master' into random_once
rowanseymour Jan 14, 2021
4b0d3d8
Merge branch 'master' into random_once
rowanseymour Jan 15, 2021
1518720
Merge branch 'master' into random_once
rowanseymour Jan 15, 2021
77954ad
Revert locale file changes
rowanseymour Jan 15, 2021
d1cb235
Fix tests
rowanseymour Jan 15, 2021
88c4648
Merge branch 'main' into random_once
rowanseymour Mar 4, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions flows/routers/random_once.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package routers

import (
"encoding/json"
"strconv"

"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/gocommon/random"
"github.com/nyaruka/goflow/flows"
"github.com/nyaruka/goflow/utils"

"github.com/pkg/errors"
)

func init() {
registerType(TypeRandomOnce, readRandomOnceRouter)
}

// TypeRandomOnce is the type for a random once router
const TypeRandomOnce string = "random_once"

// RandomOnceRouter is a router which will choose one of it's exits at random, but only using each exit once
type RandomOnceRouter struct {
baseRouter

defaultCategoryUUID flows.CategoryUUID
}

// NewRandomOnce creates a new random once router
func NewRandomOnce(wait flows.Wait, resultName string, categories []flows.Category, defaultCategoryUUID flows.CategoryUUID) *RandomOnceRouter {
return &RandomOnceRouter{
baseRouter: newBaseRouter(TypeRandom, wait, resultName, categories),
defaultCategoryUUID: defaultCategoryUUID,
}
}

// Validate validates that the fields on this router are valid
func (r *RandomOnceRouter) Validate(flow flows.Flow, exits []flows.Exit) error {
// check the done category is valid
if r.defaultCategoryUUID != "" && !r.isValidCategory(r.defaultCategoryUUID) {
return errors.Errorf("default category %s is not a valid category", r.defaultCategoryUUID)
}

return r.validate(flow, exits)
}

// Route determines which exit to take from a node
func (r *RandomOnceRouter) Route(run flows.FlowRun, step flows.Step, logEvent flows.EventCallback) (flows.ExitUUID, error) {
// find all the exits we have taken in the past
exitsTaken := make(map[flows.ExitUUID]bool)
for _, s := range run.Path() {
if s.NodeUUID() == step.NodeUUID() {
exitsTaken[s.ExitUUID()] = true
}
}

// convert that to bucket categories remaining
bucketsRemaining := make([]flows.Category, 0)
for _, c := range r.categories {
if !exitsTaken[c.ExitUUID()] && c.UUID() != r.defaultCategoryUUID {
bucketsRemaining = append(bucketsRemaining, c)
}
}

// take the default route if we've been to all the other bucket categories
if len(bucketsRemaining) == 0 {
return r.routeToCategory(run, step, r.defaultCategoryUUID, "", "", nil, logEvent)
}

// pick a random remaining bucket category
categoryNum := random.IntN(len(bucketsRemaining))
categoryUUID := bucketsRemaining[categoryNum].UUID()

return r.routeToCategory(run, step, categoryUUID, strconv.Itoa(categoryNum), "", nil, logEvent)
}

//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------

type randomOnceRouterEnvelope struct {
baseRouterEnvelope

DefaultCategoryUUID flows.CategoryUUID `json:"default_category_uuid" validate:"required,uuid4"`
}

func readRandomOnceRouter(data json.RawMessage) (flows.Router, error) {
e := &randomOnceRouterEnvelope{}
if err := utils.UnmarshalAndValidate(data, e); err != nil {
return nil, err
}

r := &RandomOnceRouter{
defaultCategoryUUID: e.DefaultCategoryUUID,
}

if err := r.unmarshal(&e.baseRouterEnvelope); err != nil {
return nil, err
}

return r, nil
}

// MarshalJSON marshals this resume into JSON
func (r *RandomOnceRouter) MarshalJSON() ([]byte, error) {
e := &randomOnceRouterEnvelope{
DefaultCategoryUUID: r.defaultCategoryUUID,
}

if err := r.marshal(&e.baseRouterEnvelope); err != nil {
return nil, err
}

return jsonx.Marshal(e)
}
118 changes: 118 additions & 0 deletions flows/routers/testdata/random_once.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
[
{
"description": "Random bucket category chosen and result created",
"router": {
"type": "random_once",
"result_name": "Random Result",
"categories": [
{
"uuid": "598ae7a5-2f81-48f1-afac-595262514aa1",
"name": "Question 1",
"exit_uuid": "49a47f31-ec90-42b5-a0d8-6efb5b1fa57b"
},
{
"uuid": "c70fe86c-9aac-4cc2-a5cb-d35cbe3fed6e",
"name": "Question 2",
"exit_uuid": "5bd6a427-2b9a-4a4d-ad3f-eb39eaaa7e5a"
},
{
"uuid": "78ae8f05-f92e-43b2-a886-406eaea1b8e0",
"name": "Done",
"exit_uuid": "b787ffe3-c21a-46ad-9475-954614b52477"
}
],
"default_category_uuid": "78ae8f05-f92e-43b2-a886-406eaea1b8e0"
},
"results": {
"random_result": {
"name": "Random Result",
"value": "1",
"category": "Question 2",
"node_uuid": "64373978-e8f6-4973-b6ff-a2993f3376fc",
"created_on": "2018-10-18T14:20:30.000123456Z"
}
},
"events": [
{
"type": "run_result_changed",
"created_on": "2018-10-18T14:20:30.000123456Z",
"step_uuid": "59d74b86-3e2f-4a93-aece-b05d2fdcde0c",
"name": "Random Result",
"value": "1",
"category": "Question 2"
}
],
"inspection": {
"dependencies": [],
"issues": [],
"results": [
{
"key": "random_result",
"name": "Random Result",
"categories": [
"Question 1",
"Question 2",
"Done"
],
"node_uuids": [
"64373978-e8f6-4973-b6ff-a2993f3376fc"
]
}
],
"waiting_exits": [],
"parent_refs": []
}
},
{
"description": "Default category taken if no bucket categories",
"router": {
"type": "random_once",
"result_name": "Random Result",
"categories": [
{
"uuid": "78ae8f05-f92e-43b2-a886-406eaea1b8e0",
"name": "Done",
"exit_uuid": "b787ffe3-c21a-46ad-9475-954614b52477"
}
],
"default_category_uuid": "78ae8f05-f92e-43b2-a886-406eaea1b8e0"
},
"results": {
"random_result": {
"name": "Random Result",
"value": "",
"category": "Done",
"node_uuid": "64373978-e8f6-4973-b6ff-a2993f3376fc",
"created_on": "2018-10-18T14:20:30.000123456Z"
}
},
"events": [
{
"type": "run_result_changed",
"created_on": "2018-10-18T14:20:30.000123456Z",
"step_uuid": "59d74b86-3e2f-4a93-aece-b05d2fdcde0c",
"name": "Random Result",
"category": "Done",
"value": ""
}
],
"inspection": {
"dependencies": [],
"issues": [],
"results": [
{
"key": "random_result",
"name": "Random Result",
"categories": [
"Done"
],
"node_uuids": [
"64373978-e8f6-4973-b6ff-a2993f3376fc"
]
}
],
"waiting_exits": [],
"parent_refs": []
}
}
]
3 changes: 3 additions & 0 deletions test/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/nyaruka/gocommon/dates"
"github.com/nyaruka/gocommon/httpx"
"github.com/nyaruka/gocommon/jsonx"
"github.com/nyaruka/gocommon/random"
"github.com/nyaruka/gocommon/uuids"
"github.com/nyaruka/goflow/assets"
"github.com/nyaruka/goflow/envs"
Expand Down Expand Up @@ -191,6 +192,7 @@ func TestFlows(t *testing.T) {
require.NoError(t, err)
require.True(t, len(testCases) > 0)

defer random.SetGenerator(random.DefaultGenerator)
defer uuids.SetGenerator(uuids.DefaultGenerator)
defer dates.SetNowSource(dates.DefaultNowSource)
defer httpx.SetRequestor(httpx.DefaultRequestor)
Expand All @@ -200,6 +202,7 @@ func TestFlows(t *testing.T) {
var httpMocksCopy *httpx.MockRequestor
fmt.Printf("running %s\n", tc)

random.SetGenerator(random.NewSeededGenerator(123456))
uuids.SetGenerator(uuids.NewSeededGenerator(123456))
dates.SetNowSource(dates.NewSequentialNowSource(time.Date(2018, 7, 6, 12, 30, 0, 123456789, time.UTC)))
smtpx.SetSender(smtpx.NewMockSender(""))
Expand Down
Loading