(;module: {#;doc "The actor model of concurrency."} lux (lux (control monad ["p" parser] ["ex" exception #+ exception:]) [io #- run "io/" Monad] (data text/format (coll [list "L/" Monoid Monad]) [product]) [macro #+ with-gensyms] (macro [code] ["s" syntax #+ syntax: Syntax] (syntax ["cs" common] (common ["csr" reader] ["csw" writer]))) [type]) (.. ["A" atom] ["P" promise "P/" Monad] ["T" task] [stm #+ Monad] [frp])) (exception: #export Poisoned) (exception: #export Killed) ## [Types] (with-expansions [ (as-is (-> s (Actor s) (T;Task s))) (as-is [Text s (List )])] (type: #export (Actor s) {#;doc "An actor, defined as all the necessities it requires."} {#mailbox (stm;Var ) #kill-switch (P;Promise Unit) #obituary (P;Promise )}) (type: #export (Message s) ) (type: #export (Obituary s) )) (type: #export (Behavior s) {#;doc "An actor's behavior when messages are received."} {#step (-> (Message s) s (Actor s) (T;Task s)) #end (-> Text s (P;Promise Unit))}) ## [Values] (def: #export (spawn init behavior) {#;doc "Given a behavior and initial state, spawns an actor and returns it."} (All [s] (-> s (Behavior s) (IO (Actor s)))) (io (let [[step end] behavior self (: (Actor ($ +0)) {#mailbox (stm;var (:! (Message ($ +0)) [])) #kill-switch (P;promise Unit) #obituary (P;promise (Obituary ($ +0)))}) mailbox-chan (io;run (stm;follow (get@ #mailbox self))) |mailbox| (stm;var mailbox-chan) _ (P/map (function [_] (io;run (do Monad [mb (stm;read! |mailbox|)] (frp;close mb)))) (get@ #kill-switch self)) process (loop [state init messages mailbox-chan] (do P;Monad [?messages+ messages] (case ?messages+ ## No kill-switch so far, so I may proceed... (#;Some [message messages']) (do P;Monad [#let [_ (io;run (stm;write! messages' |mailbox|))] ?state' (step message state self)] (case ?state' (#;Left error) (do @ [#let [_ (io;run (P;resolve [] (get@ #kill-switch self))) _ (io;run (frp;close messages'))] _ (end error state) remaining-messages (frp;consume messages')] (wrap [error state (#;Cons message remaining-messages)])) (#;Right state') (recur state' messages'))) ## Otherwise, clean-up and return current state. #;None (do P;Monad [#let [_ (io;run (frp;close messages)) death-message (Killed "")] _ (end death-message state)] (wrap [death-message state (list)])))))] self))) (def: #export (alive? actor) (All [s] (-> (Actor s) Bool)) (case [(P;poll (get@ #kill-switch actor)) (P;poll (get@ #obituary actor))] [#;None #;None] true _ false)) (def: #export (send message actor) {#;doc "Communicate with an actor through message passing."} (All [s] (-> (Message s) (Actor s) (IO Bool))) (if (alive? actor) (exec (io;run (stm;write! message (get@ #mailbox actor))) (io/wrap true)) (io/wrap false))) (def: #export (kill actor) {#;doc "Immediately kills the given actor (if it is not already dead)."} (All [s] (-> (Actor s) (io;IO Bool))) (if (alive? actor) (|> actor (get@ #kill-switch) (P;resolve [])) (io/wrap false))) (def: #export (poison actor) {#;doc "Kills the actor by sending a message that will kill it upon processing, but allows the actor to handle previous messages."} (All [s] (-> (Actor s) (IO Bool))) (send (function [state self] (T;throw Poisoned "")) actor)) ## [Syntax] (type: Method {#name Text #vars (List Text) #args (List [Text Code]) #state Text #self Text #return Code #body Code}) (def: method^ (Syntax Method) (s;form (do p;Monad [vars (p;default (list) (s;tuple (p;some s;local-symbol))) [name args state self] (s;form ($_ p;seq s;local-symbol (p;some csr;typed-input) s;local-symbol s;local-symbol )) return s;any body s;any] (wrap {#name name #vars vars #args args #state state #self self #return return #body body})))) (def: stop^ (Syntax [[Text Text] Code]) (s;form (p;seq (s;tuple (p;seq s;local-symbol s;local-symbol)) s;any))) (def: actor-decl^ (Syntax [(List Text) Text (List [Text Code])]) (p;seq (p;default (list) (s;tuple (p;some s;local-symbol))) (p;either (s;form (p;seq s;local-symbol (p;many csr;typed-input))) (p;seq s;local-symbol (:: p;Monad wrap (list)))))) (syntax: #export (actor: [export csr;export] [[_vars _name _args] actor-decl^] state-type [methods (p;some method^)] [?stop (p;opt stop^)]) {#;doc (doc "Defines an actor, with internal state and methods that can be called on it." "A method can access the actor's state through the state parameter." "A method can also access the actor itself through the self parameter." "A method may succeed or fail (in case of failure, the actor dies). This is handled through the Either type." "A method's output must be a promise containing a 2-tuple with the updated state and a return value." "All methods are run implicitly within the Promise monad." (actor: #export Counter Int ((count! [increment Int] state self) [Int Int] (if (i.>= 0 increment) (let [state' (i.+ increment state)] (T;return [state' [state state']])) (T;fail "Cannot add negative numbers!"))) ([cause state] (:: P;Monad wrap (log! (if (ex;match? ;;Killed cause) (format "Counter was killed: " (%i state)) cause)))) ))} (with-gensyms [g!message g!self g!state g!init g!error g!return g!output] (let [g!state-type (code;symbol ["" (format _name "//Actor:State")]) g!behavior (code;symbol ["" (format _name "//Actor:Behavior")]) g!actor (code;symbol ["" _name]) g!methods (L/map (: (-> Method Code) (function [(^slots [#name #vars #args #state #self #return #body])] (let [g!method (code;symbol ["" name]) g!vars (L/map (|>. [""] code;symbol) vars) g!var-refs (: (List Code) (if (list;empty? vars) (list) (|> vars list;size n.dec (list;n.range +0) (L/map (|>. code;nat (~) ($) (`)))))) g!args-names (L/map (|>. product;left [""] code;symbol) args) g!arg-types (L/map product;right args) g!state (code;symbol ["" state]) g!self (code;symbol ["" self])] (` (def: (~@ (csw;export export)) ((~ g!method) (~@ g!args-names) (~ g!self)) (All [(~@ g!vars)] (-> (~@ g!arg-types) (~ g!actor) (T;Task (~ return)))) (let [(~ g!output) (T;task (~ return))] (exec (;;send (function [(~ g!state) (~ g!self)] (do P;Monad [(~ g!return) (: (T;Task [((~ g!state-type) (~@ g!var-refs)) (~ return)]) (~ body))] (case (~ g!return) (#;Right [(~ g!state) (~ g!return)]) (exec (io;run (P;resolve (#;Right (~ g!return)) (~ g!output))) (T;return (~ g!state))) (#;Left (~ g!error)) (exec (io;run (P;resolve (#;Left (~ g!error)) (~ g!output))) (T;fail (~ g!error)))))) (~ g!self)) (~ g!output)))))))) methods) g!new (code;symbol ["" (format "new-" _name)]) g!vars (L/map (|>. [""] code;symbol) _vars)] (wrap (list& (` (type: (~@ (csw;export export)) ((~ g!state-type) (~@ g!vars)) (~ state-type))) (` (type: (~@ (csw;export export)) ((~ g!actor) (~@ g!vars)) (;;Actor ((~ g!state-type) (~@ g!vars))))) (` (def: (~@ (csw;export export)) (~ g!behavior) (All [(~@ g!vars)] (Behavior ((~ g!state-type) (~@ g!vars)))) {#step (function [(~' message) (~' state) (~' self)] ((~' message) (~' state) (~' self))) #end (~ (case ?stop (#;Some [[cause state] body]) (let [g!cause (code;symbol ["" cause]) g!state (code;symbol ["" state])] (` (function [(~ g!cause) (~ g!state)] (do P;Monad [] (~ body))))) #;None (` (:: P;Monad (~' wrap) []))))})) (` (def: (~@ (csw;export export)) ((~ g!new) (~ g!init)) (All [(~@ g!vars)] (-> ((~ g!state-type) (~@ g!vars)) (io;IO ((~ g!actor) (~@ g!vars))))) (;;spawn (~ g!init) (~ g!behavior)))) g!methods)) )))