github.com/koko1123/flow-go-1@v0.29.6/engine/access/relay/example_test.go (about) 1 package relay_test 2 3 import ( 4 "fmt" 5 "math/rand" 6 7 "github.com/rs/zerolog" 8 9 "github.com/koko1123/flow-go-1/engine/access/relay" 10 splitterNetwork "github.com/koko1123/flow-go-1/engine/common/splitter/network" 11 "github.com/koko1123/flow-go-1/model/flow" 12 "github.com/koko1123/flow-go-1/network/channels" 13 testnet "github.com/koko1123/flow-go-1/utils/unittest/network" 14 ) 15 16 func Example() { 17 // create a mock network 18 net := testnet.NewNetwork() 19 20 // create splitter network 21 logger := zerolog.Nop() 22 splitterNet := splitterNetwork.NewNetwork(net, logger) 23 24 // generate a random origin ID 25 var id flow.Identifier 26 rand.Seed(0) 27 rand.Read(id[:]) 28 29 // create engines 30 engineProcessFunc := func(engineName string) testnet.EngineProcessFunc { 31 return func(channel channels.Channel, originID flow.Identifier, event interface{}) error { 32 fmt.Printf("Engine %v received message: channel=%v, originID=%v, event=%v\n", engineName, channel, originID, event) 33 return nil 34 } 35 } 36 fooEngine := testnet.NewEngine().OnProcess(engineProcessFunc("Foo")) 37 barEngine := testnet.NewEngine().OnProcess(engineProcessFunc("Bar")) 38 39 // register engines on the splitter network 40 fooChannel := channels.Channel("foo-channel") 41 barChannel := channels.Channel("bar-channel") 42 _, err := splitterNet.Register(fooChannel, fooEngine) 43 if err != nil { 44 fmt.Println(err) 45 } 46 _, err = splitterNet.Register(barChannel, barEngine) 47 if err != nil { 48 fmt.Println(err) 49 } 50 51 // create another network that messages will be relayed to 52 relayNet := testnet.NewNetwork().OnPublish(func(channel channels.Channel, event interface{}, targetIDs ...flow.Identifier) error { 53 fmt.Printf("Message published to relay network: channel=%v, event=%v, targetIDs=%v\n", channel, event, targetIDs) 54 return nil 55 }) 56 57 // create relay engine 58 channels := channels.ChannelList{fooChannel, barChannel} 59 _, err = relay.New(logger, channels, splitterNet, relayNet) 60 if err != nil { 61 fmt.Println(err) 62 } 63 64 // send messages to network 65 err = net.Send(fooChannel, id, "foo") 66 if err != nil { 67 fmt.Println(err) 68 } 69 err = net.Send(barChannel, id, "bar") 70 if err != nil { 71 fmt.Println(err) 72 } 73 74 // Unordered output: 75 // Message published to relay network: channel=foo-channel, event=foo, targetIDs=[0000000000000000000000000000000000000000000000000000000000000000] 76 // Engine Foo received message: channel=foo-channel, originID=0194fdc2fa2ffcc041d3ff12045b73c86e4ff95ff662a5eee82abdf44a2d0b75, event=foo 77 // Message published to relay network: channel=bar-channel, event=bar, targetIDs=[0000000000000000000000000000000000000000000000000000000000000000] 78 // Engine Bar received message: channel=bar-channel, originID=0194fdc2fa2ffcc041d3ff12045b73c86e4ff95ff662a5eee82abdf44a2d0b75, event=bar 79 }