implement subscriptions with callback

This commit is contained in:
Daniel Barlow 2024-04-21 13:19:17 +01:00
parent 50de1b090f
commit f9c03998b8
2 changed files with 28 additions and 13 deletions

View file

@ -20,19 +20,28 @@
(doto found (table.insert e)) (doto found (table.insert e))
found))) found)))
(fn record-event [db subscribers str]
(let [e (parse-uevent str)]
(match e.action
:add (tset db e.path e)
:change (tset db e.path e)
;; should we do something for bind?
:remove (tset db e.path nil)
)
(each [_ { : terms : callback } (ipairs subscribers)]
(if (event-matches? e terms) (callback e)))
e))
(fn database [] (fn database []
(let [db {}] (let [db {}
subscribers []]
{ {
:find (fn [_ terms] (find-in-database db terms)) :find (fn [_ terms] (find-in-database db terms))
:add (fn [_ event-string] :add (fn [_ event-string] (record-event db subscribers event-string))
(let [e (parse-uevent event-string)]
(match e.action
:add (tset db e.path e)
:change (tset db e.path e)
; ;bind ?
:remove (tset db e.path nil)
)))
:at-path (fn [_ path] (. db path)) :at-path (fn [_ path] (. db path))
:subscribe (fn [_ callback terms]
(table.insert subscribers {: callback : terms }))
})) }))

View file

@ -114,10 +114,16 @@ MINOR=17")
;;; tests for subscriptions ;;; tests for subscriptions
(example "I can subscribe to some search terms") (example
"I can subscribe to some search terms and be notified of matching events"
(example "my callback is invoked when devices matching those terms are (var received [])
added/changed/removed") (let [db (database)
subscriber (fn [e] (table.insert received e))]
(db:subscribe subscriber {:devname "/dev/sdb1"})
(db:add sdb1-insert)
(db:add sda-uevent)
(db:add sdb1-remove)
(expect= (# received) 2)))
(if failed (os.exit 1) (print "OK")) (if failed (os.exit 1) (print "OK"))