Skip to content

Instantly share code, notes, and snippets.

@dpwiz
Last active February 25, 2016 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpwiz/e6c16dec877368639ee2 to your computer and use it in GitHub Desktop.
Save dpwiz/e6c16dec877368639ee2 to your computer and use it in GitHub Desktop.
Check local registry for a process and spawn one if necessary.
import Control.Distributed.Process
import Control.Distributed.Process
spawnLocalOrHandoff :: String -> Process () -> Process ProcessId
spawnLocalOrHandoff regKey proc = do
(pidTo, pidFrom) <- newChan
pid <- spawnLocal $ registerOrHandoff regKey pidTo proc
withMonitor pid $ receiveWait
[ matchChan pidFrom $ either die pure
, matchIf
( \(ProcessMonitorNotification _ mpid r) ->
mpid == pid && r /= DiedNormal
)
$ \_ -> die
("Process crashed while attempting registration." :: String)
]
registerOrHandoff :: String -> SendPort (Either String ProcessId) -> Process () -> Process ()
registerOrHandoff regKey pidTo proc = do
myself <- getSelfPid
res <- try $ register regKey myself
case res of
Right () ->
sendChan pidTo (Right myself) >> proc
Left (ProcessRegistrationException _ (Just someone)) ->
sendChan pidTo (Right someone)
Left _ ->
sendChan pidTo . Left $ concat
[ "Registration for "
, regKey
, " failed without hand-off pid provided."
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment