From f9c03998b8e5476c7d89f167552b44ee75db1315 Mon Sep 17 00:00:00 2001 From: Daniel Barlow Date: Sun, 21 Apr 2024 13:19:17 +0100 Subject: [PATCH] implement subscriptions with callback --- pkgs/devout/devout.fnl | 27 ++++++++++++++++++--------- pkgs/devout/test.fnl | 14 ++++++++++---- 2 files changed, 28 insertions(+), 13 deletions(-) diff --git a/pkgs/devout/devout.fnl b/pkgs/devout/devout.fnl index b1481fb..b6041ed 100644 --- a/pkgs/devout/devout.fnl +++ b/pkgs/devout/devout.fnl @@ -20,19 +20,28 @@ (doto found (table.insert e)) 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 [] - (let [db {}] + (let [db {} + subscribers []] { :find (fn [_ terms] (find-in-database db terms)) - :add (fn [_ 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) - ))) + :add (fn [_ event-string] (record-event db subscribers event-string)) :at-path (fn [_ path] (. db path)) + :subscribe (fn [_ callback terms] + (table.insert subscribers {: callback : terms })) + })) diff --git a/pkgs/devout/test.fnl b/pkgs/devout/test.fnl index ed7a106..8c61541 100644 --- a/pkgs/devout/test.fnl +++ b/pkgs/devout/test.fnl @@ -114,10 +114,16 @@ MINOR=17") ;;; tests for subscriptions -(example "I can subscribe to some search terms") - -(example "my callback is invoked when devices matching those terms are - added/changed/removed") +(example + "I can subscribe to some search terms and be notified of matching events" + (var received []) + (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"))