-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
App.hs
1545 lines (1393 loc) · 58.9 KB
/
App.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 QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
-- | Defines the CE version of the engine.
--
-- This module contains everything that is required to run the community edition
-- of the engine: the base application monad and the implementation of all its
-- behaviour classes.
module Hasura.App
( -- * top-level error handling
ExitCode (..),
ExitException (..),
throwErrExit,
throwErrJExit,
accessDeniedErrMsg,
-- * printing helpers
printJSON,
-- * logging
mkLoggers,
mkPGLogger,
-- * basic connection info
BasicConnectionInfo (..),
initMetadataConnectionInfo,
initBasicConnectionInfo,
resolvePostgresConnInfo,
-- * app init
initialiseAppEnv,
initialiseAppContext,
migrateCatalogAndFetchMetadata,
buildFirstSchemaCache,
initSubscriptionsState,
initLockedEventsCtx,
-- * app monad
AppM,
runAppM,
-- * misc
getCatalogStateTx,
updateJwkCtxThread,
notifySchemaCacheSyncTx,
parseArgs,
runHGEServer,
setCatalogStateTx,
mkHGEServer,
mkPgSourceResolver,
mkMSSQLSourceResolver,
)
where
import Control.Concurrent.Async.Lifted.Safe qualified as LA
import Control.Concurrent.Extended (sleep)
import Control.Concurrent.Extended qualified as C
import Control.Concurrent.STM
import Control.Concurrent.STM qualified as STM
import Control.Exception (bracket_, throwIO)
import Control.Monad.Catch
( Exception,
MonadCatch,
MonadMask,
MonadThrow,
)
import Control.Monad.Morph (hoist)
import Control.Monad.Stateless
import Control.Monad.Trans.Control (MonadBaseControl (..))
import Control.Monad.Trans.Managed (ManagedT (..), allocate, allocate_)
import Control.Retry qualified as Retry
import Data.Aeson qualified as J
import Data.ByteString.Char8 qualified as BC
import Data.ByteString.Lazy qualified as BL
import Data.ByteString.Lazy.Char8 qualified as BLC
import Data.Environment qualified as Env
import Data.FileEmbed (makeRelativeToProject)
import Data.HashMap.Strict qualified as HashMap
import Data.Set.NonEmpty qualified as NE
import Data.Text qualified as T
import Data.Time.Clock (UTCTime)
import Data.Time.Clock qualified as Clock
import Database.MSSQL.Pool qualified as MSPool
import Database.PG.Query qualified as PG
import Database.PG.Query qualified as Q
import GHC.AssertNF.CPP
import Hasura.App.State
import Hasura.Authentication.Role (adminRoleName)
import Hasura.Authentication.User (ExtraUserInfo (..), UserInfo (..))
import Hasura.Backends.MSSQL.Connection
import Hasura.Backends.Postgres.Connection
import Hasura.Base.Error
import Hasura.ClientCredentials (getEEClientCredentialsTx, setEEClientCredentialsTx)
import Hasura.Eventing.Backend
import Hasura.Eventing.Common
import Hasura.Eventing.EventTrigger
import Hasura.Eventing.ScheduledTrigger
import Hasura.GraphQL.Execute
( ExecutionStep (..),
MonadGQLExecutionCheck (..),
checkQueryInAllowlist,
)
import Hasura.GraphQL.Execute.Action
import Hasura.GraphQL.Execute.Action.Subscription
import Hasura.GraphQL.Execute.Subscription.Poll qualified as ES
import Hasura.GraphQL.Execute.Subscription.State qualified as ES
import Hasura.GraphQL.Logging (MonadExecutionLog (..), MonadQueryLog (..))
import Hasura.GraphQL.Transport.HTTP
( CacheResult (..),
MonadExecuteQuery (..),
)
import Hasura.GraphQL.Transport.HTTP.Protocol (toParsed)
import Hasura.GraphQL.Transport.WSServerApp qualified as WS
import Hasura.GraphQL.Transport.WebSocket.Server qualified as WS
import Hasura.GraphQL.Transport.WebSocket.Types (WSServerEnv (..))
import Hasura.Logging
import Hasura.Metadata.Class
import Hasura.NativeQuery.Validation (DisableNativeQueryValidation)
import Hasura.PingSources
import Hasura.Prelude
import Hasura.QueryTags
import Hasura.RQL.DDL.EventTrigger (MonadEventLogCleanup (..))
import Hasura.RQL.DDL.Schema.Cache
import Hasura.RQL.DDL.Schema.Cache.Common
import Hasura.RQL.DDL.Schema.Cache.Config
import Hasura.RQL.DDL.Schema.Catalog
import Hasura.RQL.DDL.SchemaRegistry qualified as SchemaRegistry
import Hasura.RQL.Types.Allowlist
import Hasura.RQL.Types.Backend
import Hasura.RQL.Types.BackendType
import Hasura.RQL.Types.Common
import Hasura.RQL.Types.Metadata
import Hasura.RQL.Types.ResizePool
import Hasura.RQL.Types.SchemaCache
import Hasura.RQL.Types.SchemaCache.Build
import Hasura.RQL.Types.Source
import Hasura.SQL.AnyBackend qualified as AB
import Hasura.Server.API.Query (requiresAdmin)
import Hasura.Server.App
import Hasura.Server.AppStateRef
import Hasura.Server.Auth
import Hasura.Server.CheckUpdates (checkForUpdates)
import Hasura.Server.Init
import Hasura.Server.Limits
import Hasura.Server.Logging
import Hasura.Server.Metrics (ServerMetrics (..))
import Hasura.Server.Migrate (migrateCatalog)
import Hasura.Server.Prometheus
( PrometheusMetrics (..),
decWarpThreads,
incWarpThreads,
)
import Hasura.Server.ResourceChecker (getServerResources)
import Hasura.Server.SchemaUpdate
import Hasura.Server.Telemetry
import Hasura.Server.Types
import Hasura.Server.Version
import Hasura.Services
import Hasura.ShutdownLatch
import Hasura.Tracing
import Network.HTTP.Client qualified as HTTP
import Network.HTTP.Client.CreateManager (mkHttpManager)
import Network.Types.Extended
import Network.Wai (Application)
import Network.Wai.Handler.Warp qualified as Warp
import Options.Applicative
import Refined (unrefine)
import System.Metrics qualified as EKG
import System.Metrics.Gauge qualified as EKG.Gauge
import Text.Mustache.Compile qualified as M
import Web.Spock.Core qualified as Spock
--------------------------------------------------------------------------------
-- Error handling (move to another module!)
data ExitCode
= -- these are used during server initialization:
InvalidEnvironmentVariableOptionsError
| InvalidDatabaseConnectionParamsError
| AuthConfigurationError
| DatabaseMigrationError
| -- | used by MT because it initialises the schema cache only
-- these are used in app/Main.hs:
SchemaCacheInitError
| MetadataExportError
| MetadataCleanError
| DowngradeProcessError
deriving (Show)
data ExitException = ExitException
{ eeCode :: !ExitCode,
eeMessage :: !BC.ByteString
}
deriving (Show)
instance Exception ExitException
throwErrExit :: (MonadIO m) => forall a. ExitCode -> String -> m a
throwErrExit reason = liftIO . throwIO . ExitException reason . BC.pack
throwErrJExit :: (J.ToJSON a, MonadIO m) => forall b. ExitCode -> a -> m b
throwErrJExit reason = liftIO . throwIO . ExitException reason . BLC.toStrict . J.encode
accessDeniedErrMsg :: Text
accessDeniedErrMsg = "restricted access : admin only"
--------------------------------------------------------------------------------
-- Printing helpers (move to another module!)
printJSON :: (J.ToJSON a, MonadIO m) => a -> m ()
printJSON = liftIO . BLC.putStrLn . J.encode
--------------------------------------------------------------------------------
-- Logging
mkPGLogger :: Logger Hasura -> PG.PGLogger
mkPGLogger (Logger logger) (PG.PLERetryMsg msg) = logger $ PGLog LevelWarn msg
-- | Create all loggers based on the set of enabled logs and chosen log level.
mkLoggers ::
(MonadIO m, MonadBaseControl IO m) =>
HashSet (EngineLogType Hasura) ->
LogLevel ->
ManagedT m Loggers
mkLoggers enabledLogs logLevel = do
loggerCtx <- mkLoggerCtx (defaultLoggerSettings True logLevel) enabledLogs
let logger = mkLogger loggerCtx
pgLogger = mkPGLogger logger
pure $ Loggers loggerCtx logger pgLogger
--------------------------------------------------------------------------------
-- Basic connection info
-- | Basic information required to connect to the metadata DB, and to the
-- default Postgres DB if any.
data BasicConnectionInfo = BasicConnectionInfo
{ -- | metadata db connection info
bciMetadataConnInfo :: PG.ConnInfo,
-- | default postgres connection info, if any
bciDefaultPostgres :: Maybe PostgresConnConfiguration
}
-- | Only create the metadata connection info.
--
-- Like 'initBasicConnectionInfo', it prioritizes @--metadata-database-url@, and
-- falls back to @--database-url@ otherwise.
--
-- !!! This function throws a fatal error if the @--database-url@ cannot be
-- !!! resolved.
initMetadataConnectionInfo ::
(MonadIO m) =>
Env.Environment ->
-- | metadata DB URL (--metadata-database-url)
Maybe String ->
-- | user's DB URL (--database-url)
PostgresConnInfo (Maybe UrlConf) ->
m PG.ConnInfo
initMetadataConnectionInfo env metadataDbURL dbURL =
fmap bciMetadataConnInfo
$ initBasicConnectionInfo
env
metadataDbURL
dbURL
Nothing -- ignored
False -- ignored
PG.ReadCommitted -- ignored
-- | Create a 'BasicConnectionInfo' based on the given options.
--
-- The default postgres connection is only created when the @--database-url@
-- option is given. If the @--metadata-database-url@ isn't given, the
-- @--database-url@ will be used for the metadata connection.
--
-- All arguments related to the default postgres connection are ignored if the
-- @--database-url@ is missing.
--
-- !!! This function throws a fatal error if the @--database-url@ cannot be
-- !!! resolved.
initBasicConnectionInfo ::
(MonadIO m) =>
Env.Environment ->
-- | metadata DB URL (--metadata-database-url). This is expected to be either
-- a postgres connection string URI, or our own @dynamic-from-file@ URI,
-- corresponding to the dynamic_from_file feature when connecting a postgres
-- data source.
Maybe String ->
-- | user's DB URL (--database-url)
PostgresConnInfo (Maybe UrlConf) ->
-- | pool settings of the default PG connection
Maybe PostgresPoolSettings ->
-- | whether the default PG config should use prepared statements
Bool ->
-- | default transaction isolation level
PG.TxIsolation ->
m BasicConnectionInfo
initBasicConnectionInfo
env
metadataDbUrl
(PostgresConnInfo dbUrlConf maybeRetries)
poolSettings
usePreparedStatements
isolationLevel =
case (metadataDbUrl, dbUrlConf) of
(Nothing, Nothing) ->
throwErrExit
InvalidDatabaseConnectionParamsError
"Fatal Error: Either of --metadata-database-url or --database-url option expected"
-- If no metadata storage specified consider use default database as
-- metadata storage
(Nothing, Just srcURL) -> do
srcConnInfo <- resolvePostgresConnInfo env srcURL maybeRetries
pure $ BasicConnectionInfo srcConnInfo (Just $ mkSourceConfig srcURL)
(Just mdURL, Nothing) ->
pure $ BasicConnectionInfo (mkConnInfoFromMDB mdURL) Nothing
(Just mdURL, Just srcURL) -> do
_srcConnInfo <- resolvePostgresConnInfo env srcURL maybeRetries
pure $ BasicConnectionInfo (mkConnInfoFromMDB mdURL) (Just $ mkSourceConfig srcURL)
where
-- Our own made up URI scheme corresponding to the dynamic_from_file feature
-- NOTE: Since this can only be set by the administrator, there's no need
-- to validate against something like HASURA_GRAPHQL_DYNAMIC_SECRETS_ALLOWED_PATH_PREFIX
dynamicScheme = "dynamic-from-file://"
mkConnInfoFromMDB mdbURL =
PG.ConnInfo
{ PG.ciRetries = fromMaybe 1 maybeRetries,
PG.ciDetails = case splitAt (length dynamicScheme) mdbURL of
(mbDynamicScheme, mbPath)
| mbDynamicScheme == dynamicScheme ->
PG.CDDynamicDatabaseURI mbPath
_ -> PG.CDDatabaseURI $ txtToBs $ T.pack mdbURL
}
mkSourceConfig srcURL =
PostgresConnConfiguration
{ pccConnectionInfo =
PostgresSourceConnInfo
{ psciDatabaseUrl = srcURL,
psciPoolSettings = poolSettings,
psciUsePreparedStatements = usePreparedStatements,
psciIsolationLevel = isolationLevel,
psciSslConfiguration = Nothing
},
pccReadReplicas = Nothing,
pccExtensionsSchema = defaultPostgresExtensionsSchema,
pccConnectionTemplate = Nothing,
pccConnectionSet = mempty
}
-- | Creates a 'PG.ConnInfo' from a 'UrlConf' parameter.
--
-- !!! throws a fatal error if the configuration is invalid
resolvePostgresConnInfo ::
(MonadIO m) =>
Env.Environment ->
UrlConf ->
Maybe Int ->
m PG.ConnInfo
resolvePostgresConnInfo env dbUrlConf (fromMaybe 1 -> retries) = do
connDetails <-
runExceptT (resolveUrlConf env dbUrlConf)
>>= either (liftIO . throwErrJExit InvalidDatabaseConnectionParamsError) pure
pure $ PG.ConnInfo retries connDetails
--------------------------------------------------------------------------------
-- App init
-- | The initialisation of the app is split into several functions, for clarity;
-- but there are several pieces of information that need to be threaded across
-- those initialisation functions. This small data structure groups together all
-- such pieces of information that are required throughout the initialisation,
-- but that aren't needed in the rest of the application.
data AppInit = AppInit
{ aiTLSAllowListRef :: TLSAllowListRef,
aiMetadataWithResourceVersion :: MetadataWithResourceVersion
}
-- | Initializes or migrates the catalog and creates the 'AppEnv' required to
-- start the server, and also create the 'AppInit' that needs to be threaded
-- along the init code.
--
-- For historical reasons, this function performs a few additional startup tasks
-- that are not required to create the 'AppEnv', such as starting background
-- processes and logging startup information. All of those are flagged with a
-- comment marking them as a side-effect.
--
-- NOTE: this is invoked in pro, but only for OSS mode (no license key)
initialiseAppEnv ::
(C.ForkableMonadIO m) =>
Env.Environment ->
BasicConnectionInfo ->
ServeOptions Hasura ->
Maybe ES.SubscriptionPostPollHook ->
ServerMetrics ->
PrometheusMetrics ->
SamplingPolicy ->
ManagedT m (AppInit, AppEnv)
initialiseAppEnv env BasicConnectionInfo {..} serveOptions@ServeOptions {..} liveQueryHook serverMetrics prometheusMetrics traceSamplingPolicy = do
loggers@(Loggers _loggerCtx logger pgLogger) <- mkLoggers soEnabledLogTypes soLogLevel
-- SIDE EFFECT: print a warning if no admin secret is set.
when (null soAdminSecret)
$ unLogger
logger
StartupLog
{ slLogLevel = LevelWarn,
slKind = "no_admin_secret",
slInfo = J.toJSON ("WARNING: No admin secret provided" :: Text)
}
-- SIDE EFFECT: log all server options.
unLogger logger $ serveOptsToLog serveOptions
-- SIDE EFFECT: log metadata postgres connection info.
unLogger logger $ connInfoToLog bciMetadataConnInfo
-- Generate the instance id.
instanceId <- liftIO generateInstanceId
let connectionContext :: J.Value
connectionContext = J.object ["source" J..= J.String "metadata"]
-- Init metadata db pool.
metadataDbPool <-
allocate
(liftIO $ PG.initPGPool bciMetadataConnInfo connectionContext soConnParams pgLogger)
(liftIO . PG.destroyPGPool)
-- Migrate the catalog and fetch the metdata.
metadataWithVersion <-
lift
$ migrateCatalogAndFetchMetadata
logger
metadataDbPool
bciDefaultPostgres
soEnableMaintenanceMode
soExtensionsSchema
-- Create the TLSAllowListRef and the HTTP Manager.
let metadata = _mwrvMetadata metadataWithVersion
tlsAllowListRef <- liftIO $ createTLSAllowListRef $ networkTlsAllowlist $ _metaNetwork metadata
httpManager <- liftIO $ mkHttpManager (readTLSAllowList tlsAllowListRef) mempty
-- Start a background thread for listening schema sync events from other
-- server instances (an interval of 0 indicates that no schema sync is
-- required). Logs whether the thread is started or not, and with what
-- interval.
-- TODO: extract into a separate init function.
metaVersionRef <- liftIO $ STM.newEmptyTMVarIO
case soSchemaPollInterval of
Skip -> unLogger logger $ mkGenericLog @Text LevelInfo "schema-sync" "Schema sync disabled"
Interval interval -> do
unLogger logger $ mkGenericLog @String LevelInfo "schema-sync" ("Schema sync enabled. Polling at " <> show interval)
void $ startSchemaSyncListenerThread logger metadataDbPool instanceId interval metaVersionRef
-- Generate the shutdown latch.
latch <- liftIO newShutdownLatch
-- Generate subscription state.
subscriptionsState <- liftIO $ initSubscriptionsState logger liveQueryHook
-- Generate event's trigger shared state
lockedEventsCtx <- liftIO $ initLockedEventsCtx
pure
( AppInit
{ aiTLSAllowListRef = tlsAllowListRef,
aiMetadataWithResourceVersion = metadataWithVersion
},
AppEnv
{ appEnvPort = soPort,
appEnvHost = soHost,
appEnvMetadataDbPool = metadataDbPool,
appEnvIntrospectionDbPool = Nothing, -- No introspection storage for self-hosted CE
appEnvManager = httpManager,
appEnvLoggers = loggers,
appEnvMetadataVersionRef = metaVersionRef,
appEnvInstanceId = instanceId,
appEnvEnableMaintenanceMode = soEnableMaintenanceMode,
appEnvLoggingSettings = LoggingSettings soEnabledLogTypes soEnableMetadataQueryLogging soHttpLogQueryOnlyOnError,
appEnvEventingMode = soEventingMode,
appEnvEnableReadOnlyMode = soReadOnlyMode,
appEnvServerMetrics = serverMetrics,
appEnvShutdownLatch = latch,
appEnvMetaVersionRef = metaVersionRef,
appEnvPrometheusMetrics = prometheusMetrics,
appEnvTraceSamplingPolicy = traceSamplingPolicy,
appEnvSubscriptionState = subscriptionsState,
appEnvLockedEventsCtx = lockedEventsCtx,
appEnvConnParams = soConnParams,
appEnvTxIso = soTxIso,
appEnvConsoleAssetsDir = soConsoleAssetsDir,
appEnvConsoleSentryDsn = soConsoleSentryDsn,
appEnvConnectionOptions = soConnectionOptions,
appEnvWebSocketKeepAlive = soWebSocketKeepAlive,
appEnvWebSocketConnectionInitTimeout = soWebSocketConnectionInitTimeout,
appEnvGracefulShutdownTimeout = soGracefulShutdownTimeout,
appEnvCheckFeatureFlag = ceCheckFeatureFlag env,
appEnvSchemaPollInterval = soSchemaPollInterval,
appEnvLicenseKeyCache = Nothing,
appEnvMaxTotalHeaderLength = soMaxTotalHeaderLength,
appEnvTriggersErrorLogLevelStatus = soTriggersErrorLogLevelStatus,
appEnvAsyncActionsFetchBatchSize = soAsyncActionsFetchBatchSize,
appEnvPersistedQueries = soPersistedQueries,
appEnvPersistedQueriesTtl = soPersistedQueriesTtl
}
)
-- | Initializes the 'AppContext' and returns a corresponding 'AppStateRef'.
--
-- This function is meant to be run in the app monad, which provides the
-- 'AppEnv'.
initialiseAppContext ::
(C.ForkableMonadIO m, HasAppEnv m) =>
Env.Environment ->
ServeOptions Hasura ->
AppInit ->
m (AppStateRef Hasura)
initialiseAppContext env serveOptions AppInit {..} = do
appEnv@AppEnv {..} <- askAppEnv
let cacheStaticConfig = buildCacheStaticConfig appEnv
Loggers _ logger pgLogger = appEnvLoggers
-- Build the RebuildableAppContext.
-- (See note [Hasura Application State].)
rebuildableAppCtxE <-
liftIO
$ runExceptT
( buildRebuildableAppContext
(logger, appEnvManager)
serveOptions
appEnvCheckFeatureFlag
env
)
!rebuildableAppCtx <- onLeft rebuildableAppCtxE $ \e -> throwErrExit InvalidEnvironmentVariableOptionsError $ T.unpack $ qeError e
let cacheDynamicConfig = buildCacheDynamicConfig (lastBuiltAppContext rebuildableAppCtx)
-- Create the schema cache
rebuildableSchemaCache <-
buildFirstSchemaCache
(soDisableNativeQueryValidation serveOptions)
env
logger
(mkPgSourceResolver pgLogger)
mkMSSQLSourceResolver
aiMetadataWithResourceVersion
cacheStaticConfig
cacheDynamicConfig
appEnvManager
Nothing
-- Initialise the 'AppStateRef' from 'RebuildableSchemaCacheRef' and 'RebuildableAppContext'.
initialiseAppStateRef aiTLSAllowListRef Nothing appEnvServerMetrics rebuildableSchemaCache rebuildableAppCtx
-- | Runs catalogue migration, and returns the metadata that was fetched.
--
-- On success, this function logs the result of the migration, on failure it
-- logs a 'catalog_migrate' error and throws a fatal error.
migrateCatalogAndFetchMetadata ::
(MonadIO m, MonadBaseControl IO m) =>
Logger Hasura ->
PG.PGPool ->
Maybe (SourceConnConfiguration ('Postgres 'Vanilla)) ->
MaintenanceMode () ->
ExtensionsSchema ->
m MetadataWithResourceVersion
migrateCatalogAndFetchMetadata
logger
pool
defaultSourceConfig
maintenanceMode
extensionsSchema = do
-- TODO: should we allow the migration to happen during maintenance mode?
-- Allowing this can be a sanity check, to see if the hdb_catalog in the
-- DB has been set correctly
currentTime <- liftIO Clock.getCurrentTime
result <-
runExceptT
$ PG.runTx pool (PG.Serializable, Just PG.ReadWrite)
$ migrateCatalog
defaultSourceConfig
extensionsSchema
maintenanceMode
currentTime
case result of
Left err -> do
unLogger
logger
StartupLog
{ slLogLevel = LevelError,
slKind = "catalog_migrate",
slInfo = J.toJSON err
}
liftIO (throwErrJExit DatabaseMigrationError err)
Right (migrationResult, metadataWithVersion) -> do
unLogger logger migrationResult
pure metadataWithVersion
-- | Build the original 'RebuildableSchemaCache'.
--
-- On error, it logs a 'catalog_migrate' error and throws a fatal error. This
-- misnomer is intentional: it is to preserve a previous behaviour of the code
-- and avoid a breaking change.
buildFirstSchemaCache ::
(MonadIO m) =>
DisableNativeQueryValidation ->
Env.Environment ->
Logger Hasura ->
SourceResolver ('Postgres 'Vanilla) ->
SourceResolver ('MSSQL) ->
MetadataWithResourceVersion ->
CacheStaticConfig ->
CacheDynamicConfig ->
HTTP.Manager ->
Maybe SchemaRegistry.SchemaRegistryContext ->
m RebuildableSchemaCache
buildFirstSchemaCache
disableNativeQueryValidation
env
logger
pgSourceResolver
mssqlSourceResolver
metadataWithVersion
cacheStaticConfig
cacheDynamicConfig
httpManager
mSchemaRegistryContext = do
let cacheBuildParams = CacheBuildParams httpManager pgSourceResolver mssqlSourceResolver cacheStaticConfig
result <-
runExceptT
$ runCacheBuild cacheBuildParams
$ buildRebuildableSchemaCache logger env disableNativeQueryValidation metadataWithVersion cacheDynamicConfig mSchemaRegistryContext
result `onLeft` \err -> do
-- TODO: we used to bundle the first schema cache build with the catalog
-- migration, using the same error handler for both, meaning that an
-- error in the first schema cache build would be reported as
-- follows. Changing this will be a breaking change.
unLogger
logger
StartupLog
{ slLogLevel = LevelError,
slKind = "catalog_migrate",
slInfo = J.toJSON err
}
liftIO (throwErrJExit DatabaseMigrationError err)
initSubscriptionsState ::
Logger Hasura ->
Maybe ES.SubscriptionPostPollHook ->
IO ES.SubscriptionsState
initSubscriptionsState logger liveQueryHook = ES.initSubscriptionsState postPollHook
where
postPollHook = fromMaybe (ES.defaultSubscriptionPostPollHook logger) liveQueryHook
initLockedEventsCtx :: IO LockedEventsCtx
initLockedEventsCtx =
liftM4
LockedEventsCtx
(STM.newTVarIO mempty)
(STM.newTVarIO mempty)
(STM.newTVarIO mempty)
(STM.newTVarIO mempty)
--------------------------------------------------------------------------------
-- App monad
-- | The base app monad of the CE engine.
newtype AppM a = AppM (ReaderT AppEnv (TraceT IO) a)
deriving newtype
( Functor,
MonadFail, -- only due to https://gitlab.haskell.org/ghc/ghc/-/issues/15681
Applicative,
Monad,
MonadIO,
MonadFix,
MonadCatch,
MonadThrow,
MonadMask,
MonadReader AppEnv,
MonadBase IO,
MonadBaseControl IO
)
runAppM :: AppEnv -> AppM a -> IO a
runAppM c (AppM a) = ignoreTraceT $ runReaderT a c
instance HasAppEnv AppM where
askAppEnv = ask
instance HasFeatureFlagChecker AppM where
checkFlag f = AppM do
CheckFeatureFlag {runCheckFeatureFlag} <- asks appEnvCheckFeatureFlag
liftIO $ runCheckFeatureFlag f
instance HasCacheStaticConfig AppM where
askCacheStaticConfig = buildCacheStaticConfig <$> askAppEnv
instance MonadTrace AppM where
newTraceWith c p n (AppM a) = AppM $ newTraceWith c p n a
newSpanWith i n k (AppM a) = AppM $ newSpanWith i n k a
attachMetadata = AppM . attachMetadata
instance MonadTraceContext AppM where
currentContext = AppM currentContext
instance ProvidesNetwork AppM where
askHTTPManager = asks appEnvManager
instance HasResourceLimits AppM where
askHTTPHandlerLimit = pure $ ResourceLimits id
askGraphqlOperationLimit _ _ _ = pure $ ResourceLimits id
instance HttpLog AppM where
type ExtraHttpLogMetadata AppM = ()
emptyExtraHttpLogMetadata = ()
buildExtraHttpLogMetadata _ _ = ()
logHttpError logger loggingSettings userInfoM reqId waiReq req qErr qTime cType headers _ _ =
unLoggerTracing logger
$ mkHttpLog
$ mkHttpErrorLogContext userInfoM loggingSettings reqId waiReq req qErr qTime cType headers
logHttpSuccess logger loggingSettings userInfoM reqId waiReq reqBody response compressedResponse qTime cType headers (CommonHttpLogMetadata rb batchQueryOpLogs, ()) _ =
unLoggerTracing logger
$ mkHttpLog
$ mkHttpAccessLogContext userInfoM loggingSettings reqId waiReq reqBody (BL.length response) compressedResponse qTime cType headers rb batchQueryOpLogs
instance MonadExecuteQuery AppM where
cacheLookup _ _ _ _ _ _ = pure $ Right ([], ResponseUncached Nothing)
instance UserAuthentication AppM where
resolveUserInfo logger manager headers authMode reqs =
runExceptT $ do
(a, b, c) <- getUserInfoWithExpTime logger manager headers authMode reqs
pure $ (a, b, c, ExtraUserInfo Nothing)
instance MonadMetadataApiAuthorization AppM where
authorizeV1QueryApi query handlerCtx = runExceptT do
let currRole = _uiRole $ hcUser handlerCtx
when (requiresAdmin query && currRole /= adminRoleName)
$ withPathK "args"
$ throw400 AccessDenied accessDeniedErrMsg
authorizeV1MetadataApi _ handlerCtx = runExceptT do
let currRole = _uiRole $ hcUser handlerCtx
when (currRole /= adminRoleName)
$ withPathK "args"
$ throw400 AccessDenied accessDeniedErrMsg
authorizeV2QueryApi _ handlerCtx = runExceptT do
let currRole = _uiRole $ hcUser handlerCtx
when (currRole /= adminRoleName)
$ withPathK "args"
$ throw400 AccessDenied accessDeniedErrMsg
instance ConsoleRenderer AppM where
type ConsoleType AppM = CEConsoleType
renderConsole path authMode enableTelemetry consoleAssetsDir consoleSentryDsn consoleType =
return $ mkConsoleHTML path authMode enableTelemetry consoleAssetsDir consoleSentryDsn consoleType
instance MonadVersionAPIWithExtraData AppM where
-- we always default to CE as the `server_type` in this codebase
getExtraDataForVersionAPI = return ["server_type" J..= ("ce" :: Text)]
instance MonadGQLExecutionCheck AppM where
checkGQLExecution userInfo _ enableAL sc query _ = runExceptT $ do
req <- toParsed query
checkQueryInAllowlist enableAL AllowlistModeGlobalOnly userInfo req sc
return req
executeIntrospection _ introspectionQuery _ =
pure $ Right $ ExecStepRaw introspectionQuery
checkGQLBatchedReqs _ _ _ _ = runExceptT $ pure ()
instance MonadConfigApiHandler AppM where
runConfigApiHandler = configApiGetHandler
instance MonadGQLApiHandler AppM where
runPersistedQueriesGetHandler _ _ _ = throw400 NotSupported "PersistedQueryNotSupported"
runPersistedQueriesPostHandler _ _ query =
case query of
EqrGQLReq gqlReq -> v1GQHandler gqlReq
EqrAPQReq _ -> throw400 NotSupported "PersistedQueryNotSupported"
instance MonadQueryLog AppM where
logQueryLog logger = unLoggerTracing logger
instance MonadExecutionLog AppM where
logExecutionLog logger = unLoggerTracing logger
instance WS.MonadWSLog AppM where
logWSLog logger = unLoggerTracing logger
instance MonadResolveSource AppM where
getPGSourceResolver = asks (mkPgSourceResolver . _lsPgLogger . appEnvLoggers)
getMSSQLSourceResolver = return mkMSSQLSourceResolver
instance MonadQueryTags AppM where
createQueryTags _attributes _qtSourceConfig = return $ emptyQueryTagsComment
instance MonadEventLogCleanup AppM where
runLogCleaner _ _ = pure $ throw400 NotSupported "Event log cleanup feature is enterprise edition only"
generateCleanupSchedules _ _ _ = pure $ Right ()
updateTriggerCleanupSchedules _ _ _ _ = pure $ Right ()
instance MonadGetPolicies AppM where
runGetApiTimeLimit = pure $ Nothing
runGetPrometheusMetricsGranularity = pure (pure GranularMetricsOff)
runGetModelInfoLogStatus = pure (pure ModelInfoLogOff)
-- | Each of the function in the type class is executed in a totally separate transaction.
instance MonadMetadataStorage AppM where
fetchMetadataResourceVersion = runInSeparateTx fetchMetadataResourceVersionFromCatalog
fetchMetadata = runInSeparateTx fetchMetadataAndResourceVersionFromCatalog
fetchMetadataNotifications a b = runInSeparateTx $ fetchMetadataNotificationsFromCatalog a b
getCatalogState = runInSeparateTx getCatalogStateTx
setCatalogState a b = runInSeparateTx $ setCatalogStateTx a b
updateMetadataAndNotifySchemaSync instanceId resourceVersion metadata cacheInvalidations =
runInSeparateTx $ do
newResourceVersion <- setMetadataInCatalog resourceVersion metadata
notifySchemaCacheSyncTx newResourceVersion instanceId cacheInvalidations
pure newResourceVersion
-- stored source introspection is not available in this distribution
fetchSourceIntrospection _ = pure $ Right Nothing
storeSourceIntrospection _ _ = pure $ Right ()
getMetadataDbUid = runInSeparateTx getDbId
checkMetadataStorageHealth = runInSeparateTx $ checkDbConnection
getDeprivedCronTriggerStats = runInSeparateTx . getDeprivedCronTriggerStatsTx
getScheduledEventsForDelivery = runInSeparateTx . getScheduledEventsForDeliveryTx
insertCronEvents = runInSeparateTx . insertCronEventsTx
insertOneOffScheduledEvent = runInSeparateTx . insertOneOffScheduledEventTx
insertScheduledEventInvocation a b = runInSeparateTx $ insertInvocationTx a b
setScheduledEventOp a b c = runInSeparateTx $ setScheduledEventOpTx a b c
unlockScheduledEvents a b = runInSeparateTx $ unlockScheduledEventsTx a b
unlockAllLockedScheduledEvents = runInSeparateTx unlockAllLockedScheduledEventsTx
clearFutureCronEvents = runInSeparateTx . dropFutureCronEventsTx
getOneOffScheduledEvents a b c = runInSeparateTx $ getOneOffScheduledEventsTx a b c
getCronEvents a b c d = runInSeparateTx $ getCronEventsTx a b c d
getScheduledEventInvocations a = runInSeparateTx $ getScheduledEventInvocationsTx a
deleteScheduledEvent a b = runInSeparateTx $ deleteScheduledEventTx a b
insertAction a b c d = runInSeparateTx $ insertActionTx a b c d
fetchUndeliveredActionEvents a = runInSeparateTx $ fetchUndeliveredActionEventsTx a
setActionStatus a b = runInSeparateTx $ setActionStatusTx a b
fetchActionResponse = runInSeparateTx . fetchActionResponseTx
clearActionData = runInSeparateTx . clearActionDataTx
setProcessingActionLogsToPending = runInSeparateTx . setProcessingActionLogsToPendingTx
instance MonadEECredentialsStorage AppM where
getEEClientCredentials = runInSeparateTx getEEClientCredentialsTx
setEEClientCredentials a = runInSeparateTx $ setEEClientCredentialsTx a
--------------------------------------------------------------------------------
-- misc
-- TODO(SOLOMON): Move Into `Hasura.Server.Init`. Unable to do so
-- currently due `throwErrExit`.
-- | Parse cli arguments to graphql-engine executable.
parseArgs :: (EnabledLogTypes impl) => Env.Environment -> IO (HGEOptions (ServeOptions impl))
parseArgs env = do
rawHGEOpts <- execParser opts
let eitherOpts = runWithEnv (Env.toList env) $ mkHGEOptions rawHGEOpts
onLeft eitherOpts $ throwErrExit InvalidEnvironmentVariableOptionsError
where
opts =
info
(helper <*> parseHgeOpts)
( fullDesc
<> header "Hasura GraphQL Engine: Blazing fast, instant realtime GraphQL APIs on your DB with fine grained access control, also trigger webhooks on database events."
<> footerDoc (Just mainCmdFooter)
)
-- | Core logic to fork a poller thread to update the JWK based on the
-- expiry time specified in @Expires@ header or @Cache-Control@ header
updateJwkCtxThread ::
(C.ForkableMonadIO m) =>
IO AppContext ->
HTTP.Manager ->
Logger Hasura ->
m Void
updateJwkCtxThread getAppCtx httpManager logger = do
let sleepSeconds = 60
forever $ do
authMode <- liftIO $ acAuthMode <$> getAppCtx
updateJwkCtx
(ContextAdvice $ "retrying again after " <> tshow sleepSeconds <> " seconds")
authMode
httpManager
logger
liftIO $ sleep $ seconds sleepSeconds
-- | Event triggers live in the user's DB and other events
-- (cron, one-off and async actions)
-- live in the metadata DB, so we need a way to differentiate the
-- type of shutdown action
data ShutdownAction
= EventTriggerShutdownAction (IO ())
| MetadataDBShutdownAction (ExceptT QErr IO ())
-- | This function acts as the entrypoint for the graphql-engine webserver.
--
-- Note: at the exit of this function, or in case of a graceful server shutdown
-- (SIGTERM, or more generally, whenever the shutdown latch is set), we need to
-- make absolutely sure that we clean up any resources which were allocated during
-- server setup. In the case of a multitenant process, failure to do so can lead to
-- resource leaks.
--
-- To track these resources, we use the ManagedT monad, and attach finalizers at
-- the same point in the code where we allocate resources. If you fork a new
-- long-lived thread, or create a connection pool, or allocate any other
-- long-lived resource, make sure to pair the allocator with its finalizer.
-- There are plenty of examples throughout the code. For example, see
-- 'C.forkManagedT'.
--
-- Note also: the order in which the finalizers run can be important. Specifically,
-- we want the finalizers for the logger threads to run last, so that we retain as
-- many "thread stopping" log messages as possible. The order in which the
-- finalizers is run is determined by the order in which they are introduced in the
-- code.
{- HLINT ignore runHGEServer "Avoid lambda" -}
{- HLINT ignore runHGEServer "Use withAsync" -}
runHGEServer ::
forall m impl.
( MonadIO m,
MonadFail m, -- only due to https://gitlab.haskell.org/ghc/ghc/-/issues/15681
MonadFix m,
MonadMask m,
MonadStateless IO m,
LA.Forall (LA.Pure m),
UserAuthentication m,
HttpLog m,
HasAppEnv m,
HasCacheStaticConfig m,
ConsoleRenderer m,
MonadVersionAPIWithExtraData m,
MonadMetadataApiAuthorization m,
MonadGQLExecutionCheck m,
MonadConfigApiHandler m,
MonadQueryLog m,
MonadExecutionLog m,
WS.MonadWSLog m,
MonadExecuteQuery m,
HasResourceLimits m,
MonadMetadataStorage m,
MonadResolveSource m,
MonadQueryTags m,
MonadEventLogCleanup m,
ProvidesHasuraServices m,
MonadTrace m,
MonadGetPolicies m,
MonadGQLApiHandler m
) =>
(AppStateRef impl -> Spock.SpockT m ()) ->
AppStateRef impl ->
-- | start time
UTCTime ->
-- | A hook which can be called to indicate when the server is started succesfully
Maybe (IO ()) ->
ConsoleType m ->
EKG.Store EKG.EmptyMetrics ->
ManagedT m ()
runHGEServer setupHook appStateRef initTime startupStatusHook consoleType ekgStore = do
AppEnv {..} <- lift askAppEnv
waiApplication <- mkHGEServer setupHook appStateRef consoleType ekgStore
let logger = _lsLogger appEnvLoggers
-- `startupStatusHook`: add `Service started successfully` message to config_status
-- table when a tenant starts up in multitenant
let warpSettings :: Warp.Settings
warpSettings =
Warp.setPort (_getPort appEnvPort)
. Warp.setHost appEnvHost
. Warp.setGracefulShutdownTimeout (Just 30) -- 30s graceful shutdown
. Warp.setInstallShutdownHandler shutdownHandler
. Warp.setBeforeMainLoop (for_ startupStatusHook id)
. Warp.setServerName ""
. setForkIOWithMetrics
. Warp.setMaxTotalHeaderLength appEnvMaxTotalHeaderLength
$ Warp.defaultSettings
setForkIOWithMetrics :: Warp.Settings -> Warp.Settings
setForkIOWithMetrics = Warp.setFork \f -> do
void
$ C.forkIOWithUnmask
( \unmask -> do
labelMe "runHGEServer_warp_fork"
bracket_
( do
EKG.Gauge.inc (smWarpThreads appEnvServerMetrics)
incWarpThreads (pmConnections appEnvPrometheusMetrics)