forked from vijaygupta18/euler-hs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Language.hs
1123 lines (1035 loc) · 37.1 KB
/
Language.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs #-}
module EulerHS.Framework.Flow.Language
(
-- * Flow language
Flow(..)
, FlowMethod(..)
, MonadFlow(..)
, ReaderFlow
-- ** Extra methods
-- *** Logging
, logCallStack
, logExceptionCallStack
, logInfo
, logError
, logDebug
, logWarning
-- *** Other
, callAPI
, callAPI'
, callHTTP
, runIO
, forkFlow
, forkFlow'
-- *** PublishSubscribe
, unpackLanguagePubSub
-- ** Interpretation
, foldFlow
) where
import Control.Monad.Catch (ExitCase, MonadCatch (catch),
MonadThrow (throwM))
import Control.Monad.Free.Church (MonadFree)
import Control.Monad.Trans.RWS.Strict (RWST)
import Control.Monad.Trans.Writer (WriterT)
import qualified Data.Text as Text
import EulerHS.Core.Language (KVDB, Logger, logMessage')
import qualified EulerHS.Core.Language as L
import qualified EulerHS.Core.PubSub.Language as PSL
import qualified EulerHS.Core.Types as T
import EulerHS.Framework.Runtime (FlowRuntime)
import EulerHS.Prelude hiding (getOption, throwM)
import Servant.Client (BaseUrl, ClientError)
-- | Flow language.
data FlowMethod (next :: Type) where
CallServantAPI
:: HasCallStack
=> Maybe T.ManagerSelector
-> BaseUrl
-> T.EulerClient a
-> (Either ClientError a -> next)
-> FlowMethod next
CallHTTP
:: HasCallStack
=> T.HTTPRequest
-> Maybe T.HTTPCert
-> (Either Text T.HTTPResponse -> next)
-> FlowMethod next
EvalLogger
:: HasCallStack
=> Logger a
-> (a -> next)
-> FlowMethod next
RunIO
:: HasCallStack
=> Text
-> IO a
-> (a -> next)
-> FlowMethod next
GetOption
:: HasCallStack
=> Text
-> (Maybe a -> next)
-> FlowMethod next
SetOption
:: HasCallStack
=> Text
-> a
-> (() -> next)
-> FlowMethod next
DelOption
:: HasCallStack
=> Text
-> (() -> next)
-> FlowMethod next
GenerateGUID
:: HasCallStack
=> (Text -> next)
-> FlowMethod next
RunSysCmd
:: HasCallStack
=> String
-> (String -> next)
-> FlowMethod next
Fork
:: HasCallStack
=> T.Description
-> T.ForkGUID
-> Flow a
-> (T.Awaitable (Either Text a) -> next)
-> FlowMethod next
Await
:: HasCallStack
=> Maybe T.Microseconds
-> T.Awaitable (Either Text a)
-> (Either T.AwaitingError a -> next)
-> FlowMethod next
ThrowException
:: forall a e next
. (HasCallStack, Exception e)
=> e
-> (a -> next)
-> FlowMethod next
CatchException
:: forall a e next
. (HasCallStack, Exception e)
=> Flow a
-> (e -> Flow a)
-> (a -> next)
-> FlowMethod next
Mask
:: forall b next
. HasCallStack
=> ((forall a . Flow a -> Flow a) -> Flow b)
-> (b -> next)
-> FlowMethod next
UninterruptibleMask
:: forall b next
. HasCallStack
=> ((forall a . Flow a -> Flow a) -> Flow b)
-> (b -> next)
-> FlowMethod next
GeneralBracket
:: forall a b c next
. HasCallStack
=> Flow a
-> (a -> ExitCase b -> Flow c)
-> (a -> Flow b)
-> ((b, c) -> next)
-> FlowMethod next
-- This is technically redundant - we can implement this using something like
-- bracket, but better. - Koz
RunSafeFlow
:: HasCallStack
=> T.SafeFlowGUID
-> Flow a
-> (Either Text a -> next)
-> FlowMethod next
InitSqlDBConnection
:: HasCallStack
=> T.DBConfig beM
-> (T.DBResult (T.SqlConn beM) -> next)
-> FlowMethod next
DeInitSqlDBConnection
:: HasCallStack
=> T.SqlConn beM
-> (() -> next)
-> FlowMethod next
GetSqlDBConnection
:: HasCallStack
=> T.DBConfig beM
-> (T.DBResult (T.SqlConn beM) -> next)
-> FlowMethod next
InitKVDBConnection
:: HasCallStack
=> T.KVDBConfig
-> (T.KVDBAnswer T.KVDBConn -> next)
-> FlowMethod next
DeInitKVDBConnection
:: HasCallStack
=> T.KVDBConn
-> (() -> next)
-> FlowMethod next
GetKVDBConnection
:: HasCallStack
=> T.KVDBConfig
-> (T.KVDBAnswer T.KVDBConn -> next)
-> FlowMethod next
RunDB
:: HasCallStack
=> T.SqlConn beM
-> L.SqlDB beM a
-> Bool
-> (T.DBResult a -> next)
-> FlowMethod next
RunKVDB
:: HasCallStack
=> Text
-> KVDB a
-> (T.KVDBAnswer a -> next)
-> FlowMethod next
RunPubSub
:: HasCallStack
=> PubSub a
-> (a -> next)
-> FlowMethod next
WithModifiedRuntime
:: HasCallStack
=> (FlowRuntime -> FlowRuntime)
-> Flow a
-> (a -> next)
-> FlowMethod next
-- Needed due to lack of impredicative instantiation (for stuff like Mask). -
-- Koz
instance Functor FlowMethod where
{-# INLINEABLE fmap #-}
fmap f = \case
CallServantAPI mSel url client cont ->
CallServantAPI mSel url client (f . cont)
CallHTTP req cert cont -> CallHTTP req cert (f . cont)
EvalLogger logger cont -> EvalLogger logger (f . cont)
RunIO t act cont -> RunIO t act (f . cont)
GetOption k cont -> GetOption k (f . cont)
SetOption k v cont -> SetOption k v (f . cont)
DelOption k cont -> DelOption k (f . cont)
GenerateGUID cont -> GenerateGUID (f . cont)
RunSysCmd cmd cont -> RunSysCmd cmd (f . cont)
Fork desc guid flow cont -> Fork desc guid flow (f . cont)
Await time awaitable cont -> Await time awaitable (f . cont)
ThrowException e cont -> ThrowException e (f . cont)
CatchException flow handler cont -> CatchException flow handler (f . cont)
Mask cb cont -> Mask cb (f . cont)
UninterruptibleMask cb cont -> UninterruptibleMask cb (f . cont)
GeneralBracket acquire release act cont ->
GeneralBracket acquire release act (f . cont)
RunSafeFlow guid flow cont -> RunSafeFlow guid flow (f . cont)
InitSqlDBConnection conf cont -> InitSqlDBConnection conf (f . cont)
DeInitSqlDBConnection conn cont -> DeInitSqlDBConnection conn (f . cont)
GetSqlDBConnection conf cont -> GetSqlDBConnection conf (f . cont)
InitKVDBConnection conf cont -> InitKVDBConnection conf (f . cont)
DeInitKVDBConnection conn cont -> DeInitKVDBConnection conn (f . cont)
GetKVDBConnection conf cont -> GetKVDBConnection conf (f . cont)
RunDB conn db b cont -> RunDB conn db b (f . cont)
RunKVDB t db cont -> RunKVDB t db (f . cont)
RunPubSub pubSub cont -> RunPubSub pubSub (f . cont)
WithModifiedRuntime g innerFlow cont ->
WithModifiedRuntime g innerFlow (f . cont)
newtype Flow (a :: Type) = Flow (F FlowMethod a)
deriving newtype (Functor, Applicative, Monad, MonadFree FlowMethod)
instance MonadThrow Flow where
{-# INLINEABLE throwM #-}
throwM e = liftFC . ThrowException e $ id
instance MonadCatch Flow where
{-# INLINEABLE catch #-}
catch comp handler = liftFC . CatchException comp handler $ id
instance MonadMask Flow where
{-# INLINEABLE mask #-}
mask cb = liftFC . Mask cb $ id
{-# INLINEABLE uninterruptibleMask #-}
uninterruptibleMask cb = liftFC . UninterruptibleMask cb $ id
{-# INLINEABLE generalBracket #-}
generalBracket acquire release act =
liftFC . GeneralBracket acquire release act $ id
foldFlow :: (Monad m) => (forall b . FlowMethod b -> m b) -> Flow a -> m a
foldFlow f (Flow comp) = foldF f comp
type ReaderFlow r = ReaderT r Flow
newtype PubSub a = PubSub {
unpackLanguagePubSub :: HasCallStack => (forall b . Flow b -> IO b) -> PSL.PubSub a
}
type MessageCallback
= ByteString -- ^ Message payload
-> Flow ()
type PMessageCallback
= ByteString -- ^ Channel name
-> ByteString -- ^ Message payload
-> Flow ()
-- | Fork a unit-returning flow.
--
-- __Note__: to fork a flow which yields a value use 'forkFlow\'' instead.
--
-- __Warning__: With forked flows, race coniditions and dead / live blocking become possible.
-- All the rules applied to forked threads in Haskell can be applied to forked flows.
--
-- Generally, the method is thread safe. Doesn't do anything to bookkeep the threads.
-- There is no possibility to kill a thread at the moment.
--
-- Thread safe, exception free.
--
-- > myFlow1 = do
-- > logInfoT "myflow1" "logFromMyFlow1"
-- > someAction
-- >
-- > myFlow2 = do
-- > _ <- runIO someAction
-- > forkFlow "myFlow1 fork" myFlow1
-- > pure ()
--
forkFlow :: HasCallStack => T.Description -> Flow () -> Flow ()
forkFlow description flow = void $ forkFlow' description $ do
eitherResult <- runSafeFlow flow
case eitherResult of
Left msg -> logError ("forkFlow" :: Text) msg
Right _ -> pure ()
-- | Same as 'forkFlow', but takes @Flow a@ and returns an 'T.Awaitable' which can be used
-- to reap results from the flow being forked.
--
-- > myFlow1 = do
-- > logInfoT "myflow1" "logFromMyFlow1"
-- > pure 10
-- >
-- > myFlow2 = do
-- > awaitable <- forkFlow' "myFlow1 fork" myFlow1
-- > await Nothing awaitable
--
forkFlow' :: HasCallStack =>
T.Description -> Flow a -> Flow (T.Awaitable (Either Text a))
forkFlow' description flow = do
flowGUID <- generateGUID
logInfo ("ForkFlow" :: Text) $ case Text.uncons description of
Nothing ->
"Flow forked. Description: " +| description |+ " GUID: " +| flowGUID |+ ""
Just _ -> "Flow forked. GUID: " +| flowGUID |+ ""
liftFC $ Fork description flowGUID flow id
-- | Method for calling external HTTP APIs using the facilities of servant-client.
-- Allows to specify what manager should be used. If no manager found,
-- `HttpManagerNotFound` will be returne (as part of `ClientError.ConnectionError`).
--
-- Thread safe, exception free.
--
-- Alias for callServantAPI.
--
-- | Takes remote url, servant client for this endpoint
-- and returns either client error or result.
--
-- > data User = User { firstName :: String, lastName :: String , userGUID :: String}
-- > deriving (Generic, Show, Eq, ToJSON, FromJSON )
-- >
-- > data Book = Book { author :: String, name :: String }
-- > deriving (Generic, Show, Eq, ToJSON, FromJSON )
-- >
-- > type API = "user" :> Get '[JSON] User
-- > :<|> "book" :> Get '[JSON] Book
-- >
-- > api :: HasCallStack => Proxy API
-- > api = Proxy
-- >
-- > getUser :: HasCallStack => EulerClient User
-- > getBook :: HasCallStack => EulerClient Book
-- > (getUser :<|> getBook) = client api
-- >
-- > url = BaseUrl Http "localhost" port ""
-- >
-- >
-- > myFlow = do
-- > book <- callAPI url getBook
-- > user <- callAPI url getUser
callAPI' :: (HasCallStack, MonadFlow m) =>
Maybe T.ManagerSelector -> BaseUrl -> T.EulerClient a -> m (Either ClientError a)
callAPI' = callServantAPI
-- | The same as `callAPI'` but with default manager to be used.
callAPI :: (HasCallStack, MonadFlow m) =>
BaseUrl -> T.EulerClient a -> m (Either ClientError a)
callAPI = callServantAPI Nothing
-- | Log message with Info level.
--
-- Thread safe.
logInfo :: forall (tag :: Type) (m :: Type -> Type) .
(HasCallStack, MonadFlow m, Show tag) => tag -> T.Message -> m ()
logInfo tag msg = evalLogger' $ logMessage' T.Info tag msg
-- | Log message with Error level.
--
-- Thread safe.
logError :: forall (tag :: Type) (m :: Type -> Type) .
(HasCallStack, MonadFlow m, Show tag) => tag -> T.Message -> m ()
logError tag msg = do
logCallStack
evalLogger' $ logMessage' T.Error tag msg
-- | Log message with Debug level.
--
-- Thread safe.
logDebug :: forall (tag :: Type) (m :: Type -> Type) .
(HasCallStack, MonadFlow m, Show tag) => tag -> T.Message -> m ()
logDebug tag msg = evalLogger' $ logMessage' T.Debug tag msg
-- | Log message with Warning level.
--
-- Thread safe.
logWarning :: forall (tag :: Type) (m :: Type -> Type) .
(HasCallStack, MonadFlow m, Show tag) => tag -> T.Message -> m ()
logWarning tag msg = evalLogger' $ logMessage' T.Warning tag msg
-- | Run some IO operation, result should have 'ToJSONEx' instance (extended 'ToJSON'),
-- because we have to collect it in recordings for ART system.
--
-- Warning. This method is dangerous and should be used wisely.
--
-- > myFlow = do
-- > content <- runIO $ readFromFile file
-- > logDebugT "content id" $ extractContentId content
-- > pure content
runIO :: (HasCallStack, MonadFlow m) => IO a -> m a
runIO = runIO' ""
-- | The same as callHTTPWithCert but does not need certificate data.
--
-- Thread safe, exception free.
--
-- Takes remote url and returns either client error or result.
--
-- > myFlow = do
-- > book <- callHTTP url
callHTTP :: (HasCallStack, MonadFlow m) =>
T.HTTPRequest -> m (Either Text.Text T.HTTPResponse)
callHTTP url = callHTTPWithCert url Nothing
-- | MonadFlow implementation for the `Flow` Monad. This allows implementation of MonadFlow for
-- `ReaderT` and other monad transformers.
--
-- Omit `forkFlow` as this will break some monads like StateT (you can lift this manually if you
-- know what you're doing)
class (MonadMask m) => MonadFlow m where
-- | Method for calling external HTTP APIs using the facilities of servant-client.
-- Allows to specify what manager should be used. If no manager found,
-- `HttpManagerNotFound` will be returne (as part of `ClientError.ConnectionError`).
--
-- Thread safe, exception free.
--
-- Takes remote url, servant client for this endpoint
-- and returns either client error or result.
--
-- > data User = User { firstName :: String, lastName :: String , userGUID :: String}
-- > deriving (Generic, Show, Eq, ToJSON, FromJSON )
-- >
-- > data Book = Book { author :: String, name :: String }
-- > deriving (Generic, Show, Eq, ToJSON, FromJSON )
-- >
-- > type API = "user" :> Get '[JSON] User
-- > :<|> "book" :> Get '[JSON] Book
-- >
-- > api :: HasCallStack => Proxy API
-- > api = Proxy
-- >
-- > getUser :: HasCallStack => EulerClient User
-- > getBook :: HasCallStack => EulerClient Book
-- > (getUser :<|> getBook) = client api
-- >
-- > url = BaseUrl Http "localhost" port ""
-- >
-- >
-- > myFlow = do
-- > book <- callServantAPI url getBook
-- > user <- callServantAPI url getUser
callServantAPI
:: HasCallStack
=> Maybe T.ManagerSelector -- ^ name of the connection manager to be used
-> BaseUrl -- ^ remote url 'BaseUrl'
-> T.EulerClient a -- ^ servant client 'EulerClient'
-> m (Either ClientError a) -- ^ result
-- | Method for calling external HTTP APIs without bothering with types.
--
-- Thread safe, exception free.
--
-- Takes remote url, optional certificate data and returns either client error or result.
--
-- > myFlow = do
-- > book <- callHTTPWithCert url cert
callHTTPWithCert
:: HasCallStack
=> T.HTTPRequest -- ^ remote url 'Text'
-> Maybe T.HTTPCert -- ^ TLS certificate data
-> m (Either Text.Text T.HTTPResponse) -- ^ result
-- | Evaluates a logging action.
evalLogger' :: HasCallStack => Logger a -> m a
-- | The same as runIO, but accepts a description which will be written into the ART recordings
-- for better clarity.
--
-- Warning. This method is dangerous and should be used wisely.
--
-- > myFlow = do
-- > content <- runIO' "reading from file" $ readFromFile file
-- > logDebugT "content id" $ extractContentId content
-- > pure content
runIO' :: HasCallStack => Text -> IO a -> m a
-- | Gets stored a typed option by a typed key.
--
-- Thread safe, exception free.
getOption :: forall k v. (HasCallStack, T.OptionEntity k v) => k -> m (Maybe v)
-- Sets a typed option using a typed key (a mutable destructive operation)
--
-- Be aware that it's possible to overflow the runtime with options
-- created uncontrollably.
--
-- Also please keep in mind the options are runtime-bound and if you have
-- several API methods working with the same option key, you'll get a race.
--
-- Thread safe, exception free.
--
-- > data MerchantIdKey = MerchantIdKey
-- >
-- > instance OptionEntity MerchantIdKey Text
-- >
-- > myFlow = do
-- > _ <- setOption MerchantIdKey "abc1234567"
-- > mKey <- getOption MerchantIdKey
-- > runIO $ putTextLn mKey
-- > delOption MerchantIdKey
setOption :: forall k v. (HasCallStack, T.OptionEntity k v) => k -> v -> m ()
-- | Deletes a typed option using a typed key.
delOption :: forall k v. (HasCallStack, T.OptionEntity k v) => k -> m ()
-- | Generate a version 4 UUIDs as specified in RFC 4122
-- e.g. 25A8FC2A-98F2-4B86-98F6-84324AF28611.
--
-- Thread safe, exception free.
generateGUID :: HasCallStack => m Text
-- | Runs system command and returns its output.
--
-- Warning. This method is dangerous and should be used wisely.
--
-- > myFlow = do
-- > currentDir <- runSysCmd "pwd"
-- > logInfoT "currentDir" $ toText currentDir
-- > ...
runSysCmd :: HasCallStack => String -> m String
-- | Inits an SQL connection using a config.
--
-- Returns an error (Left $ T.DBError T.ConnectionAlreadyExists msg)
-- if the connection already exists for this config.
--
-- Thread safe, exception free.
initSqlDBConnection :: HasCallStack => T.DBConfig beM -> m (T.DBResult (T.SqlConn beM))
-- | Deinits an SQL connection.
-- Does nothing if the connection is not found (might have been closed earlier).
--
-- Thread safe, exception free.
deinitSqlDBConnection :: HasCallStack => T.SqlConn beM -> m ()
-- | Gets the existing connection.
--
-- Returns an error (Left $ T.DBError T.ConnectionDoesNotExist)
-- if the connection does not exist.
--
-- Thread safe, exception free.
getSqlDBConnection :: HasCallStack => T.DBConfig beM -> m (T.DBResult (T.SqlConn beM))
-- | Inits a KV DB connection using a config.
--
-- Returns an error (Left $ KVDBError KVDBConnectionAlreadyExists msg)
-- if the connection already exists.
--
-- Thread safe, exception free.
initKVDBConnection :: HasCallStack => T.KVDBConfig -> m (T.KVDBAnswer T.KVDBConn)
-- | Deinits the given KV DB connection.
-- Does nothing if the connection is not found (might have been closed earlier).
--
-- Thread safe, exception free.
deinitKVDBConnection :: HasCallStack => T.KVDBConn -> m ()
-- | Get the existing connection.
-- Returns an error (Left $ KVDBError KVDBConnectionDoesNotExist)
-- if the connection does not exits for this config.
--
-- Thread safe, exception free.
getKVDBConnection :: HasCallStack => T.KVDBConfig -> m (T.KVDBAnswer T.KVDBConn)
-- | Evaluates SQL DB operations outside of any transaction.
-- It's possible to have a chain of SQL DB calls (within the SqlDB language).
-- These chains will be executed as a single transaction.
--
-- Thread safe, exception free.
--
-- The underlying library is beam which allows to access 3 different SQL backends.
-- See TUTORIAL.md, README.md and QueryExamplesSpec.hs for more info.
--
-- > myFlow :: HasCallStack => L.Flow (T.DBResult (Maybe User))
-- > myFlow = do
-- > connection <- L.initSqlDBConnection postgresCfg
-- >
-- > res <- L.runDB connection $ do
-- > let predicate1 User {..} = _userFirstName ==. B.val_ "John"
-- >
-- > L.updateRows $ B.update (_users eulerDb)
-- > (\User {..} -> mconcat
-- > [ _userFirstName <-. B.val_ "Leo"
-- > , _userLastName <-. B.val_ "San"
-- > ]
-- > )
-- > predicate1
-- >
-- > let predicate2 User {..} = _userFirstName ==. B.val_ "Leo"
-- > L.findRow
-- > $ B.select
-- > $ B.limit_ 1
-- > $ B.filter_ predicate2
-- > $ B.all_ (_users eulerDb)
-- >
-- > L.deinitSqlDBConnection connection
-- > pure res
runDB
::
( HasCallStack
, T.BeamRunner beM
, T.BeamRuntime be beM
)
=> T.SqlConn beM
-> L.SqlDB beM a
-> m (T.DBResult a)
-- | Like `runDB` but runs inside a SQL transaction.
runTransaction
::
( HasCallStack
, T.BeamRunner beM
, T.BeamRuntime be beM
)
=> T.SqlConn beM
-> L.SqlDB beM a
-> m (T.DBResult a)
-- | Await for some a result from the flow.
-- If the timeout is Nothing than the operation is blocking.
-- If the timeout is set then the internal mechanism tries to do several (10) checks for the result.
-- Can return earlier if the result became available.
-- Returns either an Awaiting error or a result.
--
-- Warning. There are no guarantees of a proper thread delaying here.
--
-- Thread safe, exception free.
--
-- | mbMcs == Nothing: infinite awaiting.
-- | mbMcs == Just (Microseconds n): await for approximately n seconds.
-- Awaiting may succeed ealier.
--
-- > myFlow1 = do
-- > logInfoT "myflow1" "logFromMyFlow1"
-- > pure 10
-- >
-- > myFlow2 = do
-- > awaitable <- forkFlow' "myFlow1 fork" myFlow1
-- > await Nothing awaitable
await
:: HasCallStack
=> Maybe T.Microseconds
-> T.Awaitable (Either Text a)
-> m (Either T.AwaitingError a)
-- | Throw a given exception.
--
-- It's possible to catch this exception using runSafeFlow method.
--
-- Thread safe. Exception throwing.
--
-- > myFlow = do
-- > res <- authAction
-- > case res of
-- > Failure reason -> throwException err403 {errBody = reason}
-- > Success -> ...
throwException :: forall a e. (HasCallStack, Exception e) => e -> m a
throwException ex = do
-- Doubt: Should we just print the exception details without the
-- contextual details that logError prints. As finding the message inside logError is a bit
-- cumbersome. Just printing the exception details will be much cleaner if we don't need the
-- contextual details.
logExceptionCallStack ex
throwExceptionWithoutCallStack ex
throwExceptionWithoutCallStack :: forall a e. (HasCallStack, Exception e) => e -> m a
throwExceptionWithoutCallStack = throwM
-- | Run a flow safely with catching all the exceptions from it.
-- Returns either a result or the exception turned into a text message.
--
-- This includes ususal instances of the Exception type class,
-- `error` exception and custom user exceptions thrown by the `throwException` method.
--
-- Thread safe, exception free.
--
-- > myFlow = runSafeFlow $ throwException err403 {errBody = reason}
--
-- > myFlow = do
-- > eitherContent <- runSafeFlow $ runIO $ readFromFile file
-- > case eitherContent of
-- > Left err -> ...
-- > Right content -> ...
runSafeFlow :: HasCallStack => Flow a -> m (Either Text a)
-- | Execute kvdb actions.
--
-- Thread safe, exception free.
--
-- > myFlow = do
-- > kvres <- L.runKVDB $ do
-- > set "aaa" "bbb"
-- > res <- get "aaa"
-- > del ["aaa"]
-- > pure res
runKVDB
:: HasCallStack
=> Text
-> KVDB a -- ^ KVDB action
-> m (T.KVDBAnswer a)
---- Experimental Pub Sub implementation using Redis Pub Sub.
runPubSub
:: HasCallStack
=> PubSub a
-> m a
-- | Publish payload to channel.
publish
:: HasCallStack
=> PSL.Channel -- ^ Channel in which payload will be send
-> PSL.Payload -- ^ Payload
-> m (Either T.KVDBReply Integer) -- ^ Number of subscribers received payload
-- | Subscribe to all channels from list.
-- Note: Subscription won't be unsubscribed automatically on thread end.
-- Use canceller explicitly to cancel subscription
subscribe
:: HasCallStack
=> [PSL.Channel] -- ^ List of channels to subscribe
-> MessageCallback -- ^ Callback function.
-> m (Flow ()) -- ^ Inner flow is a canceller of current subscription
-- | Subscribe to all channels from list. Respects redis pattern syntax.
-- Note: Subscription won't be unsubscribed automatically on thread end.
-- Use canceller explicitly to cancel subscription
psubscribe
:: HasCallStack
=> [PSL.ChannelPattern] -- ^ List of channels to subscribe (wit respect to patterns supported by redis)
-> PMessageCallback -- ^ Callback function
-> m (Flow ()) -- ^ Inner flow is a canceller of current subscription
-- | Run a flow with a modified runtime. The runtime will be restored after
-- the computation finishes.
--
-- @since 2.0.3.1
withModifiedRuntime
:: (HasCallStack, MonadFlow m)
=> (FlowRuntime -> FlowRuntime) -- ^ Temporary modification function for runtime
-> Flow a -- ^ Computation to run with modified runtime
-> m a
instance MonadFlow Flow where
{-# INLINEABLE callServantAPI #-}
callServantAPI mbMgrSel url cl = liftFC $ CallServantAPI mbMgrSel url cl id
{-# INLINEABLE callHTTPWithCert #-}
callHTTPWithCert url cert = liftFC $ CallHTTP url cert id
{-# INLINEABLE evalLogger' #-}
evalLogger' logAct = liftFC $ EvalLogger logAct id
{-# INLINEABLE runIO' #-}
runIO' descr ioAct = liftFC $ RunIO descr ioAct id
{-# INLINEABLE getOption #-}
getOption :: forall k v. (HasCallStack, T.OptionEntity k v) => k -> Flow (Maybe v)
getOption k = liftFC $ GetOption (T.mkOptionKey @k @v k) id
{-# INLINEABLE setOption #-}
setOption :: forall k v. (HasCallStack, T.OptionEntity k v) => k -> v -> Flow ()
setOption k v = liftFC $ SetOption (T.mkOptionKey @k @v k) v id
{-# INLINEABLE delOption #-}
delOption :: forall k v. (HasCallStack, T.OptionEntity k v) => k -> Flow ()
delOption k = liftFC $ DelOption (T.mkOptionKey @k @v k) id
{-# INLINEABLE generateGUID #-}
generateGUID = liftFC $ GenerateGUID id
{-# INLINEABLE runSysCmd #-}
runSysCmd cmd = liftFC $ RunSysCmd cmd id
{-# INLINEABLE initSqlDBConnection #-}
initSqlDBConnection cfg = liftFC $ InitSqlDBConnection cfg id
{-# INLINEABLE deinitSqlDBConnection #-}
deinitSqlDBConnection conn = liftFC $ DeInitSqlDBConnection conn id
{-# INLINEABLE getSqlDBConnection #-}
getSqlDBConnection cfg = liftFC $ GetSqlDBConnection cfg id
{-# INLINEABLE initKVDBConnection #-}
initKVDBConnection cfg = liftFC $ InitKVDBConnection cfg id
{-# INLINEABLE deinitKVDBConnection #-}
deinitKVDBConnection conn = liftFC $ DeInitKVDBConnection conn id
{-# INLINEABLE getKVDBConnection #-}
getKVDBConnection cfg = liftFC $ GetKVDBConnection cfg id
{-# INLINEABLE runDB #-}
runDB conn dbAct = liftFC $ RunDB conn dbAct False id
{-# INLINEABLE runTransaction #-}
runTransaction conn dbAct = liftFC $ RunDB conn dbAct True id
{-# INLINEABLE await #-}
await mbMcs awaitable = liftFC $ Await mbMcs awaitable id
{-# INLINEABLE runSafeFlow #-}
runSafeFlow flow = do
safeFlowGUID <- generateGUID
liftFC $ RunSafeFlow safeFlowGUID flow id
{-# INLINEABLE runKVDB #-}
runKVDB cName act = liftFC $ RunKVDB cName act id
{-# INLINEABLE runPubSub #-}
runPubSub act = liftFC $ RunPubSub act id
{-# INLINEABLE publish #-}
publish channel payload = runPubSub $ PubSub $ const $ PSL.publish channel payload
{-# INLINEABLE subscribe #-}
subscribe channels cb = fmap (runIO' "subscribe") $
runPubSub $ PubSub $ \runFlow -> PSL.subscribe channels (runFlow . cb)
{-# INLINEABLE psubscribe #-}
psubscribe channels cb = fmap (runIO' "psubscribe") $
runPubSub $ PubSub $ \runFlow -> PSL.psubscribe channels (\ch -> runFlow . cb ch)
{-# INLINEABLE withModifiedRuntime #-}
withModifiedRuntime f flow = liftFC $ WithModifiedRuntime f flow id
instance MonadFlow m => MonadFlow (ReaderT r m) where
{-# INLINEABLE callServantAPI #-}
callServantAPI mbMgrSel url = lift . callServantAPI mbMgrSel url
{-# INLINEABLE callHTTPWithCert #-}
callHTTPWithCert url = lift . callHTTPWithCert url
{-# INLINEABLE evalLogger' #-}
evalLogger' = lift . evalLogger'
{-# INLINEABLE runIO' #-}
runIO' descr = lift . runIO' descr
{-# INLINEABLE getOption #-}
getOption = lift . getOption
{-# INLINEABLE setOption #-}
setOption k = lift . setOption k
{-# INLINEABLE delOption #-}
delOption = lift . delOption
{-# INLINEABLE generateGUID #-}
generateGUID = lift generateGUID
{-# INLINEABLE runSysCmd #-}
runSysCmd = lift . runSysCmd
{-# INLINEABLE initSqlDBConnection #-}
initSqlDBConnection = lift . initSqlDBConnection
{-# INLINEABLE deinitSqlDBConnection #-}
deinitSqlDBConnection = lift . deinitSqlDBConnection
{-# INLINEABLE getSqlDBConnection #-}
getSqlDBConnection = lift . getSqlDBConnection
{-# INLINEABLE initKVDBConnection #-}
initKVDBConnection = lift . initKVDBConnection
{-# INLINEABLE deinitKVDBConnection #-}
deinitKVDBConnection = lift . deinitKVDBConnection
{-# INLINEABLE getKVDBConnection #-}
getKVDBConnection = lift . getKVDBConnection
{-# INLINEABLE runDB #-}
runDB conn = lift . runDB conn
{-# INLINEABLE runTransaction #-}
runTransaction conn = lift . runTransaction conn
{-# INLINEABLE await #-}
await mbMcs = lift . await mbMcs
{-# INLINEABLE runSafeFlow #-}
runSafeFlow = lift . runSafeFlow
{-# INLINEABLE runKVDB #-}
runKVDB cName = lift . runKVDB cName
{-# INLINEABLE runPubSub #-}
runPubSub = lift . runPubSub
{-# INLINEABLE publish #-}
publish channel = lift . publish channel
{-# INLINEABLE subscribe #-}
subscribe channels = lift . subscribe channels
{-# INLINEABLE psubscribe #-}
psubscribe channels = lift . psubscribe channels
{-# INLINEABLE withModifiedRuntime #-}
withModifiedRuntime f = lift . withModifiedRuntime f
instance MonadFlow m => MonadFlow (StateT s m) where
{-# INLINEABLE callServantAPI #-}
callServantAPI mbMgrSel url = lift . callServantAPI mbMgrSel url
{-# INLINEABLE callHTTPWithCert #-}
callHTTPWithCert url = lift . callHTTPWithCert url
{-# INLINEABLE evalLogger' #-}
evalLogger' = lift . evalLogger'
{-# INLINEABLE runIO' #-}
runIO' descr = lift . runIO' descr
{-# INLINEABLE getOption #-}
getOption = lift . getOption
{-# INLINEABLE setOption #-}
setOption k = lift . setOption k
{-# INLINEABLE delOption #-}
delOption = lift . delOption
{-# INLINEABLE generateGUID #-}
generateGUID = lift generateGUID
{-# INLINEABLE runSysCmd #-}
runSysCmd = lift . runSysCmd
{-# INLINEABLE initSqlDBConnection #-}
initSqlDBConnection = lift . initSqlDBConnection
{-# INLINEABLE deinitSqlDBConnection #-}
deinitSqlDBConnection = lift . deinitSqlDBConnection
{-# INLINEABLE getSqlDBConnection #-}
getSqlDBConnection = lift . getSqlDBConnection
{-# INLINEABLE initKVDBConnection #-}
initKVDBConnection = lift . initKVDBConnection
{-# INLINEABLE deinitKVDBConnection #-}
deinitKVDBConnection = lift . deinitKVDBConnection
{-# INLINEABLE getKVDBConnection #-}
getKVDBConnection = lift . getKVDBConnection
{-# INLINEABLE runDB #-}
runDB conn = lift . runDB conn
{-# INLINEABLE runTransaction #-}
runTransaction conn = lift . runTransaction conn
{-# INLINEABLE await #-}
await mbMcs = lift . await mbMcs
{-# INLINEABLE runSafeFlow #-}
runSafeFlow = lift . runSafeFlow
{-# INLINEABLE runKVDB #-}
runKVDB cName = lift . runKVDB cName
{-# INLINEABLE runPubSub #-}
runPubSub = lift . runPubSub
{-# INLINEABLE publish #-}
publish channel = lift . publish channel
{-# INLINEABLE subscribe #-}
subscribe channels = lift . subscribe channels
{-# INLINEABLE psubscribe #-}
psubscribe channels = lift . psubscribe channels
{-# INLINEABLE withModifiedRuntime #-}
withModifiedRuntime f = lift . withModifiedRuntime f
instance (MonadFlow m, Monoid w) => MonadFlow (WriterT w m) where
{-# INLINEABLE callServantAPI #-}
callServantAPI mbMgrSel url = lift . callServantAPI mbMgrSel url
{-# INLINEABLE callHTTPWithCert #-}
callHTTPWithCert url = lift . callHTTPWithCert url
{-# INLINEABLE evalLogger' #-}
evalLogger' = lift . evalLogger'
{-# INLINEABLE runIO' #-}
runIO' descr = lift . runIO' descr
{-# INLINEABLE getOption #-}
getOption = lift . getOption
{-# INLINEABLE setOption #-}
setOption k = lift . setOption k
{-# INLINEABLE delOption #-}
delOption = lift . delOption
{-# INLINEABLE generateGUID #-}
generateGUID = lift generateGUID
{-# INLINEABLE runSysCmd #-}
runSysCmd = lift . runSysCmd
{-# INLINEABLE initSqlDBConnection #-}
initSqlDBConnection = lift . initSqlDBConnection
{-# INLINEABLE deinitSqlDBConnection #-}
deinitSqlDBConnection = lift . deinitSqlDBConnection
{-# INLINEABLE getSqlDBConnection #-}
getSqlDBConnection = lift . getSqlDBConnection
{-# INLINEABLE initKVDBConnection #-}
initKVDBConnection = lift . initKVDBConnection
{-# INLINEABLE deinitKVDBConnection #-}
deinitKVDBConnection = lift . deinitKVDBConnection
{-# INLINEABLE getKVDBConnection #-}
getKVDBConnection = lift . getKVDBConnection
{-# INLINEABLE runDB #-}
runDB conn = lift . runDB conn
{-# INLINEABLE runTransaction #-}
runTransaction conn = lift . runTransaction conn
{-# INLINEABLE await #-}
await mbMcs = lift . await mbMcs
{-# INLINEABLE runSafeFlow #-}
runSafeFlow = lift . runSafeFlow
{-# INLINEABLE runKVDB #-}
runKVDB cName = lift . runKVDB cName
{-# INLINEABLE runPubSub #-}
runPubSub = lift . runPubSub
{-# INLINEABLE publish #-}