{-# LANGUAGE DeriveDataTypeable
, ScopedTypeVariables
, FlexibleInstances
, FlexibleContexts
#-}{-# OPTIONS -IControl/Workflow #-}{- | This module contains monadic combinators that express some workflow patterns.
see the docAprobal.hs example included in the package
EXAMPLE:
This fragment below describes the approbal procedure of a document.
First the document reference is sent to a list of bosses trough a queue.
ithey return a boolean in a return queue ( askUser)
the booleans are summed up according with a monoid instance (sumUp)
if the resullt is false, the correctWF workflow is executed
If the result is True, the pipeline continues to the next stage (`checkValidated`)
the next stage is the same process with a new list of users (superbosses).
There is a timeout of seven days. The result of the users that voted is summed
up according with the same monoid instance
if the result is true the document is added to the persistent list of approbed documents
if the result is false, the document is added to the persistent list of rejectec documents (@checlkValidated1@)
The program can be interrupted at any moment. The Workflow monad will restartWorkflows
it at the point where it was interrupted.
This example uses queues from "Data.Persistent.Queue"
@docApprobal :: Document -> Workflow IO ()
docApprobal doc = `getWFRef` \>>= docApprobal1
docApprobal1 rdoc=
return True \>>=
log \"requesting approbal from bosses\" \>>=
`sumUp` 0 (map (askUser doc rdoc) bosses) \>>=
checkValidated \>>=
log \"requesting approbal from superbosses or timeout\" \>>=
`sumUp` (7*60*60*24) (map(askUser doc rdoc) superbosses) \>>=
checkValidated1
askUser _ _ user False = return False
askUser doc rdoc user True = do
`step` $ `push` (quser user) rdoc
`logWF` (\"wait for any response from the user: \" ++ user)
`step` . `pop` $ qdocApprobal (title doc)
log txt x = `logWF` txt >> return x
checkValidated :: Bool -> `Workflow` IO Bool
checkValidated val =
case val of
False -> correctWF (title doc) rdoc >> return False
_ -> return True
checkValidated1 :: Bool -> Workflow IO ()
checkValidated1 val = step $ do
case val of
False -> `push` qrejected doc
_ -> `push` qapproved doc
mapM (\u ->deleteFromQueue (quser u) rdoc) superbosses@
-}moduleControl.Workflow.Patterns(-- * Low level combinatorssplit,merge,select,-- * High level conbinatorsvote,sumUp,Select(..))whereimportControl.Concurrent.STMimportData.MonoidimportqualifiedControl.Monad.CatchIOasCMCimportControl.Workflow.StatimportControl.WorkflowimportData.TypeableimportPreludehiding(catch)importControl.MonadimportControl.Monad.TransimportControl.ConcurrentimportControl.Exception.Extensible(Exception,SomeException)importData.RefSerializeimportControl.Workflow.StatimportqualifiedData.VectorasVimportData.TCacheimportDebug.TraceimportData.MaybedataActionWFa=ActionWF(WFRef(Maybea))ThreadId-- (WFRef (String, Bool))-- | spawn a list of independent workflow 'actions' with a seed value 'a'-- The results are reduced by `merge` or `select`split::(Typeableb,Serializeb,HasForkio,CMC.MonadCatchIOio)=>[a->Workflowiob]->a->Workflowio[ActionWFb]splitactionsa=mapM(\ac->domv<-newWFRefNothingth<-fork(aca>>=\v->(step.liftIO.atomicallySync.writeWFRefmv.Just)v)return$ActionWFmvth)actions-- | wait for the results and apply the cond to produce a single output in the Workflow monadmerge::(MonadIOio,Typeablea,Typeableb,Serializea,Serializeb)=>([a]->iob)->[ActionWFa]->Workflowiobmergecondresults=step$mapM(\(ActionWFmv_)->liftIO(atomically$readWFRef1mv))results>>=cond-- !> "cond"readWFRef1::(Serializea,Typeablea)=>WFRef(Maybea)->STMareadWFRef1r=domv<-readWFRefrcasemvofJust(Justv)->returnv-- !> "return v"JustNothing->retry-- !> "retry"Nothing->error$"readWFRef1: workflow not found "++showrdataSelect=Select-- ^ select the source output|Discard-- ^ Discard the source output|Continue-- ^ Continue the source process|FinishDiscard-- ^ Discard this output, kill all and return the selected outputs|FinishSelect-- ^ Select this output, kill all and return the selected outputsderiving(Typeable,Read,Show)instanceExceptionSelect-- | select the outputs of the workflows produced by `split` constrained within a timeout.-- The check filter, can select , discard or finish the entire computation before-- the timeout is reached. When the computation finalizes, it kill all-- the pending workflows and return the list of selected outputs-- the timeout is in seconds and it is is in the workflow monad,-- so it is possible to restart the process if interrupted,-- so it can proceed for years.---- This is necessary for the modelization of real-life institutional cycles such are political elections-- A timeout of 0 means no timeout.select::(Serializea-- , Serialize [a],Typeablea,HasForkio,CMC.MonadCatchIOio)=>Integer->(a->STMSelect)->[ActionWFa]->Workflowio[a]selecttimeoutcheckactions=dores<-liftIO$newTVarIO$V.generate(lengthactions)(constNothing)flag<-getTimeoutFlagtimeoutparent<-liftIOmyThreadIdchecThreads<-liftIO$newEmptyMVarcount<-liftIO$newMVar1letprocess=doletcheck'(ActionWFac_)i=doliftIO.atomically$dor<-readWFRef1acb<-checkrcasebofDiscard->return()Select->addResirContinue->addResir>>retryFinishDiscard->dounsafeIOToSTM$throwToparentFinishDiscardFinishSelect->doaddResirunsafeIOToSTM$throwToparentFinishDiscardn<-liftIO$CMC.block$don<-takeMVarcountputMVarcount(n+1)returnn-- !> ("SELECT" ++ show n)if(n==lengthactions)thenliftIO$throwToparentFinishDiscardelsereturn()`CMC.catch`(\(e::Select)->liftIO$throwToparente)ws<-mapM(\(ac,i)->fork$check'aci)$zipactions[0..]liftIO$putMVarchecThreadswsliftIO$atomically$dov<-readTVarflag-- wait fo timeoutcasevofFalse->retryTrue->return()throwFinishDiscardwhereaddResir=dol<-readTVarreswriteTVarres$lV.//[(i,Justr)]letkillall=liftIO$dows<-readMVarchecThreadsliftIO$mapM_killThreadwsliftIO$mapM_(\(ActionWF_th)->killThreadth)actions-- !> "KILLALL"step$CMC.catchprocess-- (WF $ \s -> process >>= \ r -> return (s, r))(\(e::Select)->doliftIO$return.catMaybes.V.toList=<<atomically(readTVarres))`CMC.finally`killalljustifystrNothing=errorstrjustify_(Justx)=returnx-- | spawn a list of workflows and reduces the results according with the 'comp' parameter within a given timeout---- @-- vote timeout actions comp x=-- split actions x >>= select timeout (const $ return Select) >>= comp-- @vote::(Serializeb-- , Serialize [b],Typeableb,HasForkio,CMC.MonadCatchIOio)=>Integer->[a->Workflowiob]->([b]->Workflowioc)->a->Workflowiocvotetimeoutactionscompx=splitactionsx>>=selecttimeout(const$returnContinue)>>=comp-- | sum the outputs of a list of workflows according with its monoid definition---- @ sumUp timeout actions = vote timeout actions (return . mconcat) @sumUp::(Serializeb-- , Serialize [b],Typeableb,Monoidb,HasForkio,CMC.MonadCatchIOio)=>Integer->[a->Workflowiob]->a->WorkflowiobsumUptimeoutactions=votetimeoutactions(return.mconcat)main=dosyncWriteSyncManualr<-exec1"sumup"$sumUp0[f1,f2]"0"printr`CMC.catch`\(e::SomeException)->syncCache-- !> "syncCache"f::Int->String->WorkflowIOStringfns=step(threadDelay(5000000*n))>>return(s++"1")main2=dosyncWriteSyncManualexec1"split"$split(take10$repeat(step.print))"hi">>=merge(const$returnTrue)main3=do-- syncWrite SyncManualrefs<-exec1"WFRef"$dorefs<-replicateM20$newWFRefNothing--"bye initial valoe"mapM(\r->fork$unsafeIOtoWF$atomically$writeWFRefr$Just"hi final value")refsreturnrefsmapM(\r->liftIO(atomically$readWFRef1r)>>=print)refs