eventbus: remove hacks, add sender

pull/3134/head
Abdullah Atta 2019-12-18 10:16:33 +05:00 committed by Alexander Medvednikov
parent 02939d776b
commit 489ec05b23
6 changed files with 148 additions and 139 deletions

View File

@ -11,6 +11,8 @@ fn main(){
some_module.do_work() some_module.do_work()
} }
fn on_error(p eventbus.Params) { fn on_error(sender voidptr, p eventbus.Params) {
work := *(*some_module.Work(sender))
println(work.hours)
println(p.get_string("error")) println(p.get_string("error"))
} }

View File

@ -8,14 +8,20 @@ const (
eb = eventbus.new() eb = eventbus.new()
) )
pub struct Work {
pub:
hours int
}
pub fn do_work(){ pub fn do_work(){
work := Work{20}
mut params := eventbus.Params{} mut params := eventbus.Params{}
for i in 0..20 { for i in 0..20 {
println("working...") println("working...")
if i == 15 { if i == 15 {
params.put_string("error", "CRASH!!") params.put_string("error", "CRASH!!")
eb.publish("error", params) eb.publish("error", work, params)
eb.publish("error", params) eb.publish("error", work, params)
return return
} }
} }

View File

@ -10,14 +10,14 @@ A module to provide eventing capabilities using pub/sub.
**EventBus:** **EventBus:**
1. `publish(string, Params)` - publish an event with provided Params & name 1. `publish(string, voidptr, Params)` - publish an event with provided Params & name
2. `clear_all()` - clear all subscribers 2. `clear_all()` - clear all subscribers
3. `has_subscriber(string)` - check if a subscriber to an event exists 3. `has_subscriber(string)` - check if a subscriber to an event exists
**Subscriber:** **Subscriber:**
1. `subscribe(string, fn(Params))` - subscribe to an event 1. `subscribe(string, fn(voidptr, Params))` - subscribe to an event
2. `subscribe_once(string, fn(Params))` - subscribe only once to an event 2. `subscribe_once(string, fn(voidptr, Params))` - subscribe only once to an event
3. `is_subscribed(string)` - check if we are subscribed to an event 3. `is_subscribed(string)` - check if we are subscribed to an event
4. `unsubscribe(string)` - unsubscribe from an event 4. `unsubscribe(string)` - unsubscribe from an event
@ -26,11 +26,11 @@ A module to provide eventing capabilities using pub/sub.
The function given to `subscribe` and `subscribe_once` must match this: The function given to `subscribe` and `subscribe_once` must match this:
```v ```v
fn(Params){ fn(voidptr, Params){
} }
// Example // Example
fn onPress(p Params){ fn onPress(sender voidptr, p Params){
//your code here... //your code here...
} }
``` ```
@ -39,7 +39,7 @@ fn onPress(p Params){
For **usage across modules** [check the example](https://github.com/vlang/v/tree/master/examples/eventbus). For **usage across modules** [check the example](https://github.com/vlang/v/tree/master/examples/eventbus).
_Note: As a general rule, you will need to **subscribe before emitting**._ _Note: As a general rule, you will need to **subscribe before publishing**._
**main.v** **main.v**
@ -62,8 +62,13 @@ fn main(){
} }
// the event handler // the event handler
fn on_error(p eventbus.Params) { fn on_error(sender voidptr, p eventbus.Params) {
println(p.get_string("error")) //cast the sender to the real type
//you can also make this mutable if required.
work := *(*Work(sender)) //a little verbose but works
error := p.get_string("error")
println('error occured on ${work.hours}. Error: ${error}')
} }
``` ```
@ -76,12 +81,17 @@ import (
eventbus eventbus
) )
struct Work{
hours int
}
fn do_work(){ fn do_work(){
work := Work{20}
// get a mutable Params instance & put some data into it // get a mutable Params instance & put some data into it
mut params := eventbus.Params{} mut params := eventbus.Params{}
params.put_string("error", "Error: no internet connection.") params.put_string("error", "Error: no internet connection.")
// publish the event // publish the event
eb.publish("error", params) eb.publish("error", work, params)
} }
``` ```
@ -89,38 +99,39 @@ fn do_work(){
```v ```v
mut params := eventbus.Params{} mut params := eventbus.Params{}
params.put_string("string", "vevent")
params.put_string("string", "some_string")
params.put_int("int", 20) params.put_int("int", 20)
params.put_bool("bo", true) params.put_bool("bool", true)
//the array & map currently needs to set like this
eventbus.put_array(mut params, "array", [1,2,3])
eventbus.put_map(mut params, "map", "", {"hello": "world"})
params.get_string("string") == "vevent" // add maps and arrays of any type like this
params.get_int("int") == 20 arr := [1,2,3]
params.get_bool("bo") == true params.put_array("array", arr)
m := params.get_string_map("map") mp := {"hello": "world"}
//the array currently needs to gotten like this params.put_map("map", mp)
arr := eventbus.get_array(params, "array", 0)
//you can also pass around custom type arrays & maps (it's a little crude but works): //get and use the params like this
struct Example{} assert params.get_string("string") == "some_string"
custom_map := {"example": Example{}} assert params.get_int("int") == 20
eventbus.put_map(mut params, "custom_map", Example{}, custom_map) assert params.get_bool("bool") == true
//and get it like this
eventbus.get_map(params, "custom_map", {"":Example{}}
//For arrays: g_arr := params.get_array("array", 0)
eventbus.put_array(mut params, "array", [Example{}]) assert g_arr[0] == 1
eventbus.get_array(params, "custom_array", Example{})
g_m := params.get_map("map", "")
assert g_m["hello"] == "world"
``` ```
#### Caution when putting arrays:
Currently putting arrays and maps directly as parameters in `put_array` doesn't work, so make a variable first and use that.
### Notes: ### Notes:
1. Each `EventBus` instance has it's own registry (i.e. there is no global event registry so you can't just subscribe to an event wherever you are. 1. Each `EventBus` instance has it's own registry (i.e. there is no global event registry so you can't just subscribe to an event wherever you are.
2. Each `EventBus` has a `Subscriber` instance which will need to be either exposed or you can make small public helper functions specific to your module like (`onPress`, `onError`) and etc. 2. Each `EventBus` has a `Subscriber` instance which will need to be either exposed or you can make small public helper functions specific to your module like (`onPress`, `onError`) and etc.
3. The `eventbus` module has some helpers to ease getting/setting of Params (since V doesn't support empty interfaces yet or reflection) so use them (see usage above). 3. The `eventbus` module has some helpers to ease getting/setting of Params (since V doesn't support empty interfaces yet or reflection) so use them (see usage above).
**The rationale behind separating Subscriber & Emitter:** **The rationale behind separating Subscriber & Publisher:**
This is mainly for security because the if emitter & subscriber are both passed around, a client can easily emit events acting as the server. So a client should only be able to use the Subscriber methods. This is mainly for security because the if publisher & subscriber are both passed around, a client can easily publish events acting as the server. So a client should only be able to use the Subscriber methods.

View File

@ -1,6 +1,5 @@
module eventbus module eventbus
pub struct Publisher { pub struct Publisher {
mut: mut:
registry &Registry registry &Registry
@ -19,11 +18,11 @@ struct Registry{
} }
struct EventHandler { struct EventHandler {
func fn(Params) func fn(voidptr, Params)
} }
pub struct EventBus{ pub struct EventBus{
mut: pub mut:
registry &Registry registry &Registry
publisher &Publisher publisher &Publisher
pub: pub:
@ -45,9 +44,9 @@ pub fn new() &EventBus{
// EventBus Methods // EventBus Methods
pub fn (eb &EventBus) publish(name string, p Params) { pub fn (eb &EventBus) publish(name string, sender voidptr, p Params) {
mut publisher := eb.publisher mut publisher := eb.publisher
publisher.publish(name, p) publisher.publish(name, sender, p)
} }
pub fn (eb &EventBus) clear_all(){ pub fn (eb &EventBus) clear_all(){
@ -61,36 +60,38 @@ pub fn (eb &EventBus) has_subscriber(name string) bool {
// Publisher Methods // Publisher Methods
fn (pb mut Publisher) publish(name string, p Params){ fn (pb mut Publisher) publish(name string, sender voidptr, p Params){
//p.put_custom("sender", "any", sender) //add sender to params
for i, n in pb.registry.names { for i, n in pb.registry.names {
if name == n { if name == n {
eh := pb.registry.events[i] eh := pb.registry.events[i]
invoke(eh, p)
once_index := pb.registry.once.index(pb.registry.names[i]) once_index := pb.registry.once.index(pb.registry.names[i])
if once_index > -1 { if once_index > -1 {
pb.registry.events.delete(i) pb.registry.events.delete(i)
pb.registry.names.delete(i) pb.registry.names.delete(i)
pb.registry.once.delete(once_index) pb.registry.once.delete(once_index)
} }
invoke(eh, sender, p)
} }
} }
} }
fn (p mut Publisher) clear_all(){ fn (p mut Publisher) clear_all(){
for i, n in p.registry.names { if p.registry.names.len == 0 {return}
for i := p.registry.names.len - 1; i >= 0; i-- {
p.registry.delete_entry(i) p.registry.delete_entry(i)
} }
} }
// Subscriber Methods // Subscriber Methods
pub fn (s mut Subscriber) subscribe(name string, handler fn(Params)){ pub fn (s mut Subscriber) subscribe(name string, handler fn(voidptr, Params)){
s.registry.names << name s.registry.names << name
v := voidptr(handler) v := voidptr(handler)
s.registry.events << v s.registry.events << v
} }
pub fn (s mut Subscriber) subscribe_once(name string, handler fn(Params)){ pub fn (s mut Subscriber) subscribe_once(name string, handler fn(voidptr, Params)){
s.subscribe(name, handler) s.subscribe(name, handler)
s.registry.once << name s.registry.once << name
} }
@ -99,7 +100,7 @@ pub fn (s &Subscriber) is_subscribed(name string) bool {
return s.registry.check_subscriber(name) return s.registry.check_subscriber(name)
} }
pub fn (s mut Subscriber) unsubscribe(name string, handler fn(Params)){ pub fn (s mut Subscriber) unsubscribe(name string, handler fn(voidptr, Params)){
v := voidptr(handler) v := voidptr(handler)
for i, n in s.registry.names { for i, n in s.registry.names {
if name == n { if name == n {
@ -131,7 +132,7 @@ fn (r mut Registry) delete_entry(index int) {
// Helper Functions // Helper Functions
fn invoke(p voidptr, arr Params){ fn invoke(p, sender voidptr, arr Params){
handler := EventHandler{p}.func handler := EventHandler{p}.func
handler(arr) handler(sender, arr)
} }

View File

@ -5,38 +5,60 @@ import (
fn test_eventbus(){ fn test_eventbus(){
mut eb := eventbus.new() mut eb := eventbus.new()
eb.subscriber.subscribe_once("on_test", on_test) eb.subscriber.subscribe_once("on_test", on_test)
assert eb.has_subscriber("on_test") == true
assert eb.subscriber.is_subscribed("on_test") == true assert eb.has_subscriber("on_test")
assert eb.subscriber.is_subscribed("on_test")
mut params := eventbus.Params{} mut params := eventbus.Params{}
params.put_string("eventbus", "vevent") params.put_string("eventbus", "vevent")
eb.publish("on_test", params)
assert eb.has_subscriber("on_test") == false eb.publish("on_test", eb, params)
assert eb.subscriber.is_subscribed("on_test") == false
eb.subscriber.subscribe_once("on_test", on_test) assert !eb.has_subscriber("on_test")
assert eb.has_subscriber("on_test") == true assert !eb.subscriber.is_subscribed("on_test")
assert eb.subscriber.is_subscribed("on_test") == true
eb.subscriber.subscribe("on_test", on_test)
assert eb.has_subscriber("on_test")
assert eb.subscriber.is_subscribed("on_test")
eb.clear_all() eb.clear_all()
assert eb.has_subscriber("on_test") == false
assert eb.subscriber.is_subscribed("on_test") == false assert !eb.has_subscriber("on_test")
assert !eb.subscriber.is_subscribed("on_test")
} }
fn test_params(){ fn test_params(){
mut params := eventbus.Params{} mut params := eventbus.Params{}
params.put_string("string", "vevent")
params.put_int("int", 20)
params.put_bool("bo", true)
eventbus.put_array(mut params, "array", [1,2,3])
eventbus.put_map(mut params, "map", "", {"hello": "world"})
assert params.get_string("string") == "vevent" params.put_string("string", "some_string")
params.put_int("int", 20)
params.put_bool("bool", true)
arr := [1,2,3]
params.put_array("array", arr)
mp := {"hello": "world"}
params.put_map("map", mp)
assert params.get_string("string") == "some_string"
assert params.get_int("int") == 20 assert params.get_int("int") == 20
assert params.get_bool("bo") == true assert params.get_bool("bool") == true
arr := eventbus.get_array(params, "array", 0)
assert arr[0] == 1 g_arr := params.get_array("array", 0)
m := params.get_string_map("map") assert g_arr[0] == 1
assert m["hello"] == "world"
g_m := params.get_map("map", "")
assert g_m["hello"] == "world"
} }
fn on_test(p eventbus.Params) { fn on_test(sender voidptr, p eventbus.Params) {
mut eb := *(*eventbus.EventBus(sender))
eb.subscriber.subscribe("on_test_2", on_test_2)
eb.clear_all()
assert !eb.has_subscriber("on_test_2")
assert !eb.subscriber.is_subscribed("on_test_2")
assert p.get_string("eventbus") == "vevent" assert p.get_string("eventbus") == "vevent"
} }
fn on_test_2(sender voidptr, p eventbus.Params){}

View File

@ -14,7 +14,6 @@ struct Param{
typ string typ string
name string name string
value voidptr value voidptr
keys voidptr
} }
pub fn (p Params) get_string(name string) string { pub fn (p Params) get_string(name string) string {
@ -32,68 +31,37 @@ pub fn (p Params) get_bool(name string) bool {
return if is_type {int(param.value) == 1}else{false} return if is_type {int(param.value) == 1}else{false}
} }
pub fn get_array<T>(p Params, name string, def T) []T { pub fn (p Params) get_array<T>(name string, def T) []T {
param, is_type := p.get_param(name, "array")
if is_type {
val := param.value
return unmarshall_array(def, val)
} else {
return []
}
}
pub fn (p Params) get_map<T>(name string, def T) map[string]T {
param, is_type := p.get_param(name, "map")
if is_type {
val := param.value
return unmarshall_map(def, val)
} else {
return map[string]T
}
}
pub fn (p Params) get_raw(name string) voidptr {
param, _ := p.get_param(name, "") param, _ := p.get_param(name, "")
if param.typ.contains("[") { return param.value
len := parse_len(param.typ, "[", "]")
mut b := []T
b = C.new_array_from_c_array_no_alloc(len, len, sizeof(T), param.value)
return b
}
return []
} }
fn C.map_set() // TODO remove hack pub fn (p mut Params) put_map(name string, value voidptr) {
p.put_custom(name, "map", value)
// TODO: make this a method after generics are fixed.
pub fn get_map<T>(p Params, name string, valueTyp T) map[string]T {
param, _ := p.get_param(name, "")
ret := map[string]T
if param.typ.contains("map(") {
len := parse_len(param.typ, "(", ")")
mut keys := []string
// the best way (that I could find) to convert voidptr into array without alloc
// since we know that the voidptr we are getting is an array
keys = C.new_array_from_c_array_no_alloc(len, len, sizeof(T), param.keys)
for i, key in keys {
//the most simple way to set map value without knowing the typ
// TODO remove
C.map_set(&ret, key, param.value + i * sizeof(T))
}
}
return ret
} }
pub fn (p Params) get_string_map(name string) map[string]string { pub fn (p mut Params) put_array(name string, arr voidptr) {
return get_map(p, name, "") p.put_custom(name, "array", arr)
}
pub fn (p Params) get_int_map(name string) map[string]int {
return get_map(p, name, 0)
}
pub fn (p Params) get_bool_map(name string) map[string]bool {
return get_map(p, name, false)
}
// TODO: make this a method after generics are fixed.
pub fn put_map<T>(p mut Params, name string, valueTyp T, value map[string]T) {
keys := value.keys()
mut vals := []T
for key in keys {
vals << value[key]
}
p.params << Param {
typ: "map($value.size)"
name: name
keys: keys.data
value: vals.data
}
}
// TODO: make this a method after generic methods are working.
pub fn put_array<T>(p mut Params, name string, arr []T) {
p.put_custom(name, "[$arr.len]", arr.data)
} }
pub fn (p mut Params) put_int(name string, num int) { pub fn (p mut Params) put_int(name string, num int) {
@ -108,25 +76,24 @@ pub fn (p mut Params) put_bool(name string, val bool) {
p.put_custom(name, "bool", if val { 1 } else { 0 }) p.put_custom(name, "bool", if val { 1 } else { 0 })
} }
pub fn (p mut Params) put_custom(name string, typ string, data voidptr) { pub fn (p mut Params) put_custom(name, typ string, data voidptr) {
p.params << Param {typ, name, data, voidptr(0)} p.params << Param {typ, name, data}
} }
//HELPERS //HELPERS
fn parse_len(typ, s_tok, e_tok string) int {
start_index := typ.index(s_tok) or { return 0 }
end_index := typ.index(e_tok) or { return 0 }
len := typ[start_index+1..end_index].int()
//t := typ.substr(typ.index(e_tok) + 1, typ.len)
return len
}
fn (p Params) get_param(name string, typ string) (Param, bool) { fn (p Params) get_param(name string, typ string) (Param, bool) {
for param in p.params { for param in p.params {
if param.name == name { if param.name == name {
return param, param.typ == typ return param, param.typ == typ
} }
} }
return Param{value: voidptr(0), keys: voidptr(0)}, false return Param{value: voidptr(0)}, false
} }
fn unmarshall_array<T> (s T, m voidptr) array_T {
return *(*array_T(m))
}
fn unmarshall_map<T> (s T, m voidptr) map_T {
return *(*map_T(m))
}