mirror of
https://github.com/hasura/graphql-engine.git
synced 2024-12-18 13:02:11 +03:00
a01d1188f2
The main aim of the PR is: 1. To set up a module structure for 'remote-schemas' package. 2. Move parts by the remote schema codebase into the new module structure to validate it. ## Notes to the reviewer Why a PR with large-ish diff? 1. We've been making progress on the MM project but we don't yet know long it is going to take us to get to the first milestone. To understand this better, we need to figure out the unknowns as soon as possible. Hence I've taken a stab at the first two items in the [end-state](https://gist.github.com/0x777/ca2bdc4284d21c3eec153b51dea255c9) document to figure out the unknowns. Unsurprisingly, there are a bunch of issues that we haven't discussed earlier. These are documented in the 'open questions' section. 1. The diff is large but that is only code moved around and I've added a section that documents how things are moved. In addition, there are fair number of PR comments to help with the review process. ## Changes in the PR ### Module structure Sets up the module structure as follows: ``` Hasura/ RemoteSchema/ Metadata/ Types.hs SchemaCache/ Types.hs Permission.hs RemoteRelationship.hs Build.hs MetadataAPI/ Types.hs Execute.hs ``` ### 1. Types representing metadata are moved Types that capture metadata information (currently scattered across several RQL modules) are moved into `Hasura.RemoteSchema.Metadata.Types`. - This new module only depends on very 'core' modules such as `Hasura.Session` for the notion of roles and `Hasura.Incremental` for `Cacheable` typeclass. - The requirement on database modules is avoided by generalizing the remote schemas metadata to accept an arbitrary 'r' for a remote relationship definition. ### 2. SchemaCache related types and build logic have been moved Types that represent remote schemas information in SchemaCache are moved into `Hasura.RemoteSchema.SchemaCache.Types`. Similar to `H.RS.Metadata.Types`, this module depends on 'core' modules except for `Hasura.GraphQL.Parser.Variable`. It has something to do with remote relationships but I haven't spent time looking into it. The validation of 'remote relationships to remote schema' is also something that needs to be looked at. Rips out the logic that builds remote schema's SchemaCache information from the monolithic `buildSchemaCacheRule` and moves it into `Hasura.RemoteSchema.SchemaCache.Build`. Further, the `.SchemaCache.Permission` and `.SchemaCache.RemoteRelationship` have been created from existing modules that capture schema cache building logic for those two components. This was a fair amount of work. On main, currently remote schema's SchemaCache information is built in two phases - in the first phase, 'permissions' and 'remote relationships' are ignored and in the second phase they are filled in. While remote relationships can only be resolved after partially resolving sources and other remote schemas, the same isn't true for permissions. Further, most of the work that is done to resolve remote relationships can be moved to the first phase so that the second phase can be a very simple traversal. This is the approach that was taken - resolve permissions and as much as remote relationships information in the first phase. ### 3. Metadata APIs related types and build logic have been moved The types that represent remote schema related metadata APIs and the execution logic have been moved to `Hasura.RemoteSchema.MetadataAPI.Types` and `.Execute` modules respectively. ## Open questions: 1. `Hasura.RemoteSchema.Metadata.Types` is so called because I was hoping that all of the metadata related APIs of remote schema can be brought in at `Hasura.RemoteSchema.Metadata.API`. However, as metadata APIs depended on functions from `SchemaCache` module (see [1](ceba6d6226/server/src-lib/Hasura/RQL/DDL/RemoteSchema.hs (L55)
) and [2](ceba6d6226/server/src-lib/Hasura/RQL/DDL/RemoteSchema.hs (L91)
), it made more sense to create a separate top-level module for `MetadataAPI`s. Maybe we can just have `Hasura.RemoteSchema.Metadata` and get rid of the extra nesting or have `Hasura.RemoteSchema.Metadata.{Core,Permission,RemoteRelationship}` if we want to break them down further. 1. `buildRemoteSchemas` in `H.RS.SchemaCache.Build` has the following type: ```haskell buildRemoteSchemas :: ( ArrowChoice arr, Inc.ArrowDistribute arr, ArrowWriter (Seq CollectedInfo) arr, Inc.ArrowCache m arr, MonadIO m, HasHttpManagerM m, Inc.Cacheable remoteRelationshipDefinition, ToJSON remoteRelationshipDefinition, MonadError QErr m ) => Env.Environment -> ( (Inc.Dependency (HashMap RemoteSchemaName Inc.InvalidationKey), OrderedRoles), [RemoteSchemaMetadataG remoteRelationshipDefinition] ) `arr` HashMap RemoteSchemaName (PartiallyResolvedRemoteSchemaCtxG remoteRelationshipDefinition, MetadataObject) ``` Note the dependence on `CollectedInfo` which is defined as ```haskell data CollectedInfo = CIInconsistency InconsistentMetadata | CIDependency MetadataObject -- ^ for error reporting on missing dependencies SchemaObjId SchemaDependency deriving (Eq) ``` this pretty much means that remote schemas is dependent on types from databases, actions, .... How do we fix this? Maybe introduce a typeclass such as `ArrowCollectRemoteSchemaDependencies` which is defined in `Hasura.RemoteSchema` and then implemented in graphql-engine? 1. The dependency on `buildSchemaCacheFor` in `.MetadataAPI.Execute` which has the following signature: ```haskell buildSchemaCacheFor :: (QErrM m, CacheRWM m, MetadataM m) => MetadataObjId -> MetadataModifier -> ``` This can be easily resolved if we restrict what the metadata APIs are allowed to do. Currently, they operate in an unfettered access to modify SchemaCache (the `CacheRWM` constraint): ```haskell runAddRemoteSchema :: ( QErrM m, CacheRWM m, MonadIO m, HasHttpManagerM m, MetadataM m, Tracing.MonadTrace m ) => Env.Environment -> AddRemoteSchemaQuery -> m EncJSON ``` This should instead be changed to restrict remote schema APIs to only modify remote schema metadata (but has access to the remote schemas part of the schema cache), this dependency is completely removed. ```haskell runAddRemoteSchema :: ( QErrM m, MonadIO m, HasHttpManagerM m, MonadReader RemoteSchemasSchemaCache m, MonadState RemoteSchemaMetadata m, Tracing.MonadTrace m ) => Env.Environment -> AddRemoteSchemaQuery -> m RemoteSchemeMetadataObjId ``` The idea is that the core graphql-engine would call these functions and then call `buildSchemaCacheFor`. PR-URL: https://github.com/hasura/graphql-engine-mono/pull/6291 GitOrigin-RevId: 51357148c6404afe70219afa71bd1d59bdf4ffc6
302 lines
11 KiB
Haskell
302 lines
11 KiB
Haskell
module Hasura.GraphQL.Execute.Backend
|
|
( BackendExecute (..),
|
|
DBStepInfo (..),
|
|
ExecutionPlan,
|
|
ExecutionStep (..),
|
|
ExplainPlan (..),
|
|
MonadQueryTags (..),
|
|
convertRemoteSourceRelationship,
|
|
)
|
|
where
|
|
|
|
import Control.Monad.Trans.Control (MonadBaseControl)
|
|
import Data.Aeson qualified as J
|
|
import Data.Aeson.Casing qualified as J
|
|
import Data.Aeson.Ordered qualified as JO
|
|
import Data.Environment as Env
|
|
import Data.Kind (Type)
|
|
import Data.Tagged
|
|
import Data.Text.Extended
|
|
import Data.Text.NonEmpty (mkNonEmptyTextUnsafe)
|
|
import Database.PG.Query qualified as PG
|
|
import Hasura.Base.Error
|
|
import Hasura.EncJSON
|
|
import Hasura.GraphQL.Execute.Action.Types (ActionExecutionPlan)
|
|
import Hasura.GraphQL.Execute.RemoteJoin.Types
|
|
import Hasura.GraphQL.Execute.Subscription.Plan
|
|
import Hasura.GraphQL.Namespace (RootFieldAlias, RootFieldMap)
|
|
import Hasura.GraphQL.Schema.Options qualified as Options
|
|
import Hasura.GraphQL.Transport.HTTP.Protocol qualified as GH
|
|
import Hasura.Metadata.Class
|
|
import Hasura.Prelude
|
|
import Hasura.QueryTags
|
|
import Hasura.RQL.DDL.Schema.Cache (CacheRWT)
|
|
import Hasura.RQL.IR
|
|
import Hasura.RQL.Types.Action
|
|
import Hasura.RQL.Types.Backend
|
|
import Hasura.RQL.Types.Column (ColumnType, fromCol)
|
|
import Hasura.RQL.Types.Common
|
|
import Hasura.RQL.Types.QueryTags (QueryTagsConfig)
|
|
import Hasura.RQL.Types.ResultCustomization
|
|
import Hasura.RQL.Types.Run (RunT (..))
|
|
import Hasura.RQL.Types.SchemaCache.Build (MetadataT (..))
|
|
import Hasura.RemoteSchema.SchemaCache
|
|
import Hasura.SQL.AnyBackend qualified as AB
|
|
import Hasura.SQL.Backend
|
|
import Hasura.Session
|
|
import Hasura.Tracing (TraceT)
|
|
import Language.GraphQL.Draft.Syntax qualified as G
|
|
import Network.HTTP.Types qualified as HTTP
|
|
|
|
-- | This typeclass enacapsulates how a given backend translates a root field into an execution
|
|
-- plan. For now, each root field maps to one execution step, but in the future, when we have
|
|
-- a client-side dataloader, each root field might translate into a multi-step plan.
|
|
class
|
|
( Backend b,
|
|
ToTxt (MultiplexedQuery b),
|
|
Monad (ExecutionMonad b)
|
|
) =>
|
|
BackendExecute (b :: BackendType)
|
|
where
|
|
-- generated query information
|
|
type PreparedQuery b :: Type
|
|
type MultiplexedQuery b :: Type
|
|
type ExecutionMonad b :: Type -> Type
|
|
|
|
-- execution plan generation
|
|
mkDBQueryPlan ::
|
|
forall m.
|
|
( MonadError QErr m,
|
|
MonadQueryTags m,
|
|
MonadReader QueryTagsComment m
|
|
) =>
|
|
UserInfo ->
|
|
Env.Environment ->
|
|
SourceName ->
|
|
SourceConfig b ->
|
|
QueryDB b Void (UnpreparedValue b) ->
|
|
m (DBStepInfo b)
|
|
mkDBMutationPlan ::
|
|
forall m.
|
|
( MonadError QErr m,
|
|
MonadQueryTags m,
|
|
MonadReader QueryTagsComment m
|
|
) =>
|
|
UserInfo ->
|
|
Options.StringifyNumbers ->
|
|
SourceName ->
|
|
SourceConfig b ->
|
|
MutationDB b Void (UnpreparedValue b) ->
|
|
m (DBStepInfo b)
|
|
mkLiveQuerySubscriptionPlan ::
|
|
forall m.
|
|
( MonadError QErr m,
|
|
MonadIO m,
|
|
MonadBaseControl IO m,
|
|
MonadReader QueryTagsComment m
|
|
) =>
|
|
UserInfo ->
|
|
SourceName ->
|
|
SourceConfig b ->
|
|
Maybe G.Name ->
|
|
RootFieldMap (QueryDB b Void (UnpreparedValue b)) ->
|
|
m (SubscriptionQueryPlan b (MultiplexedQuery b))
|
|
mkDBStreamingSubscriptionPlan ::
|
|
forall m.
|
|
( MonadError QErr m,
|
|
MonadIO m,
|
|
MonadBaseControl IO m,
|
|
MonadReader QueryTagsComment m
|
|
) =>
|
|
UserInfo ->
|
|
SourceName ->
|
|
SourceConfig b ->
|
|
(RootFieldAlias, (QueryDB b Void (UnpreparedValue b))) ->
|
|
m (SubscriptionQueryPlan b (MultiplexedQuery b))
|
|
mkDBQueryExplain ::
|
|
forall m.
|
|
( MonadError QErr m
|
|
) =>
|
|
RootFieldAlias ->
|
|
UserInfo ->
|
|
SourceName ->
|
|
SourceConfig b ->
|
|
QueryDB b Void (UnpreparedValue b) ->
|
|
m (AB.AnyBackend DBStepInfo)
|
|
mkSubscriptionExplain ::
|
|
( MonadError QErr m,
|
|
MonadIO m,
|
|
MonadBaseControl IO m
|
|
) =>
|
|
SubscriptionQueryPlan b (MultiplexedQuery b) ->
|
|
m SubscriptionQueryPlanExplanation
|
|
|
|
mkDBRemoteRelationshipPlan ::
|
|
forall m.
|
|
( MonadError QErr m,
|
|
MonadQueryTags m
|
|
) =>
|
|
UserInfo ->
|
|
SourceName ->
|
|
SourceConfig b ->
|
|
-- | List of json objects, each of which becomes a row of the table.
|
|
NonEmpty J.Object ->
|
|
-- | The above objects have this schema.
|
|
HashMap FieldName (Column b, ScalarType b) ->
|
|
-- | This is a field name from the lhs that *has* to be selected in the
|
|
-- response along with the relationship. It is populated in
|
|
-- `Hasura.GraphQL.Execute.RemoteJoin.Join.processRemoteJoins_` and
|
|
-- the function `convertRemoteSourceRelationship` below assumes it
|
|
-- to be returned as either a number or a string with a number in it
|
|
FieldName ->
|
|
(FieldName, SourceRelationshipSelection b Void UnpreparedValue) ->
|
|
m (DBStepInfo b)
|
|
|
|
-- | This is a helper function to convert a remote source's relationship to a
|
|
-- normal relationship to a temporary table. This function can be used to
|
|
-- implement executeRemoteRelationship function in databases which support
|
|
-- constructing a temporary table for a list of json objects.
|
|
convertRemoteSourceRelationship ::
|
|
forall b.
|
|
(Backend b) =>
|
|
-- | Join columns for the relationship
|
|
HashMap (Column b) (Column b) ->
|
|
-- | The LHS of the join, this is the expression which selects from json
|
|
-- objects
|
|
SelectFromG b (UnpreparedValue b) ->
|
|
-- | This is the __argument__ id column, that needs to be added to the response
|
|
-- This is used by by the remote joins processing logic to convert the
|
|
-- response from upstream to join indices
|
|
Column b ->
|
|
-- | This is the type of the __argument__ id column
|
|
ColumnType b ->
|
|
-- | The relationship column and its name (how it should be selected in the
|
|
-- response)
|
|
(FieldName, SourceRelationshipSelection b Void UnpreparedValue) ->
|
|
QueryDB b Void (UnpreparedValue b)
|
|
convertRemoteSourceRelationship
|
|
columnMapping
|
|
selectFrom
|
|
argumentIdColumn
|
|
argumentIdColumnType
|
|
(relationshipName, relationship) =
|
|
QDBMultipleRows simpleSelect
|
|
where
|
|
-- TODO: FieldName should have also been a wrapper around NonEmptyText
|
|
relName = RelName $ mkNonEmptyTextUnsafe $ getFieldNameTxt relationshipName
|
|
|
|
relationshipField = case relationship of
|
|
SourceRelationshipObject s ->
|
|
AFObjectRelation $ AnnRelationSelectG relName columnMapping s
|
|
SourceRelationshipArray s ->
|
|
AFArrayRelation $ ASSimple $ AnnRelationSelectG relName columnMapping s
|
|
SourceRelationshipArrayAggregate s ->
|
|
AFArrayRelation $ ASAggregate $ AnnRelationSelectG relName columnMapping s
|
|
|
|
argumentIdField =
|
|
( fromCol @b argumentIdColumn,
|
|
AFColumn $
|
|
AnnColumnField
|
|
{ _acfColumn = argumentIdColumn,
|
|
_acfType = argumentIdColumnType,
|
|
_acfAsText = False,
|
|
_acfArguments = Nothing,
|
|
_acfCaseBoolExpression = Nothing
|
|
}
|
|
)
|
|
|
|
simpleSelect =
|
|
AnnSelectG
|
|
{ _asnFields = [argumentIdField, (relationshipName, relationshipField)],
|
|
_asnFrom = selectFrom,
|
|
_asnPerm = TablePerm annBoolExpTrue Nothing,
|
|
_asnArgs = noSelectArgs,
|
|
_asnStrfyNum = Options.Don'tStringifyNumbers,
|
|
_asnNamingConvention = Nothing
|
|
}
|
|
|
|
data DBStepInfo b = DBStepInfo
|
|
{ dbsiSourceName :: SourceName,
|
|
dbsiSourceConfig :: SourceConfig b,
|
|
dbsiPreparedQuery :: Maybe (PreparedQuery b),
|
|
dbsiAction :: ExecutionMonad b EncJSON
|
|
}
|
|
|
|
-- | The result of an explain query: for a given root field (denoted by its name): the generated SQL
|
|
-- query, and the detailed explanation obtained from the database (if any). We mostly use this type
|
|
-- as an intermediary step, and immediately tranform any value we obtain into an equivalent JSON
|
|
-- representation.
|
|
data ExplainPlan = ExplainPlan
|
|
{ _fpField :: !RootFieldAlias,
|
|
_fpSql :: !(Maybe Text),
|
|
_fpPlan :: !(Maybe [Text])
|
|
}
|
|
deriving (Show, Eq, Generic)
|
|
|
|
instance J.ToJSON ExplainPlan where
|
|
toJSON = J.genericToJSON $ J.aesonPrefix J.camelCase
|
|
|
|
-- | One execution step to processing a GraphQL query (e.g. one root field).
|
|
data ExecutionStep where
|
|
-- | A query to execute against the database
|
|
ExecStepDB ::
|
|
HTTP.ResponseHeaders ->
|
|
AB.AnyBackend DBStepInfo ->
|
|
Maybe RemoteJoins ->
|
|
ExecutionStep
|
|
-- | Execute an action
|
|
ExecStepAction ::
|
|
ActionExecutionPlan ->
|
|
ActionsInfo ->
|
|
Maybe RemoteJoins ->
|
|
ExecutionStep
|
|
-- | A graphql query to execute against a remote schema
|
|
ExecStepRemote ::
|
|
!RemoteSchemaInfo ->
|
|
!ResultCustomizer ->
|
|
!GH.GQLReqOutgoing ->
|
|
Maybe RemoteJoins ->
|
|
ExecutionStep
|
|
-- | Output a plain JSON object
|
|
ExecStepRaw ::
|
|
JO.Value ->
|
|
ExecutionStep
|
|
ExecStepMulti ::
|
|
[ExecutionStep] ->
|
|
ExecutionStep
|
|
|
|
-- | The series of steps that need to be executed for a given query. For now, those steps are all
|
|
-- independent. In the future, when we implement a client-side dataloader and generalized joins,
|
|
-- this will need to be changed into an annotated tree.
|
|
type ExecutionPlan = RootFieldMap ExecutionStep
|
|
|
|
class (Monad m) => MonadQueryTags m where
|
|
-- | Creates Query Tags. These are appended to the Generated SQL.
|
|
-- Helps users to use native database monitoring tools to get some 'application-context'.
|
|
createQueryTags ::
|
|
QueryTagsAttributes -> Maybe QueryTagsConfig -> Tagged m QueryTagsComment
|
|
|
|
instance (MonadQueryTags m) => MonadQueryTags (ReaderT r m) where
|
|
createQueryTags qtSourceConfig attr = retag (createQueryTags @m qtSourceConfig attr) :: Tagged (ReaderT r m) QueryTagsComment
|
|
|
|
instance (MonadQueryTags m) => MonadQueryTags (ExceptT e m) where
|
|
createQueryTags qtSourceConfig attr = retag (createQueryTags @m qtSourceConfig attr) :: Tagged (ExceptT e m) QueryTagsComment
|
|
|
|
instance (MonadQueryTags m) => MonadQueryTags (TraceT m) where
|
|
createQueryTags qtSourceConfig attr = retag (createQueryTags @m qtSourceConfig attr) :: Tagged (TraceT m) QueryTagsComment
|
|
|
|
instance (MonadQueryTags m) => MonadQueryTags (MetadataStorageT m) where
|
|
createQueryTags qtSourceConfig attr = retag (createQueryTags @m qtSourceConfig attr) :: Tagged (MetadataStorageT m) QueryTagsComment
|
|
|
|
instance (MonadQueryTags m) => MonadQueryTags (PG.TxET QErr m) where
|
|
createQueryTags qtSourceConfig attr = retag (createQueryTags @m qtSourceConfig attr) :: Tagged (PG.TxET QErr m) QueryTagsComment
|
|
|
|
instance (MonadQueryTags m) => MonadQueryTags (MetadataT m) where
|
|
createQueryTags qtSourceConfig attr = retag (createQueryTags @m qtSourceConfig attr) :: Tagged (MetadataT m) QueryTagsComment
|
|
|
|
instance (MonadQueryTags m) => MonadQueryTags (CacheRWT m) where
|
|
createQueryTags qtSourceConfig attr = retag (createQueryTags @m qtSourceConfig attr) :: Tagged (CacheRWT m) QueryTagsComment
|
|
|
|
instance (MonadQueryTags m) => MonadQueryTags (RunT m) where
|
|
createQueryTags qtSourceConfig attr = retag (createQueryTags @m qtSourceConfig attr) :: Tagged (RunT m) QueryTagsComment
|