Rewrite GraphQL schema generation and query parsing (close #2801) (#4111)
Aka “the PDV refactor.” History is preserved on the branch 2801-graphql-schema-parser-refactor.
* [skip ci] remove stale benchmark commit from commit_diff
* [skip ci] Check for root field name conflicts between remotes
* [skip ci] Additionally check for conflicts between remotes and DB
* [skip ci] Check for conflicts in schema when tracking a table
* [skip ci] Fix equality checking in GraphQL AST
* server: fix mishandling of GeoJSON inputs in subscriptions (fix #3239) (#4551)
* Add support for multiple top-level fields in a subscription to improve testability of subscriptions
* Add an internal flag to enable multiple subscriptions
* Add missing call to withConstructorFn in live queries (fix #3239)
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
* Scheduled triggers (close #1914) (#3553)
server: add scheduled triggers
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
* dev.sh: bump version due to addition of croniter python dependency
* server: fix an introspection query caching issue (fix #4547) (#4661)
Introspection queries accept variables, but we need to make sure to
also touch the variables that we ignore, so that an introspection
query is marked not reusable if we are not able to build a correct
query plan for it.
A better solution here would be to deal with such unused variables
correctly, so that more introspection queries become reusable.
An even better solution would be to type-safely track *how* to reuse
which variables, rather than to split the reusage marking from the
planning.
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* flush log buffer on exception in mkWaiApp ( fix #4772 ) (#4801)
* flush log buffer on exception in mkWaiApp
* add comment to explain the introduced change
* add changelog
* allow logging details of a live query polling thread (#4959)
* changes for poller-log
add various multiplexed query info in poller-log
* minor cleanup, also fixes a bug which will return duplicate data
* Live query poller stats can now be logged
This also removes in-memory stats that are collected about batched
query execution as the log lines when piped into an monitoring tool
will give us better insights.
* allow poller-log to be configurable
* log minimal information in the livequery-poller-log
Other information can be retrieved from /dev/subscriptions/extended
* fix few review comments
* avoid marshalling and unmarshalling from ByteString to EncJSON
* separate out SubscriberId and SubscriberMetadata
Co-authored-by: Anon Ray <rayanon004@gmail.com>
* Don't compile in developer APIs by default
* Tighten up handling of admin secret, more docs
Store the admin secret only as a hash to prevent leaking the secret
inadvertently, and to prevent timing attacks on the secret.
NOTE: best practice for stored user passwords is a function with a
tunable cost like bcrypt, but our threat model is quite different (even
if we thought we could reasonably protect the secret from an attacker
who could read arbitrary regions of memory), and bcrypt is far too slow
(by design) to perform on each request. We'd have to rely on our
(technically savvy) users to choose high entropy passwords in any case.
Referencing #4736
* server/docs: add instructions to fix loss of float precision in PostgreSQL <= 11 (#5187)
This adds a server flag, --pg-connection-options, that can be used to set a PostgreSQL connection parameter, extra_float_digits, that needs to be used to avoid loss of data on older versions of PostgreSQL, which have odd default behavior when returning float values. (fixes #5092)
* [skip ci] Add new commits from master to the commit diff
* [skip ci] serve default directives (skip & include) over introspection
* [skip ci] Update non-Haskell assets with the version on master
* server: refactor GQL execution check and config API (#5094)
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix js issues in tests by pinning dependencies version
* [skip ci] bump graphql version
* [skip ci] Add note about memory usage
* generalize query execution logic on Postgres (#5110)
* generalize PGExecCtx to support specialized functions for various operations
* fix tests compilation
* allow customising PGExecCtx when starting the web server
* server: changes catalog initialization and logging for pro customization (#5139)
* new typeclass to abstract the logic of QueryLog-ing
* abstract the logic of logging websocket-server logs
introduce a MonadWSLog typeclass
* move catalog initialization to init step
expose a helper function to migrate catalog
create schema cache in initialiseCtx
* expose various modules and functions for pro
* [skip ci] cosmetic change
* [skip ci] fix test calling a mutation that does not exist
* [skip ci] minor text change
* [skip ci] refactored input values
* [skip ci] remove VString Origin
* server: fix updating of headers behaviour in the update cron trigger API and create future events immediately (#5151)
* server: fix bug to update headers in an existing cron trigger and create future events
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Lower stack chunk size in RTS to reduce thread STACK memory (closes #5190)
This reduces memory consumption for new idle subscriptions significantly
(see linked ticket).
The hypothesis is: we fork a lot of threads per websocket, and some of
these use slightly more than the initial 1K stack size, so the first
overflow balloons to 32K, when significantly less is required.
However: running with `+RTS -K1K -xc` did not seem to show evidence of
any overflows! So it's a mystery why this improves things.
GHC should probably also be doubling the stack buffer at each overflow
or doing something even smarter; the knobs we have aren't so helpful.
* [skip ci] fix todo and schema generation for aggregate fields
* 5087 libpq pool leak (#5089)
Shrink libpq buffers to 1MB before returning connection to pool. Closes #5087
See: https://github.com/hasura/pg-client-hs/pull/19
Also related: #3388 #4077
* bump pg-client-hs version (fixes a build issue on some environments) (#5267)
* do not use prepared statements for mutations
* server: unlock scheduled events on graceful shutdown (#4928)
* Fix buggy parsing of new --conn-lifetime flag in 2b0e3774
* [skip ci] remove cherry-picked commit from commit_diff.txt
* server: include additional fields in scheduled trigger webhook payload (#5262)
* include scheduled triggers metadata in the webhook body
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* [skip ci] fix cast exp parser & few TODOs
* [skip ci] fix remote fields arguments
* [skip ci] fix few more TODO, no-op refactor, move resolve/action.hs to execute/action.hs
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix: restrict remote relationship field generation for hasura queries
* [skip ci] no-op refactor; move insert execution code from schema parser module
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] implement header checking
Probably closes #14 and #3659.
* server: refactor 'pollQuery' to have a hook to process 'PollDetails' (#5391)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* update pg-client (#5421)
* [skip ci] update commit_diff
* Fix latency buckets for telemetry data
These must have gotten messed up during a refactor. As a consequence
almost all samples received so far fall into the single erroneous 0 to
1K seconds (originally supposed to be 1ms?) bucket.
I also re-thought what the numbers should be, but these are still
arbitrary and might want adjusting in the future.
* [skip ci] include the latest commit compared against master in commit_diff
* [skip ci] include new commits from master in commit_diff
* [skip ci] improve description generation
* [skip ci] sort all introspect arrays
* [skip ci] allow parsers to specify error codes
* [skip ci] fix integer and float parsing error code
* [skip ci] scalar from json errors are now parse errors
* [skip ci] fixed negative integer error message and code
* [skip ci] Re-fix nullability in relationships
* [skip ci] no-op refactor and removed couple of FIXMEs
* [skip ci] uncomment code in 'deleteMetadataObject'
* [skip ci] Fix re-fix of nullability for relationships
* [skip ci] fix default arguments error code
* [skip ci] updated test error message
!!! WARNING !!!
Since all fields accept `null`, they all are technically optional in
the new schema. Meaning there's no such thing as a missing mandatory
field anymore: a field that doesn't have a default value, and which
therefore isn't labelled as "optional" in the schema, will be assumed
to be null if it's missing, meaning it isn't possible anymore to have
an error for a missing mandatory field. The only possible error is now
when a optional positional argument is omitted but is not the last
positional argument.
* [skip ci] cleanup of int scalar parser
* [skip ci] retro-compatibility of offset as string
* [skip ci] Remove commit from commit_diff.txt
Although strictly speaking we don't know if this will work correctly in PDV
if we would implement query plan caching, the fact is that in the theoretical
case that we would have the same issue in PDV, it would probably apply not just
to introspection, and the fix would be written completely differently. So this
old commit is of no value to us other than the heads-up "make sure query plan
caching works correctly even in the presence of unused variables", which is
already part of the test suite.
* Add MonadTrace and MonadExecuteQuery abstractions (#5383)
* [skip ci] Fix accumulation of input object types
Just like object types, interface types, and union types, we have to avoid
circularities when collecting input types from the GraphQL AST.
Additionally, this fixes equality checks for input object types (whose fields
are unordered, and hence should be compared as sets) and enum types (ditto).
* [skip ci] fix fragment error path
* [skip ci] fix node error code
* [skip ci] fix paths in insert queries
* [skip ci] fix path in objects
* [skip ci] manually alter node id path for consistency
* [skip ci] more node error fixups
* [skip ci] one last relay error message fix
* [skip ci] update commit_diff
* Propagate the trace context to event triggers (#5409)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: log request/response sizes for event triggers (#5463)
* server: log request/response sizes for event triggers
event triggers (and scheduled triggers) now have request/response size
in their logs.
* add changelog entry
* Tracing: Simplify HTTP traced request (#5451)
Remove the Inversion of Control (SuspendRequest) and simplify
the tracing of HTTP Requests.
Co-authored-by: Phil Freeman <phil@hasura.io>
* Attach request ID as tracing metadata (#5456)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* Include the request ID as trace metadata
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
* Typo
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: add logging for action handlers (#5471)
* server: add logging for action handlers
* add changelog entry
* change action-handler log type from internal to non-internal
* fix action-handler-log name
* server: pass http and websocket request to logging context (#5470)
* pass request body to logging context in all cases
* add message size logging on the websocket API
this is required by graphql-engine-pro/#416
* message size logging on websocket API
As we need to log all messages recieved/sent by the websocket server,
it makes sense to log them as part of the websocket server event logs.
Previously message recieved were logged inside the onMessage handler,
and messages sent were logged only for "data" messages (as a server event log)
* fix review comments
Co-authored-by: Phil Freeman <phil@hasura.io>
* server: stop eventing subsystem threads when shutting down (#5479)
* server: stop eventing subsystem threads when shutting down
* Apply suggestions from code review
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
* [skip ci] update commit_diff with new commits added in master
* Bugfix to support 0-size HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE
Also some minor refactoring of bounded cache module:
- the maxBound check in `trim` was confusing and unnecessary
- consequently trim was unnecessary for lookupPure
Also add some basic tests
* Support only the bounded cache, with default HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE of 4000. Closes #5363
* [skip ci] remove merge commit from commit_diff
* server: Fix compiler warning caused by GHC upgrade (#5489)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] update all non server code from master
* [skip ci] aligned object field error message with master
* [skip ci] fix remaining undefined?
* [skip ci] remove unused import
* [skip ci] revert to previous error message, fix tests
* Move nullableType/nonNullableType to Schema.hs
These are functions on Types, not on Parsers.
* [skip ci] fix setup to fix backend only test
the order in which permission checks are performed on the branch is
slightly different than on master, resulting in a slightly different
error if there are no other mutations the user has access to. By
adding update permissions, we go back to the expected case.
* [skip ci] fix insert geojson tests to reflect new paths
* [skip ci] fix enum test for better error message
* [skip ci] fix header test for better error message
* [skip ci] fix fragment cycle test for better error message
* [skip ci] fix error message for type mismatch
* [skip ci] fix variable path in test
* [skip ci] adjust tests after bug fix
* [skip ci] more tests fixing
* Add hdb_catalog.current_setting abstraction for reading Hasura settings
As the comment in the function’s definition explains, this is needed to
work around an awkward Postgres behavior.
* [skip ci] Update CONTRIBUTING.md to mention Node setup for Python tests
* [skip ci] Add missing Python tests env var to CONTRIBUTING.md
* [skip ci] fix order of result when subscription is run with multiple nodes
* [skip ci] no-op refactor: fix a warning in Internal/Parser.hs
* [skip ci] throw error when a subscription contains remote joins
* [skip ci] Enable easier profiling by hiding AssertNF behind a flag
In order to compile a profiling build, run:
$ cabal new-build -f profiling --enable-profiling
* [skip ci] Fix two warnings
We used to lookup the objects that implement a given interface by filtering all
objects in the schema document. However, one of the tests expects us to
generate a warning if the provided `implements` field of an introspection query
specifies an object not implementing some interface. So we use that field
instead.
* [skip ci] Fix warnings by commenting out query plan caching
* [skip ci] improve masking/commenting query caching related code & few warning fixes
* [skip ci] Fixed compiler warnings in graphql-parser-hs
* Sync non-Haskell assets with master
* [skip ci] add a test inserting invalid GraphQL but valid JSON value in a jsonb column
* [skip ci] Avoid converting to/from Map
* [skip ci] Apply some hlint suggestions
* [skip ci] remove redundant constraints from buildLiveQueryPlan and explainGQLQuery
* [skip ci] add NOTEs about missing Tracing constraints in PDV from master
* Remove -fdefer-typed-holes, fix warnings
* Update cabal.project.freeze
* Limit GHC’s heap size to 8GB in CI to avoid the OOM killer
* Commit package-lock.json for Python tests’ remote schema server
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* add test for table_by_pk node when roles doesn't have permission to PK
* [skip ci] fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* [skip ci] test case fix for a6450e126bc2d98bcfd3791501986e4627ce6c6f
* [skip ci] add tests to agg queries when role doesn't have access to any cols
* fix backend test
* Simplify subscription execution
* [skip ci] add test to check if required headers are present while querying
* Suppose, table B is related to table A and to query B certain headers are
necessary, then the test checks that we are throwing error when the header
is not set when B is queried through A
* fix mutations not checking for view mutability
* [skip ci] add variable type checking and corresponding tests
* [skip ci] add test to check if update headers are present while doing an upsert
* [skip ci] add positive counterparts to some of the negative permission tests
* fix args missing their description in introspect
* [skip ci] Remove unused function; insert missing markNotReusable call
* [skip ci] Add a Note about InputValue
* [skip ci] Delete LegacySchema/ 🎉
* [skip ci] Delete GraphQL/{Resolve,Validate}/ 🎉
* [skip ci] Delete top-level Resolve/Validate modules; tidy .cabal file
* [skip ci] Delete LegacySchema top-level module
Somehow I missed this one.
* fix input value to json
* [skip ci] elaborate on JSON objects in GraphQL
* [skip ci] add missing file
* [skip ci] add a test with subscription containing remote joins
* add a test with remote joins in mutation output
* [skip ci] Add some comments to Schema/Mutation.hs
* [skip ci] Remove no longer needed code from RemoteServer.hs
* [skip ci] Use a helper function to generate conflict clause parsers
* [skip ci] fix type checker error in fields with default value
* capitalize the header keys in select_articles_without_required_headers
* Somehow, this was the reason the tests were failing. I have no idea, why!
* [skip ci] Add a long Note about optional fields and nullability
* Improve comments a bit; simplify Schema/Common.hs a bit
* [skip ci] full implementation of 5.8.5 type checking.
* [skip ci] fix validation test teardown
* [skip ci] fix schema stitching test
* fix remote schema ignoring enum nullability
* [skip ci] fix fieldOptional to not discard nullability
* revert nullability of use_spheroid
* fix comment
* add required remote fields with arguments for tests
* [skip ci] add missing docstrings
* [skip ci] fixed description of remote fields
* [skip ci] change docstring for consistency
* fix several schema inconsistencies
* revert behaviour change in function arguments parsing
* fix remaining nullability issues in new schema
* minor no-op refactor; use isListType from graphql-parser-hs
* use nullability of remote schema node, while creating a Remote reln
* fix 'ID' input coercing & action 'ID' type relationship mapping
* include ASTs in MonadExecuteQuery
* needed for PRO code-base
* Delete code for "interfaces implementing ifaces" (draft GraphQL spec)
Previously I started writing some code that adds support for a future GraphQL
feature where interfaces may themselves be sub-types of other interfaces.
However, this code was incomplete, and partially incorrect. So this commit
deletes support for that entirely.
* Ignore a remote schema test during the upgrade/downgrade test
The PDV refactor does a better job at exposing a minimal set of types through
introspection. In particular, not every type that is present in a remote schema
is re-exposed by Hasura. The test
test_schema_stitching.py::TestRemoteSchemaBasic::test_introspection assumed that
all types were re-exposed, which is not required for GraphQL compatibility, in
order to test some aspect of our support for remote schemas.
So while this particular test has been updated on PDV, the PDV branch now does
not pass the old test, which we argue to be incorrect. Hence this test is
disabled while we await a release, after which we can re-enable it.
This also re-enables a test that was previously disabled for similar, though
unrelated, reasons.
* add haddock documentation to the action's field parsers
* Deslecting some tests in server-upgrade
Some tests with current build are failing on server upgrade
which it should not. The response is more accurate than
what it was.
Also the upgrade tests were not throwing errors when the test is
expected to return an error, but succeeds. The test framework is
patched to catch this case.
* [skip ci] Add a long Note about interfaces and object types
* send the response headers back to client after running a query
* Deselect a few more tests during upgrade/downgrade test
* Update commit_diff.txt
* change log kind from db_migrate to catalog_migrate (#5531)
* Show method and complete URI in traced HTTP calls (#5525)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* Fix telemetry reporting of transport (websocket was reported as http)
* add log kinds in cli-migrations image (#5529)
* add log kinds in cli-migrations image
* give hint to resolve timeout error
* minor changes and CHANGELOG
* server: set hasura.tracecontext in RQL mutations [#5542] (#5555)
* server: set hasura.tracecontext in RQL mutations [#5542]
* Update test suite
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Add bulldozer auto-merge and -update configuration
We still need to add the github app (as of time of opening this PR)
Afterwards devs should be able to allow bulldozer to automatically
"update" the branch, merging in parent when it changes, as well as
automatically merge when all checks pass.
This is opt-in by adding the `auto-update-auto-merge` label to the PR.
* Remove 'bulldozer' config, try 'kodiak' for auto-merge
see: https://github.com/chdsbd/kodiak
The main issue that bit us was not being able to auto update forked
branches, also:
https://github.com/palantir/bulldozer/issues/66
https://github.com/palantir/bulldozer/issues/145
* Cherry-picked all commits
* [skip ci] Slightly improve formatting
* Revert "fix introspection query if any enum column present in primary key (fix #5200) (#5522)"
This reverts commit 0f9a5afa59a88f6824f4d63d58db246a5ba3fb03.
This undoes a cherry-pick of 34288e1eb5f2c5dad9e6d1e05453dd52397dc970 that was
already done previously in a6450e126bc2d98bcfd3791501986e4627ce6c6f, and
subsequently fixed for PDV in 70e89dc250f8ddc6e2b7930bbe2b3eeaa6dbe1db
* Do a small bit of tidying in Hasura.GraphQL.Parser.Collect
* Fix cherry-picking work
Some previous cherry-picks ended up modifying code that is commented out
* [skip ci] clarified comment regarding insert representation
* [skip ci] removed obsolete todos
* cosmetic change
* fix action error message
* [skip ci] remove obsolete comment
* [skip ci] synchronize stylish haskell extensions list
* use previously defined scalar names in parsers rather than ad-hoc literals
* Apply most syntax hlint hints.
* Clarify comment on update mutation.
* [skip ci] Clarify what fields should be specified for objects
* Update "_inc" description.
* Use record types rather than tuples fo IntrospectionResult and ParsedIntrospection
* Get rid of checkFieldNamesUnique (use Data.List.Extended.duplicates)
* Throw more errors when collecting query root names
* [skip ci] clean column parser comment
* Remove dead code inserted in ab65b39
* avoid converting to non-empty list where not needed
* add note and TODO about the disabled checks in PDV
* minor refactor in remoteField' function
* Unify two getObject methods
* Nitpicks in Remote.hs
* Update CHANGELOG.md
* Revert "Unify two getObject methods"
This reverts commit bd6bb40355b3d189a46c0312eb52225e18be57b3.
We do need two different getObject functions as the corresponding error message is different
* Fix error message in Remote.hs
* Update CHANGELOG.md
Co-authored-by: Auke Booij <auke@tulcod.com>
* Apply suggested Changelog fix.
Co-authored-by: Auke Booij <auke@tulcod.com>
* Fix typo in Changelog.
* [skip ci] Update changelog.
* reuse type names to avoid duplication
* Fix Hashable instance for Definition
The presence of `Maybe Unique`, and an optional description, as part of
`Definition`s, means that `Definition`s that are considered `Eq`ual may get
different hashes. This can happen, for instance, when one object is memoized
but another is not.
* [skip ci] Update commit_diff.txt
* Bump parser version.
* Bump freeze file after changes in parser.
* [skip ci] Incorporate commits from master
* Fix developer flag in server/cabal.project.freeze
Co-authored-by: Auke Booij <auke@tulcod.com>
* Deselect a changed ENUM test for upgrade/downgrade CI
* Deselect test here as well
* [skip ci] remove dead code
* Disable more tests for upgrade/downgrade
* Fix which test gets deselected
* Revert "Add hdb_catalog.current_setting abstraction for reading Hasura settings"
This reverts commit 66e85ab9fbd56cca2c28a80201f6604fbe811b85.
* Remove circular reference in cabal.project.freeze
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Auke Booij <auke@hasura.io>
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
Co-authored-by: Brandon Simmons <brandon.m.simmons@gmail.com>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
Co-authored-by: Anon Ray <rayanon004@gmail.com>
Co-authored-by: rakeshkky <12475069+rakeshkky@users.noreply.github.com>
Co-authored-by: Anon Ray <ecthiender@users.noreply.github.com>
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Antoine Leblanc <antoine@hasura.io>
Co-authored-by: Brandon Simmons <brandon@hasura.io>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Lyndon Maydwell <lyndon@sordina.net>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Naveen Naidu <naveennaidu479@gmail.com>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Nizar Malangadan <nizar-m@users.noreply.github.com>
Co-authored-by: Antoine Leblanc <crucuny@gmail.com>
Co-authored-by: Auke Booij <auke@tulcod.com>
2020-08-21 20:27:01 +03:00
|
|
|
{-# LANGUAGE CPP #-}
|
2020-10-07 11:55:39 +03:00
|
|
|
{-# LANGUAGE UndecidableInstances #-}
|
2019-11-26 15:14:21 +03:00
|
|
|
|
|
|
|
module Hasura.App where
|
|
|
|
|
2021-01-09 02:09:15 +03:00
|
|
|
import Hasura.Prelude
|
2020-06-19 09:42:32 +03:00
|
|
|
|
2021-03-31 13:39:01 +03:00
|
|
|
import qualified Control.Concurrent.Async.Lifted.Safe as LA
|
|
|
|
import qualified Control.Concurrent.Extended as C
|
2021-04-06 06:25:02 +03:00
|
|
|
import qualified Control.Concurrent.STM as STM
|
2021-03-31 13:39:01 +03:00
|
|
|
import qualified Control.Exception.Lifted as LE
|
|
|
|
import qualified Data.Aeson as A
|
|
|
|
import qualified Data.ByteString.Char8 as BC
|
|
|
|
import qualified Data.ByteString.Lazy.Char8 as BLC
|
|
|
|
import qualified Data.Environment as Env
|
|
|
|
import qualified Data.HashMap.Strict as HM
|
|
|
|
import qualified Data.Set as Set
|
|
|
|
import qualified Data.Text as T
|
|
|
|
import qualified Data.Time.Clock as Clock
|
|
|
|
import qualified Data.Yaml as Y
|
|
|
|
import qualified Database.PG.Query as Q
|
|
|
|
import qualified Network.HTTP.Client as HTTP
|
|
|
|
import qualified Network.HTTP.Client.TLS as HTTP
|
|
|
|
import qualified Network.Wai.Handler.Warp as Warp
|
|
|
|
import qualified System.Log.FastLogger as FL
|
|
|
|
import qualified System.Metrics as EKG
|
|
|
|
import qualified System.Metrics.Gauge as EKG.Gauge
|
|
|
|
import qualified Text.Mustache.Compile as M
|
|
|
|
import qualified Web.Spock.Core as Spock
|
|
|
|
|
|
|
|
import Control.Concurrent.STM.TVar (TVar, readTVarIO)
|
|
|
|
import Control.Exception (bracket_, throwIO)
|
|
|
|
import Control.Monad.Catch (Exception, MonadCatch, MonadMask,
|
|
|
|
MonadThrow, onException)
|
|
|
|
import Control.Monad.Morph (hoist)
|
|
|
|
import Control.Monad.STM (atomically)
|
2021-01-09 02:09:15 +03:00
|
|
|
import Control.Monad.Stateless
|
2021-03-31 13:39:01 +03:00
|
|
|
import Control.Monad.Trans.Control (MonadBaseControl (..))
|
2021-05-14 12:38:37 +03:00
|
|
|
import Control.Monad.Trans.Managed (ManagedT (..))
|
2021-01-09 02:09:15 +03:00
|
|
|
import Control.Monad.Unique
|
2021-03-31 13:39:01 +03:00
|
|
|
import Data.FileEmbed (makeRelativeToProject)
|
|
|
|
import Data.Time.Clock (UTCTime)
|
2021-01-09 02:09:15 +03:00
|
|
|
#ifndef PROFILING
|
|
|
|
import GHC.AssertNF
|
|
|
|
#endif
|
|
|
|
import Network.HTTP.Client.Extended
|
|
|
|
import Options.Applicative
|
2021-03-31 13:39:01 +03:00
|
|
|
import System.Environment (getEnvironment)
|
2021-01-09 02:09:15 +03:00
|
|
|
|
2021-03-31 13:39:01 +03:00
|
|
|
import qualified Hasura.GraphQL.Execute.LiveQuery.Poll as EL
|
|
|
|
import qualified Hasura.GraphQL.Transport.WebSocket.Server as WS
|
|
|
|
import qualified Hasura.Tracing as Tracing
|
2021-01-09 02:09:15 +03:00
|
|
|
|
2020-10-27 16:53:49 +03:00
|
|
|
import Hasura.Backends.Postgres.Connection
|
2021-05-11 18:18:31 +03:00
|
|
|
import Hasura.Base.Error
|
2019-11-26 15:14:21 +03:00
|
|
|
import Hasura.EncJSON
|
2020-07-02 14:57:09 +03:00
|
|
|
import Hasura.Eventing.Common
|
2020-07-30 05:34:50 +03:00
|
|
|
import Hasura.Eventing.EventTrigger
|
2020-05-13 15:33:16 +03:00
|
|
|
import Hasura.Eventing.ScheduledTrigger
|
2021-05-05 15:25:27 +03:00
|
|
|
import Hasura.GraphQL.Execute (ExecutionStep (..),
|
|
|
|
MonadGQLExecutionCheck (..),
|
2021-03-31 13:39:01 +03:00
|
|
|
checkQueryInAllowlist)
|
2020-12-14 07:30:19 +03:00
|
|
|
import Hasura.GraphQL.Execute.Action
|
2021-03-31 13:39:01 +03:00
|
|
|
import Hasura.GraphQL.Execute.Action.Subscription
|
|
|
|
import Hasura.GraphQL.Logging (MonadQueryLog (..))
|
|
|
|
import Hasura.GraphQL.Transport.HTTP (MonadExecuteQuery (..))
|
|
|
|
import Hasura.GraphQL.Transport.HTTP.Protocol (toParsed)
|
2019-11-26 15:14:21 +03:00
|
|
|
import Hasura.Logging
|
2020-11-25 13:56:44 +03:00
|
|
|
import Hasura.Metadata.Class
|
2020-06-19 09:42:32 +03:00
|
|
|
import Hasura.RQL.DDL.Schema.Cache
|
2020-12-28 15:56:00 +03:00
|
|
|
import Hasura.RQL.DDL.Schema.Cache.Common
|
2020-12-14 07:30:19 +03:00
|
|
|
import Hasura.RQL.DDL.Schema.Catalog
|
2020-12-28 15:56:00 +03:00
|
|
|
import Hasura.RQL.DDL.Schema.Source
|
2020-11-25 13:56:44 +03:00
|
|
|
import Hasura.RQL.Types
|
2019-12-09 01:17:39 +03:00
|
|
|
import Hasura.RQL.Types.Run
|
2021-03-31 13:39:01 +03:00
|
|
|
import Hasura.Server.API.Query (requiresAdmin, runQueryM)
|
2019-11-26 15:14:21 +03:00
|
|
|
import Hasura.Server.App
|
|
|
|
import Hasura.Server.Auth
|
2021-03-31 13:39:01 +03:00
|
|
|
import Hasura.Server.CheckUpdates (checkForUpdates)
|
2019-11-26 15:14:21 +03:00
|
|
|
import Hasura.Server.Init
|
|
|
|
import Hasura.Server.Logging
|
2021-03-31 13:39:01 +03:00
|
|
|
import Hasura.Server.Migrate (getMigratedFrom, migrateCatalog)
|
2019-11-26 15:14:21 +03:00
|
|
|
import Hasura.Server.SchemaUpdate
|
|
|
|
import Hasura.Server.Telemetry
|
2020-11-25 13:56:44 +03:00
|
|
|
import Hasura.Server.Types
|
2019-11-26 15:14:21 +03:00
|
|
|
import Hasura.Server.Version
|
2020-04-24 12:10:53 +03:00
|
|
|
import Hasura.Session
|
2021-03-13 17:40:50 +03:00
|
|
|
|
2021-05-11 18:18:31 +03:00
|
|
|
|
2020-07-14 22:00:58 +03:00
|
|
|
data ExitCode
|
2020-12-21 21:56:00 +03:00
|
|
|
-- these are used during server initialization:
|
2020-07-14 22:00:58 +03:00
|
|
|
= InvalidEnvironmentVariableOptionsError
|
|
|
|
| InvalidDatabaseConnectionParamsError
|
|
|
|
| AuthConfigurationError
|
|
|
|
| EventSubSystemError
|
2020-12-21 21:56:00 +03:00
|
|
|
| DatabaseMigrationError
|
2021-02-11 20:54:25 +03:00
|
|
|
| SchemaCacheInitError -- ^ used by MT because it initialises the schema cache only
|
2020-12-21 21:56:00 +03:00
|
|
|
-- these are used in app/Main.hs:
|
2020-07-14 22:00:58 +03:00
|
|
|
| MetadataExportError
|
|
|
|
| MetadataCleanError
|
|
|
|
| ExecuteProcessError
|
|
|
|
| DowngradeProcessError
|
|
|
|
deriving Show
|
|
|
|
|
|
|
|
data ExitException
|
|
|
|
= ExitException
|
|
|
|
{ eeCode :: !ExitCode
|
|
|
|
, eeMessage :: !BC.ByteString
|
|
|
|
} deriving (Show)
|
|
|
|
|
|
|
|
instance Exception ExitException
|
|
|
|
|
|
|
|
printErrExit :: (MonadIO m) => forall a . ExitCode -> String -> m a
|
|
|
|
printErrExit reason = liftIO . throwIO . ExitException reason . BC.pack
|
|
|
|
|
|
|
|
printErrJExit :: (A.ToJSON a, MonadIO m) => forall b . ExitCode -> a -> m b
|
|
|
|
printErrJExit reason = liftIO . throwIO . ExitException reason . BLC.toStrict . A.encode
|
2019-11-26 15:14:21 +03:00
|
|
|
|
|
|
|
parseHGECommand :: EnabledLogTypes impl => Parser (RawHGECommand impl)
|
|
|
|
parseHGECommand =
|
|
|
|
subparser
|
|
|
|
( command "serve" (info (helper <*> (HCServe <$> serveOptionsParser))
|
|
|
|
( progDesc "Start the GraphQL Engine Server"
|
|
|
|
<> footerDoc (Just serveCmdFooter)
|
|
|
|
))
|
|
|
|
<> command "export" (info (pure HCExport)
|
|
|
|
( progDesc "Export graphql-engine's metadata to stdout" ))
|
|
|
|
<> command "clean" (info (pure HCClean)
|
|
|
|
( progDesc "Clean graphql-engine's metadata to start afresh" ))
|
|
|
|
<> command "execute" (info (pure HCExecute)
|
|
|
|
( progDesc "Execute a query" ))
|
2020-02-07 14:03:12 +03:00
|
|
|
<> command "downgrade" (info (HCDowngrade <$> downgradeOptionsParser)
|
|
|
|
(progDesc "Downgrade the GraphQL Engine schema to the specified version"))
|
2019-11-26 15:14:21 +03:00
|
|
|
<> command "version" (info (pure HCVersion)
|
|
|
|
(progDesc "Prints the version of GraphQL Engine"))
|
|
|
|
)
|
|
|
|
|
|
|
|
parseArgs :: EnabledLogTypes impl => IO (HGEOptions impl)
|
|
|
|
parseArgs = do
|
|
|
|
rawHGEOpts <- execParser opts
|
|
|
|
env <- getEnvironment
|
|
|
|
let eitherOpts = runWithEnv env $ mkHGEOptions rawHGEOpts
|
2020-10-28 19:40:33 +03:00
|
|
|
onLeft eitherOpts $ printErrExit InvalidEnvironmentVariableOptionsError
|
2019-11-26 15:14:21 +03:00
|
|
|
where
|
|
|
|
opts = info (helper <*> hgeOpts)
|
|
|
|
( fullDesc <>
|
|
|
|
header "Hasura GraphQL Engine: Realtime GraphQL API over Postgres with access control" <>
|
|
|
|
footerDoc (Just mainCmdFooter)
|
|
|
|
)
|
2020-12-28 15:56:00 +03:00
|
|
|
hgeOpts = HGEOptionsG <$> parsePostgresConnInfo
|
|
|
|
<*> parseMetadataDbUrl
|
|
|
|
<*> parseHGECommand
|
2019-11-26 15:14:21 +03:00
|
|
|
|
|
|
|
printJSON :: (A.ToJSON a, MonadIO m) => a -> m ()
|
|
|
|
printJSON = liftIO . BLC.putStrLn . A.encode
|
|
|
|
|
|
|
|
printYaml :: (A.ToJSON a, MonadIO m) => a -> m ()
|
|
|
|
printYaml = liftIO . BC.putStrLn . Y.encode
|
|
|
|
|
|
|
|
mkPGLogger :: Logger Hasura -> Q.PGLogger
|
|
|
|
mkPGLogger (Logger logger) (Q.PLERetryMsg msg) =
|
|
|
|
logger $ PGLog LevelWarn msg
|
|
|
|
|
2020-11-24 09:10:04 +03:00
|
|
|
-- | Context required for all graphql-engine CLI commands
|
|
|
|
data GlobalCtx
|
|
|
|
= GlobalCtx
|
2020-12-28 15:56:00 +03:00
|
|
|
{ _gcHttpManager :: !HTTP.Manager
|
|
|
|
, _gcMetadataDbConnInfo :: !Q.ConnInfo
|
2021-01-07 12:04:22 +03:00
|
|
|
, _gcDefaultPostgresConnInfo :: !(Maybe (UrlConf, Q.ConnInfo), Maybe Int)
|
|
|
|
-- ^ --database-url option, @'UrlConf' is required to construct default source configuration
|
|
|
|
-- and optional retries
|
2020-11-24 09:10:04 +03:00
|
|
|
}
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2021-02-11 20:54:25 +03:00
|
|
|
|
2020-11-24 09:10:04 +03:00
|
|
|
initGlobalCtx
|
2020-12-28 15:56:00 +03:00
|
|
|
:: (MonadIO m)
|
2021-01-07 12:04:22 +03:00
|
|
|
=> Env.Environment
|
|
|
|
-> Maybe String
|
2021-02-11 20:54:25 +03:00
|
|
|
-- ^ the metadata DB URL
|
2021-01-07 12:04:22 +03:00
|
|
|
-> PostgresConnInfo (Maybe UrlConf)
|
2021-02-11 20:54:25 +03:00
|
|
|
-- ^ the user's DB URL
|
2021-01-07 12:04:22 +03:00
|
|
|
-> m GlobalCtx
|
2020-12-28 15:56:00 +03:00
|
|
|
initGlobalCtx env metadataDbUrl defaultPgConnInfo = do
|
|
|
|
httpManager <- liftIO $ HTTP.newManager HTTP.tlsManagerSettings
|
|
|
|
|
|
|
|
let PostgresConnInfo dbUrlConf maybeRetries = defaultPgConnInfo
|
2021-02-11 20:54:25 +03:00
|
|
|
mkConnInfoFromSource dbUrl = do
|
|
|
|
resolvePostgresConnInfo env dbUrl maybeRetries
|
|
|
|
|
|
|
|
mkConnInfoFromMDb mdbUrl =
|
|
|
|
let retries = fromMaybe 1 maybeRetries
|
|
|
|
in (Q.ConnInfo retries . Q.CDDatabaseURI . txtToBs . T.pack) mdbUrl
|
|
|
|
|
|
|
|
mkGlobalCtx mdbConnInfo sourceConnInfo =
|
|
|
|
pure $ GlobalCtx httpManager mdbConnInfo (sourceConnInfo, maybeRetries)
|
2021-01-07 12:04:22 +03:00
|
|
|
|
2021-02-11 20:54:25 +03:00
|
|
|
case (metadataDbUrl, dbUrlConf) of
|
|
|
|
(Nothing, Nothing) ->
|
|
|
|
printErrExit InvalidDatabaseConnectionParamsError
|
|
|
|
"Fatal Error: Either of --metadata-database-url or --database-url option expected"
|
2021-01-07 12:04:22 +03:00
|
|
|
|
2021-02-11 20:54:25 +03:00
|
|
|
-- If no metadata storage specified consider use default database as
|
|
|
|
-- metadata storage
|
|
|
|
(Nothing, Just dbUrl) -> do
|
|
|
|
connInfo <- mkConnInfoFromSource dbUrl
|
|
|
|
mkGlobalCtx connInfo $ Just (dbUrl, connInfo)
|
2020-12-28 15:56:00 +03:00
|
|
|
|
2021-02-11 20:54:25 +03:00
|
|
|
(Just mdUrl, Nothing) -> do
|
|
|
|
let mdConnInfo = mkConnInfoFromMDb mdUrl
|
|
|
|
mkGlobalCtx mdConnInfo Nothing
|
|
|
|
|
|
|
|
(Just mdUrl, Just dbUrl) -> do
|
|
|
|
srcConnInfo <- mkConnInfoFromSource dbUrl
|
|
|
|
let mdConnInfo = mkConnInfoFromMDb mdUrl
|
|
|
|
mkGlobalCtx mdConnInfo (Just (dbUrl, srcConnInfo))
|
2020-11-24 09:10:04 +03:00
|
|
|
|
|
|
|
|
|
|
|
-- | Context required for the 'serve' CLI command.
|
|
|
|
data ServeCtx
|
|
|
|
= ServeCtx
|
2020-12-28 15:56:00 +03:00
|
|
|
{ _scHttpManager :: !HTTP.Manager
|
|
|
|
, _scInstanceId :: !InstanceId
|
|
|
|
, _scLoggers :: !Loggers
|
|
|
|
, _scMetadataDbPool :: !Q.PGPool
|
|
|
|
, _scShutdownLatch :: !ShutdownLatch
|
|
|
|
, _scSchemaCache :: !RebuildableSchemaCache
|
2021-02-11 20:54:25 +03:00
|
|
|
, _scSchemaCacheRef :: !SchemaCacheRef
|
2021-04-06 06:25:02 +03:00
|
|
|
, _scMetaVersionRef :: !(STM.TMVar MetadataResourceVersion)
|
2019-11-26 15:14:21 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
-- | Collection of the LoggerCtx, the regular Logger and the PGLogger
|
Rewrite GraphQL schema generation and query parsing (close #2801) (#4111)
Aka “the PDV refactor.” History is preserved on the branch 2801-graphql-schema-parser-refactor.
* [skip ci] remove stale benchmark commit from commit_diff
* [skip ci] Check for root field name conflicts between remotes
* [skip ci] Additionally check for conflicts between remotes and DB
* [skip ci] Check for conflicts in schema when tracking a table
* [skip ci] Fix equality checking in GraphQL AST
* server: fix mishandling of GeoJSON inputs in subscriptions (fix #3239) (#4551)
* Add support for multiple top-level fields in a subscription to improve testability of subscriptions
* Add an internal flag to enable multiple subscriptions
* Add missing call to withConstructorFn in live queries (fix #3239)
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
* Scheduled triggers (close #1914) (#3553)
server: add scheduled triggers
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
* dev.sh: bump version due to addition of croniter python dependency
* server: fix an introspection query caching issue (fix #4547) (#4661)
Introspection queries accept variables, but we need to make sure to
also touch the variables that we ignore, so that an introspection
query is marked not reusable if we are not able to build a correct
query plan for it.
A better solution here would be to deal with such unused variables
correctly, so that more introspection queries become reusable.
An even better solution would be to type-safely track *how* to reuse
which variables, rather than to split the reusage marking from the
planning.
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* flush log buffer on exception in mkWaiApp ( fix #4772 ) (#4801)
* flush log buffer on exception in mkWaiApp
* add comment to explain the introduced change
* add changelog
* allow logging details of a live query polling thread (#4959)
* changes for poller-log
add various multiplexed query info in poller-log
* minor cleanup, also fixes a bug which will return duplicate data
* Live query poller stats can now be logged
This also removes in-memory stats that are collected about batched
query execution as the log lines when piped into an monitoring tool
will give us better insights.
* allow poller-log to be configurable
* log minimal information in the livequery-poller-log
Other information can be retrieved from /dev/subscriptions/extended
* fix few review comments
* avoid marshalling and unmarshalling from ByteString to EncJSON
* separate out SubscriberId and SubscriberMetadata
Co-authored-by: Anon Ray <rayanon004@gmail.com>
* Don't compile in developer APIs by default
* Tighten up handling of admin secret, more docs
Store the admin secret only as a hash to prevent leaking the secret
inadvertently, and to prevent timing attacks on the secret.
NOTE: best practice for stored user passwords is a function with a
tunable cost like bcrypt, but our threat model is quite different (even
if we thought we could reasonably protect the secret from an attacker
who could read arbitrary regions of memory), and bcrypt is far too slow
(by design) to perform on each request. We'd have to rely on our
(technically savvy) users to choose high entropy passwords in any case.
Referencing #4736
* server/docs: add instructions to fix loss of float precision in PostgreSQL <= 11 (#5187)
This adds a server flag, --pg-connection-options, that can be used to set a PostgreSQL connection parameter, extra_float_digits, that needs to be used to avoid loss of data on older versions of PostgreSQL, which have odd default behavior when returning float values. (fixes #5092)
* [skip ci] Add new commits from master to the commit diff
* [skip ci] serve default directives (skip & include) over introspection
* [skip ci] Update non-Haskell assets with the version on master
* server: refactor GQL execution check and config API (#5094)
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix js issues in tests by pinning dependencies version
* [skip ci] bump graphql version
* [skip ci] Add note about memory usage
* generalize query execution logic on Postgres (#5110)
* generalize PGExecCtx to support specialized functions for various operations
* fix tests compilation
* allow customising PGExecCtx when starting the web server
* server: changes catalog initialization and logging for pro customization (#5139)
* new typeclass to abstract the logic of QueryLog-ing
* abstract the logic of logging websocket-server logs
introduce a MonadWSLog typeclass
* move catalog initialization to init step
expose a helper function to migrate catalog
create schema cache in initialiseCtx
* expose various modules and functions for pro
* [skip ci] cosmetic change
* [skip ci] fix test calling a mutation that does not exist
* [skip ci] minor text change
* [skip ci] refactored input values
* [skip ci] remove VString Origin
* server: fix updating of headers behaviour in the update cron trigger API and create future events immediately (#5151)
* server: fix bug to update headers in an existing cron trigger and create future events
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Lower stack chunk size in RTS to reduce thread STACK memory (closes #5190)
This reduces memory consumption for new idle subscriptions significantly
(see linked ticket).
The hypothesis is: we fork a lot of threads per websocket, and some of
these use slightly more than the initial 1K stack size, so the first
overflow balloons to 32K, when significantly less is required.
However: running with `+RTS -K1K -xc` did not seem to show evidence of
any overflows! So it's a mystery why this improves things.
GHC should probably also be doubling the stack buffer at each overflow
or doing something even smarter; the knobs we have aren't so helpful.
* [skip ci] fix todo and schema generation for aggregate fields
* 5087 libpq pool leak (#5089)
Shrink libpq buffers to 1MB before returning connection to pool. Closes #5087
See: https://github.com/hasura/pg-client-hs/pull/19
Also related: #3388 #4077
* bump pg-client-hs version (fixes a build issue on some environments) (#5267)
* do not use prepared statements for mutations
* server: unlock scheduled events on graceful shutdown (#4928)
* Fix buggy parsing of new --conn-lifetime flag in 2b0e3774
* [skip ci] remove cherry-picked commit from commit_diff.txt
* server: include additional fields in scheduled trigger webhook payload (#5262)
* include scheduled triggers metadata in the webhook body
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* [skip ci] fix cast exp parser & few TODOs
* [skip ci] fix remote fields arguments
* [skip ci] fix few more TODO, no-op refactor, move resolve/action.hs to execute/action.hs
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix: restrict remote relationship field generation for hasura queries
* [skip ci] no-op refactor; move insert execution code from schema parser module
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] implement header checking
Probably closes #14 and #3659.
* server: refactor 'pollQuery' to have a hook to process 'PollDetails' (#5391)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* update pg-client (#5421)
* [skip ci] update commit_diff
* Fix latency buckets for telemetry data
These must have gotten messed up during a refactor. As a consequence
almost all samples received so far fall into the single erroneous 0 to
1K seconds (originally supposed to be 1ms?) bucket.
I also re-thought what the numbers should be, but these are still
arbitrary and might want adjusting in the future.
* [skip ci] include the latest commit compared against master in commit_diff
* [skip ci] include new commits from master in commit_diff
* [skip ci] improve description generation
* [skip ci] sort all introspect arrays
* [skip ci] allow parsers to specify error codes
* [skip ci] fix integer and float parsing error code
* [skip ci] scalar from json errors are now parse errors
* [skip ci] fixed negative integer error message and code
* [skip ci] Re-fix nullability in relationships
* [skip ci] no-op refactor and removed couple of FIXMEs
* [skip ci] uncomment code in 'deleteMetadataObject'
* [skip ci] Fix re-fix of nullability for relationships
* [skip ci] fix default arguments error code
* [skip ci] updated test error message
!!! WARNING !!!
Since all fields accept `null`, they all are technically optional in
the new schema. Meaning there's no such thing as a missing mandatory
field anymore: a field that doesn't have a default value, and which
therefore isn't labelled as "optional" in the schema, will be assumed
to be null if it's missing, meaning it isn't possible anymore to have
an error for a missing mandatory field. The only possible error is now
when a optional positional argument is omitted but is not the last
positional argument.
* [skip ci] cleanup of int scalar parser
* [skip ci] retro-compatibility of offset as string
* [skip ci] Remove commit from commit_diff.txt
Although strictly speaking we don't know if this will work correctly in PDV
if we would implement query plan caching, the fact is that in the theoretical
case that we would have the same issue in PDV, it would probably apply not just
to introspection, and the fix would be written completely differently. So this
old commit is of no value to us other than the heads-up "make sure query plan
caching works correctly even in the presence of unused variables", which is
already part of the test suite.
* Add MonadTrace and MonadExecuteQuery abstractions (#5383)
* [skip ci] Fix accumulation of input object types
Just like object types, interface types, and union types, we have to avoid
circularities when collecting input types from the GraphQL AST.
Additionally, this fixes equality checks for input object types (whose fields
are unordered, and hence should be compared as sets) and enum types (ditto).
* [skip ci] fix fragment error path
* [skip ci] fix node error code
* [skip ci] fix paths in insert queries
* [skip ci] fix path in objects
* [skip ci] manually alter node id path for consistency
* [skip ci] more node error fixups
* [skip ci] one last relay error message fix
* [skip ci] update commit_diff
* Propagate the trace context to event triggers (#5409)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: log request/response sizes for event triggers (#5463)
* server: log request/response sizes for event triggers
event triggers (and scheduled triggers) now have request/response size
in their logs.
* add changelog entry
* Tracing: Simplify HTTP traced request (#5451)
Remove the Inversion of Control (SuspendRequest) and simplify
the tracing of HTTP Requests.
Co-authored-by: Phil Freeman <phil@hasura.io>
* Attach request ID as tracing metadata (#5456)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* Include the request ID as trace metadata
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
* Typo
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: add logging for action handlers (#5471)
* server: add logging for action handlers
* add changelog entry
* change action-handler log type from internal to non-internal
* fix action-handler-log name
* server: pass http and websocket request to logging context (#5470)
* pass request body to logging context in all cases
* add message size logging on the websocket API
this is required by graphql-engine-pro/#416
* message size logging on websocket API
As we need to log all messages recieved/sent by the websocket server,
it makes sense to log them as part of the websocket server event logs.
Previously message recieved were logged inside the onMessage handler,
and messages sent were logged only for "data" messages (as a server event log)
* fix review comments
Co-authored-by: Phil Freeman <phil@hasura.io>
* server: stop eventing subsystem threads when shutting down (#5479)
* server: stop eventing subsystem threads when shutting down
* Apply suggestions from code review
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
* [skip ci] update commit_diff with new commits added in master
* Bugfix to support 0-size HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE
Also some minor refactoring of bounded cache module:
- the maxBound check in `trim` was confusing and unnecessary
- consequently trim was unnecessary for lookupPure
Also add some basic tests
* Support only the bounded cache, with default HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE of 4000. Closes #5363
* [skip ci] remove merge commit from commit_diff
* server: Fix compiler warning caused by GHC upgrade (#5489)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] update all non server code from master
* [skip ci] aligned object field error message with master
* [skip ci] fix remaining undefined?
* [skip ci] remove unused import
* [skip ci] revert to previous error message, fix tests
* Move nullableType/nonNullableType to Schema.hs
These are functions on Types, not on Parsers.
* [skip ci] fix setup to fix backend only test
the order in which permission checks are performed on the branch is
slightly different than on master, resulting in a slightly different
error if there are no other mutations the user has access to. By
adding update permissions, we go back to the expected case.
* [skip ci] fix insert geojson tests to reflect new paths
* [skip ci] fix enum test for better error message
* [skip ci] fix header test for better error message
* [skip ci] fix fragment cycle test for better error message
* [skip ci] fix error message for type mismatch
* [skip ci] fix variable path in test
* [skip ci] adjust tests after bug fix
* [skip ci] more tests fixing
* Add hdb_catalog.current_setting abstraction for reading Hasura settings
As the comment in the function’s definition explains, this is needed to
work around an awkward Postgres behavior.
* [skip ci] Update CONTRIBUTING.md to mention Node setup for Python tests
* [skip ci] Add missing Python tests env var to CONTRIBUTING.md
* [skip ci] fix order of result when subscription is run with multiple nodes
* [skip ci] no-op refactor: fix a warning in Internal/Parser.hs
* [skip ci] throw error when a subscription contains remote joins
* [skip ci] Enable easier profiling by hiding AssertNF behind a flag
In order to compile a profiling build, run:
$ cabal new-build -f profiling --enable-profiling
* [skip ci] Fix two warnings
We used to lookup the objects that implement a given interface by filtering all
objects in the schema document. However, one of the tests expects us to
generate a warning if the provided `implements` field of an introspection query
specifies an object not implementing some interface. So we use that field
instead.
* [skip ci] Fix warnings by commenting out query plan caching
* [skip ci] improve masking/commenting query caching related code & few warning fixes
* [skip ci] Fixed compiler warnings in graphql-parser-hs
* Sync non-Haskell assets with master
* [skip ci] add a test inserting invalid GraphQL but valid JSON value in a jsonb column
* [skip ci] Avoid converting to/from Map
* [skip ci] Apply some hlint suggestions
* [skip ci] remove redundant constraints from buildLiveQueryPlan and explainGQLQuery
* [skip ci] add NOTEs about missing Tracing constraints in PDV from master
* Remove -fdefer-typed-holes, fix warnings
* Update cabal.project.freeze
* Limit GHC’s heap size to 8GB in CI to avoid the OOM killer
* Commit package-lock.json for Python tests’ remote schema server
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* add test for table_by_pk node when roles doesn't have permission to PK
* [skip ci] fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* [skip ci] test case fix for a6450e126bc2d98bcfd3791501986e4627ce6c6f
* [skip ci] add tests to agg queries when role doesn't have access to any cols
* fix backend test
* Simplify subscription execution
* [skip ci] add test to check if required headers are present while querying
* Suppose, table B is related to table A and to query B certain headers are
necessary, then the test checks that we are throwing error when the header
is not set when B is queried through A
* fix mutations not checking for view mutability
* [skip ci] add variable type checking and corresponding tests
* [skip ci] add test to check if update headers are present while doing an upsert
* [skip ci] add positive counterparts to some of the negative permission tests
* fix args missing their description in introspect
* [skip ci] Remove unused function; insert missing markNotReusable call
* [skip ci] Add a Note about InputValue
* [skip ci] Delete LegacySchema/ 🎉
* [skip ci] Delete GraphQL/{Resolve,Validate}/ 🎉
* [skip ci] Delete top-level Resolve/Validate modules; tidy .cabal file
* [skip ci] Delete LegacySchema top-level module
Somehow I missed this one.
* fix input value to json
* [skip ci] elaborate on JSON objects in GraphQL
* [skip ci] add missing file
* [skip ci] add a test with subscription containing remote joins
* add a test with remote joins in mutation output
* [skip ci] Add some comments to Schema/Mutation.hs
* [skip ci] Remove no longer needed code from RemoteServer.hs
* [skip ci] Use a helper function to generate conflict clause parsers
* [skip ci] fix type checker error in fields with default value
* capitalize the header keys in select_articles_without_required_headers
* Somehow, this was the reason the tests were failing. I have no idea, why!
* [skip ci] Add a long Note about optional fields and nullability
* Improve comments a bit; simplify Schema/Common.hs a bit
* [skip ci] full implementation of 5.8.5 type checking.
* [skip ci] fix validation test teardown
* [skip ci] fix schema stitching test
* fix remote schema ignoring enum nullability
* [skip ci] fix fieldOptional to not discard nullability
* revert nullability of use_spheroid
* fix comment
* add required remote fields with arguments for tests
* [skip ci] add missing docstrings
* [skip ci] fixed description of remote fields
* [skip ci] change docstring for consistency
* fix several schema inconsistencies
* revert behaviour change in function arguments parsing
* fix remaining nullability issues in new schema
* minor no-op refactor; use isListType from graphql-parser-hs
* use nullability of remote schema node, while creating a Remote reln
* fix 'ID' input coercing & action 'ID' type relationship mapping
* include ASTs in MonadExecuteQuery
* needed for PRO code-base
* Delete code for "interfaces implementing ifaces" (draft GraphQL spec)
Previously I started writing some code that adds support for a future GraphQL
feature where interfaces may themselves be sub-types of other interfaces.
However, this code was incomplete, and partially incorrect. So this commit
deletes support for that entirely.
* Ignore a remote schema test during the upgrade/downgrade test
The PDV refactor does a better job at exposing a minimal set of types through
introspection. In particular, not every type that is present in a remote schema
is re-exposed by Hasura. The test
test_schema_stitching.py::TestRemoteSchemaBasic::test_introspection assumed that
all types were re-exposed, which is not required for GraphQL compatibility, in
order to test some aspect of our support for remote schemas.
So while this particular test has been updated on PDV, the PDV branch now does
not pass the old test, which we argue to be incorrect. Hence this test is
disabled while we await a release, after which we can re-enable it.
This also re-enables a test that was previously disabled for similar, though
unrelated, reasons.
* add haddock documentation to the action's field parsers
* Deslecting some tests in server-upgrade
Some tests with current build are failing on server upgrade
which it should not. The response is more accurate than
what it was.
Also the upgrade tests were not throwing errors when the test is
expected to return an error, but succeeds. The test framework is
patched to catch this case.
* [skip ci] Add a long Note about interfaces and object types
* send the response headers back to client after running a query
* Deselect a few more tests during upgrade/downgrade test
* Update commit_diff.txt
* change log kind from db_migrate to catalog_migrate (#5531)
* Show method and complete URI in traced HTTP calls (#5525)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* Fix telemetry reporting of transport (websocket was reported as http)
* add log kinds in cli-migrations image (#5529)
* add log kinds in cli-migrations image
* give hint to resolve timeout error
* minor changes and CHANGELOG
* server: set hasura.tracecontext in RQL mutations [#5542] (#5555)
* server: set hasura.tracecontext in RQL mutations [#5542]
* Update test suite
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Add bulldozer auto-merge and -update configuration
We still need to add the github app (as of time of opening this PR)
Afterwards devs should be able to allow bulldozer to automatically
"update" the branch, merging in parent when it changes, as well as
automatically merge when all checks pass.
This is opt-in by adding the `auto-update-auto-merge` label to the PR.
* Remove 'bulldozer' config, try 'kodiak' for auto-merge
see: https://github.com/chdsbd/kodiak
The main issue that bit us was not being able to auto update forked
branches, also:
https://github.com/palantir/bulldozer/issues/66
https://github.com/palantir/bulldozer/issues/145
* Cherry-picked all commits
* [skip ci] Slightly improve formatting
* Revert "fix introspection query if any enum column present in primary key (fix #5200) (#5522)"
This reverts commit 0f9a5afa59a88f6824f4d63d58db246a5ba3fb03.
This undoes a cherry-pick of 34288e1eb5f2c5dad9e6d1e05453dd52397dc970 that was
already done previously in a6450e126bc2d98bcfd3791501986e4627ce6c6f, and
subsequently fixed for PDV in 70e89dc250f8ddc6e2b7930bbe2b3eeaa6dbe1db
* Do a small bit of tidying in Hasura.GraphQL.Parser.Collect
* Fix cherry-picking work
Some previous cherry-picks ended up modifying code that is commented out
* [skip ci] clarified comment regarding insert representation
* [skip ci] removed obsolete todos
* cosmetic change
* fix action error message
* [skip ci] remove obsolete comment
* [skip ci] synchronize stylish haskell extensions list
* use previously defined scalar names in parsers rather than ad-hoc literals
* Apply most syntax hlint hints.
* Clarify comment on update mutation.
* [skip ci] Clarify what fields should be specified for objects
* Update "_inc" description.
* Use record types rather than tuples fo IntrospectionResult and ParsedIntrospection
* Get rid of checkFieldNamesUnique (use Data.List.Extended.duplicates)
* Throw more errors when collecting query root names
* [skip ci] clean column parser comment
* Remove dead code inserted in ab65b39
* avoid converting to non-empty list where not needed
* add note and TODO about the disabled checks in PDV
* minor refactor in remoteField' function
* Unify two getObject methods
* Nitpicks in Remote.hs
* Update CHANGELOG.md
* Revert "Unify two getObject methods"
This reverts commit bd6bb40355b3d189a46c0312eb52225e18be57b3.
We do need two different getObject functions as the corresponding error message is different
* Fix error message in Remote.hs
* Update CHANGELOG.md
Co-authored-by: Auke Booij <auke@tulcod.com>
* Apply suggested Changelog fix.
Co-authored-by: Auke Booij <auke@tulcod.com>
* Fix typo in Changelog.
* [skip ci] Update changelog.
* reuse type names to avoid duplication
* Fix Hashable instance for Definition
The presence of `Maybe Unique`, and an optional description, as part of
`Definition`s, means that `Definition`s that are considered `Eq`ual may get
different hashes. This can happen, for instance, when one object is memoized
but another is not.
* [skip ci] Update commit_diff.txt
* Bump parser version.
* Bump freeze file after changes in parser.
* [skip ci] Incorporate commits from master
* Fix developer flag in server/cabal.project.freeze
Co-authored-by: Auke Booij <auke@tulcod.com>
* Deselect a changed ENUM test for upgrade/downgrade CI
* Deselect test here as well
* [skip ci] remove dead code
* Disable more tests for upgrade/downgrade
* Fix which test gets deselected
* Revert "Add hdb_catalog.current_setting abstraction for reading Hasura settings"
This reverts commit 66e85ab9fbd56cca2c28a80201f6604fbe811b85.
* Remove circular reference in cabal.project.freeze
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Auke Booij <auke@hasura.io>
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
Co-authored-by: Brandon Simmons <brandon.m.simmons@gmail.com>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
Co-authored-by: Anon Ray <rayanon004@gmail.com>
Co-authored-by: rakeshkky <12475069+rakeshkky@users.noreply.github.com>
Co-authored-by: Anon Ray <ecthiender@users.noreply.github.com>
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Antoine Leblanc <antoine@hasura.io>
Co-authored-by: Brandon Simmons <brandon@hasura.io>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Lyndon Maydwell <lyndon@sordina.net>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Naveen Naidu <naveennaidu479@gmail.com>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Nizar Malangadan <nizar-m@users.noreply.github.com>
Co-authored-by: Antoine Leblanc <crucuny@gmail.com>
Co-authored-by: Auke Booij <auke@tulcod.com>
2020-08-21 20:27:01 +03:00
|
|
|
-- TODO (from master): better naming?
|
2019-11-26 15:14:21 +03:00
|
|
|
data Loggers
|
|
|
|
= Loggers
|
|
|
|
{ _lsLoggerCtx :: !(LoggerCtx Hasura)
|
|
|
|
, _lsLogger :: !(Logger Hasura)
|
|
|
|
, _lsPgLogger :: !Q.PGLogger
|
|
|
|
}
|
|
|
|
|
2020-11-25 13:56:44 +03:00
|
|
|
-- | An application with Postgres database as a metadata storage
|
2021-05-26 19:19:26 +03:00
|
|
|
newtype PGMetadataStorageAppT m a
|
|
|
|
= PGMetadataStorageAppT {runPGMetadataStorageAppT :: (Q.PGPool, Q.PGLogger) -> m a}
|
2020-11-24 09:10:04 +03:00
|
|
|
deriving ( Functor, Applicative, Monad
|
2021-05-26 19:19:26 +03:00
|
|
|
, MonadIO , MonadCatch, MonadThrow, MonadMask
|
|
|
|
, HasHttpManagerM, HasServerConfigCtx
|
2020-12-28 15:56:00 +03:00
|
|
|
, MonadUnique, MonadReader (Q.PGPool, Q.PGLogger)
|
2021-05-26 19:19:26 +03:00
|
|
|
) via (ReaderT (Q.PGPool, Q.PGLogger) m)
|
|
|
|
|
|
|
|
instance MonadTrans PGMetadataStorageAppT where
|
|
|
|
lift = PGMetadataStorageAppT . const
|
|
|
|
|
|
|
|
instance (MonadBase IO m) => MonadBase IO (PGMetadataStorageAppT m) where
|
|
|
|
liftBase io = PGMetadataStorageAppT $ \_ -> liftBase io
|
|
|
|
|
|
|
|
instance (MonadBaseControl IO m) => MonadBaseControl IO (PGMetadataStorageAppT m) where
|
|
|
|
type StM (PGMetadataStorageAppT m) a = StM m a
|
|
|
|
liftBaseWith f = PGMetadataStorageAppT $
|
|
|
|
\r -> liftBaseWith \run -> f (run . flip runPGMetadataStorageAppT r)
|
|
|
|
restoreM stma = PGMetadataStorageAppT $ \_ -> restoreM stma
|
2020-12-28 15:56:00 +03:00
|
|
|
|
|
|
|
resolvePostgresConnInfo
|
|
|
|
:: (MonadIO m) => Env.Environment -> UrlConf -> Maybe Int -> m Q.ConnInfo
|
|
|
|
resolvePostgresConnInfo env dbUrlConf maybeRetries = do
|
|
|
|
dbUrlText <-
|
|
|
|
runExcept (resolveUrlConf env dbUrlConf) `onLeft` \err ->
|
|
|
|
liftIO (printErrExit InvalidDatabaseConnectionParamsError (BLC.unpack $ A.encode err))
|
|
|
|
pure $ Q.ConnInfo retries $ Q.CDDatabaseURI $ txtToBs dbUrlText
|
|
|
|
where
|
|
|
|
retries = fromMaybe 1 maybeRetries
|
2020-11-24 09:10:04 +03:00
|
|
|
|
|
|
|
-- | Initializes or migrates the catalog and returns the context required to start the server.
|
|
|
|
initialiseServeCtx
|
2020-12-21 21:56:00 +03:00
|
|
|
:: (HasVersion, C.ForkableMonadIO m, MonadCatch m)
|
2020-07-14 22:00:58 +03:00
|
|
|
=> Env.Environment
|
2020-11-24 09:10:04 +03:00
|
|
|
-> GlobalCtx
|
|
|
|
-> ServeOptions Hasura
|
2020-12-21 21:56:00 +03:00
|
|
|
-> ManagedT m ServeCtx
|
2020-11-24 09:10:04 +03:00
|
|
|
initialiseServeCtx env GlobalCtx{..} so@ServeOptions{..} = do
|
2019-11-26 15:14:21 +03:00
|
|
|
instanceId <- liftIO generateInstanceId
|
2020-06-03 00:27:14 +03:00
|
|
|
latch <- liftIO newShutdownLatch
|
2020-11-24 09:10:04 +03:00
|
|
|
loggers@(Loggers loggerCtx logger pgLogger) <- mkLoggers soEnabledLogTypes soLogLevel
|
|
|
|
-- log serve options
|
|
|
|
unLogger logger $ serveOptsToLog so
|
2020-12-28 15:56:00 +03:00
|
|
|
|
2020-11-24 09:10:04 +03:00
|
|
|
-- log postgres connection info
|
2020-12-28 15:56:00 +03:00
|
|
|
unLogger logger $ connInfoToLog _gcMetadataDbConnInfo
|
|
|
|
|
|
|
|
metadataDbPool <- liftIO $ Q.initPGPool _gcMetadataDbConnInfo soConnParams pgLogger
|
|
|
|
|
2021-01-07 12:04:22 +03:00
|
|
|
let maybeDefaultSourceConfig = fst _gcDefaultPostgresConnInfo <&> \(dbUrlConf, _) ->
|
|
|
|
let connSettings = PostgresPoolSettings
|
2021-04-28 19:49:23 +03:00
|
|
|
{ _ppsMaxConnections = Just $ Q.cpConns soConnParams
|
|
|
|
, _ppsIdleTimeout = Just $ Q.cpIdleTime soConnParams
|
|
|
|
, _ppsRetries = snd _gcDefaultPostgresConnInfo <|> Just 1
|
|
|
|
, _ppsPoolTimeout = Q.cpTimeout soConnParams
|
|
|
|
, _ppsConnectionLifetime = Q.cpMbLifetime soConnParams
|
2020-12-28 15:56:00 +03:00
|
|
|
}
|
2021-05-21 04:49:50 +03:00
|
|
|
sourceConnInfo = PostgresSourceConnInfo dbUrlConf (Just connSettings) (Q.cpAllowPrepare soConnParams) soTxIso Nothing
|
2021-02-14 09:07:52 +03:00
|
|
|
in PostgresConnConfiguration sourceConnInfo Nothing
|
2021-04-08 11:25:11 +03:00
|
|
|
sqlGenCtx = SQLGenCtx soStringifyNum soDangerousBooleanCollapse
|
2020-11-24 09:10:04 +03:00
|
|
|
|
2021-02-18 19:46:14 +03:00
|
|
|
let serverConfigCtx =
|
[Preview] Inherited roles for postgres read queries
fixes #3868
docker image - `hasura/graphql-engine:inherited-roles-preview-48b73a2de`
Note:
To be able to use the inherited roles feature, the graphql-engine should be started with the env variable `HASURA_GRAPHQL_EXPERIMENTAL_FEATURES` set to `inherited_roles`.
Introduction
------------
This PR implements the idea of multiple roles as presented in this [paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/FGALanguageICDE07.pdf). The multiple roles feature in this PR can be used via inherited roles. An inherited role is a role which can be created by combining multiple singular roles. For example, if there are two roles `author` and `editor` configured in the graphql-engine, then we can create a inherited role with the name of `combined_author_editor` role which will combine the select permissions of the `author` and `editor` roles and then make GraphQL queries using the `combined_author_editor`.
How are select permissions of different roles are combined?
------------------------------------------------------------
A select permission includes 5 things:
1. Columns accessible to the role
2. Row selection filter
3. Limit
4. Allow aggregation
5. Scalar computed fields accessible to the role
Suppose there are two roles, `role1` gives access to the `address` column with row filter `P1` and `role2` gives access to both the `address` and the `phone` column with row filter `P2` and we create a new role `combined_roles` which combines `role1` and `role2`.
Let's say the following GraphQL query is queried with the `combined_roles` role.
```graphql
query {
employees {
address
phone
}
}
```
This will translate to the following SQL query:
```sql
select
(case when (P1 or P2) then address else null end) as address,
(case when P2 then phone else null end) as phone
from employee
where (P1 or P2)
```
The other parameters of the select permission will be combined in the following manner:
1. Limit - Minimum of the limits will be the limit of the inherited role
2. Allow aggregations - If any of the role allows aggregation, then the inherited role will allow aggregation
3. Scalar computed fields - same as table column fields, as in the above example
APIs for inherited roles:
----------------------
1. `add_inherited_role`
`add_inherited_role` is the [metadata API](https://hasura.io/docs/1.0/graphql/core/api-reference/index.html#schema-metadata-api) to create a new inherited role. It accepts two arguments
`role_name`: the name of the inherited role to be added (String)
`role_set`: list of roles that need to be combined (Array of Strings)
Example:
```json
{
"type": "add_inherited_role",
"args": {
"role_name":"combined_user",
"role_set":[
"user",
"user1"
]
}
}
```
After adding the inherited role, the inherited role can be used like single roles like earlier
Note:
An inherited role can only be created with non-inherited/singular roles.
2. `drop_inherited_role`
The `drop_inherited_role` API accepts the name of the inherited role and drops it from the metadata. It accepts a single argument:
`role_name`: name of the inherited role to be dropped
Example:
```json
{
"type": "drop_inherited_role",
"args": {
"role_name":"combined_user"
}
}
```
Metadata
---------
The derived roles metadata will be included under the `experimental_features` key while exporting the metadata.
```json
{
"experimental_features": {
"derived_roles": [
{
"role_name": "manager_is_employee_too",
"role_set": [
"employee",
"manager"
]
}
]
}
}
```
Scope
------
Only postgres queries and subscriptions are supported in this PR.
Important points:
-----------------
1. All columns exposed to an inherited role will be marked as `nullable`, this is done so that cell value nullification can be done.
TODOs
-------
- [ ] Tests
- [ ] Test a GraphQL query running with a inherited role without enabling inherited roles in experimental features
- [] Tests for aggregate queries, limit, computed fields, functions, subscriptions (?)
- [ ] Introspection test with a inherited role (nullability changes in a inherited role)
- [ ] Docs
- [ ] Changelog
Co-authored-by: Vamshi Surabhi <6562944+0x777@users.noreply.github.com>
GitOrigin-RevId: 3b8ee1e11f5ceca80fe294f8c074d42fbccfec63
2021-03-08 14:14:13 +03:00
|
|
|
ServerConfigCtx soInferFunctionPermissions soEnableRemoteSchemaPermissions
|
|
|
|
sqlGenCtx soEnableMaintenanceMode soExperimentalFeatures
|
2021-02-18 19:46:14 +03:00
|
|
|
|
2021-04-06 06:25:02 +03:00
|
|
|
(rebuildableSchemaCache, _) <-
|
2020-12-28 15:56:00 +03:00
|
|
|
lift . flip onException (flushLogger loggerCtx) $
|
2021-01-07 12:04:22 +03:00
|
|
|
migrateCatalogSchema env logger metadataDbPool maybeDefaultSourceConfig _gcHttpManager
|
2021-02-18 19:46:14 +03:00
|
|
|
serverConfigCtx (mkPgSourceResolver pgLogger)
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2021-04-06 06:25:02 +03:00
|
|
|
|
|
|
|
-- Start a background thread for listening schema sync events from other server instances,
|
|
|
|
metaVersionRef <- liftIO $ STM.newEmptyTMVarIO
|
2021-04-07 12:59:48 +03:00
|
|
|
|
|
|
|
-- An interval of 0 indicates that no schema sync is required
|
|
|
|
case soSchemaPollInterval of
|
|
|
|
Skip -> unLogger logger $ mkGenericStrLog LevelInfo "schema-sync" "Schema sync disabled"
|
|
|
|
Interval i -> do
|
|
|
|
unLogger logger $ mkGenericStrLog LevelInfo "schema-sync" ("Schema sync enabled. Polling at " <> show i)
|
|
|
|
void $ startSchemaSyncListenerThread logger metadataDbPool instanceId i metaVersionRef
|
2021-04-06 06:25:02 +03:00
|
|
|
|
2021-02-11 20:54:25 +03:00
|
|
|
-- See Note [Temporarily disabling query plan caching]
|
|
|
|
-- (planCache, schemaCacheRef) <- initialiseCache
|
|
|
|
schemaCacheRef <- initialiseCache rebuildableSchemaCache
|
|
|
|
|
2020-12-28 15:56:00 +03:00
|
|
|
pure $ ServeCtx _gcHttpManager instanceId loggers metadataDbPool latch
|
2021-04-06 06:25:02 +03:00
|
|
|
rebuildableSchemaCache schemaCacheRef metaVersionRef
|
2020-11-24 09:10:04 +03:00
|
|
|
|
|
|
|
mkLoggers
|
2020-12-21 21:56:00 +03:00
|
|
|
:: (MonadIO m, MonadBaseControl IO m)
|
|
|
|
=> HashSet (EngineLogType Hasura)
|
|
|
|
-> LogLevel
|
|
|
|
-> ManagedT m Loggers
|
2020-11-24 09:10:04 +03:00
|
|
|
mkLoggers enabledLogs logLevel = do
|
2020-12-21 21:56:00 +03:00
|
|
|
loggerCtx <- mkLoggerCtx (defaultLoggerSettings True logLevel) enabledLogs
|
2020-11-24 09:10:04 +03:00
|
|
|
let logger = mkLogger loggerCtx
|
|
|
|
pgLogger = mkPGLogger logger
|
|
|
|
return $ Loggers loggerCtx logger pgLogger
|
2019-11-26 15:14:21 +03:00
|
|
|
|
|
|
|
|
2020-06-19 09:42:32 +03:00
|
|
|
-- | helper function to initialize or migrate the @hdb_catalog@ schema (used by pro as well)
|
|
|
|
migrateCatalogSchema
|
2020-12-14 07:30:19 +03:00
|
|
|
:: (HasVersion, MonadIO m, MonadBaseControl IO m)
|
2021-04-22 00:44:37 +03:00
|
|
|
=> Env.Environment -> Logger Hasura -> Q.PGPool -> Maybe (SourceConnConfiguration ('Postgres 'Vanilla))
|
2021-02-18 19:46:14 +03:00
|
|
|
-> HTTP.Manager -> ServerConfigCtx
|
2021-01-29 08:48:17 +03:00
|
|
|
-> SourceResolver
|
2020-12-14 07:30:19 +03:00
|
|
|
-> m (RebuildableSchemaCache, UTCTime)
|
2021-01-29 08:48:17 +03:00
|
|
|
migrateCatalogSchema env logger pool defaultSourceConfig
|
2021-02-18 19:46:14 +03:00
|
|
|
httpManager serverConfigCtx
|
2021-01-29 08:48:17 +03:00
|
|
|
sourceResolver = do
|
2020-06-19 09:42:32 +03:00
|
|
|
currentTime <- liftIO Clock.getCurrentTime
|
2020-12-28 15:56:00 +03:00
|
|
|
initialiseResult <- runExceptT $ do
|
2021-02-18 19:46:14 +03:00
|
|
|
-- 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
|
|
|
|
(migrationResult, metadata) <-
|
|
|
|
Q.runTx pool (Q.Serializable, Just Q.ReadWrite) $
|
|
|
|
migrateCatalog defaultSourceConfig (_sccMaintenanceMode serverConfigCtx)
|
|
|
|
currentTime
|
|
|
|
let cacheBuildParams =
|
2021-01-29 08:48:17 +03:00
|
|
|
CacheBuildParams httpManager sourceResolver serverConfigCtx
|
2021-01-07 12:04:22 +03:00
|
|
|
buildReason = case getMigratedFrom migrationResult of
|
|
|
|
Nothing -> CatalogSync
|
|
|
|
Just version ->
|
|
|
|
-- Catalog version 43 marks the metadata separation which also drops
|
|
|
|
-- the "hdb_views" schema where table event triggers are hosted.
|
|
|
|
-- We need to re-create table event trigger procedures in "hdb_catalog"
|
|
|
|
-- schema when migration happens from version < 43. Build reason
|
|
|
|
-- @'CatalogUpdate' re-creates event triggers in the database.
|
|
|
|
if version < 43 then CatalogUpdate else CatalogSync
|
2020-12-28 15:56:00 +03:00
|
|
|
schemaCache <- runCacheBuild cacheBuildParams $
|
2021-01-07 12:04:22 +03:00
|
|
|
buildRebuildableSchemaCacheWithReason buildReason env metadata
|
2020-12-28 15:56:00 +03:00
|
|
|
pure (migrationResult, schemaCache)
|
2020-06-19 09:42:32 +03:00
|
|
|
|
2020-11-24 09:10:04 +03:00
|
|
|
(migrationResult, schemaCache) <-
|
2020-06-19 09:42:32 +03:00
|
|
|
initialiseResult `onLeft` \err -> do
|
|
|
|
unLogger logger StartupLog
|
|
|
|
{ slLogLevel = LevelError
|
2020-08-05 13:23:14 +03:00
|
|
|
, slKind = "catalog_migrate"
|
2020-06-19 09:42:32 +03:00
|
|
|
, slInfo = A.toJSON err
|
|
|
|
}
|
2020-07-14 22:00:58 +03:00
|
|
|
liftIO (printErrExit DatabaseMigrationError (BLC.unpack $ A.encode err))
|
2020-06-19 09:42:32 +03:00
|
|
|
unLogger logger migrationResult
|
2020-11-24 09:10:04 +03:00
|
|
|
pure (schemaCache, currentTime)
|
2020-06-19 09:42:32 +03:00
|
|
|
|
2020-04-01 18:14:26 +03:00
|
|
|
-- | Run a transaction and if an error is encountered, log the error and abort the program
|
|
|
|
runTxIO :: Q.PGPool -> Q.TxMode -> Q.TxE QErr a -> IO a
|
|
|
|
runTxIO pool isoLevel tx = do
|
|
|
|
eVal <- liftIO $ runExceptT $ Q.runTx pool isoLevel tx
|
2020-10-28 19:40:33 +03:00
|
|
|
onLeft eVal (printErrJExit DatabaseMigrationError)
|
2020-04-01 18:14:26 +03:00
|
|
|
|
2020-06-03 00:27:14 +03:00
|
|
|
-- | A latch for the graceful shutdown of a server process.
|
|
|
|
newtype ShutdownLatch = ShutdownLatch { unShutdownLatch :: C.MVar () }
|
|
|
|
|
2021-05-14 12:38:37 +03:00
|
|
|
-- | 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 (MetadataStorageT IO ())
|
|
|
|
|
2020-06-03 00:27:14 +03:00
|
|
|
newShutdownLatch :: IO ShutdownLatch
|
|
|
|
newShutdownLatch = fmap ShutdownLatch C.newEmptyMVar
|
|
|
|
|
|
|
|
-- | Block the current thread, waiting on the latch.
|
|
|
|
waitForShutdown :: ShutdownLatch -> IO ()
|
|
|
|
waitForShutdown = C.takeMVar . unShutdownLatch
|
|
|
|
|
2020-06-16 18:23:06 +03:00
|
|
|
-- | Initiate a graceful shutdown of the server associated with the provided
|
2020-06-03 00:27:14 +03:00
|
|
|
-- latch.
|
2020-11-24 09:10:04 +03:00
|
|
|
shutdownGracefully :: ShutdownLatch -> IO ()
|
2021-04-19 04:21:34 +03:00
|
|
|
shutdownGracefully = void . flip C.tryPutMVar () . unShutdownLatch
|
2020-06-03 00:27:14 +03:00
|
|
|
|
2020-06-19 09:42:32 +03:00
|
|
|
-- | If an exception is encountered , flush the log buffer and
|
|
|
|
-- rethrow If we do not flush the log buffer on exception, then log lines
|
|
|
|
-- may be missed
|
|
|
|
-- See: https://github.com/hasura/graphql-engine/issues/4772
|
2020-07-14 22:00:58 +03:00
|
|
|
flushLogger :: MonadIO m => LoggerCtx impl -> m ()
|
|
|
|
flushLogger = liftIO . FL.flushLogStr . _lcLoggerSet
|
2020-06-19 09:42:32 +03:00
|
|
|
|
2020-12-02 09:16:05 +03:00
|
|
|
|
2020-12-21 21:56:00 +03:00
|
|
|
-- | 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
|
2020-12-28 15:56:00 +03:00
|
|
|
-- resource leaks.
|
2020-12-21 21:56:00 +03:00
|
|
|
--
|
|
|
|
-- 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.
|
2020-12-02 09:16:05 +03:00
|
|
|
{- HLINT ignore runHGEServer "Avoid lambda" -}
|
2019-11-26 15:14:21 +03:00
|
|
|
runHGEServer
|
2020-12-21 21:56:00 +03:00
|
|
|
:: forall m impl
|
|
|
|
. ( HasVersion
|
2020-01-23 00:55:55 +03:00
|
|
|
, MonadIO m
|
2020-07-14 22:00:58 +03:00
|
|
|
, MonadMask m
|
2019-11-26 15:14:21 +03:00
|
|
|
, MonadStateless IO m
|
2020-06-16 18:23:06 +03:00
|
|
|
, LA.Forall (LA.Pure m)
|
2020-07-15 13:40:48 +03:00
|
|
|
, UserAuthentication (Tracing.TraceT m)
|
2019-11-26 15:14:21 +03:00
|
|
|
, HttpLog m
|
|
|
|
, ConsoleRenderer m
|
2021-01-07 12:04:22 +03:00
|
|
|
, MonadMetadataApiAuthorization m
|
2020-06-16 18:23:06 +03:00
|
|
|
, MonadGQLExecutionCheck m
|
|
|
|
, MonadConfigApiHandler m
|
2020-07-14 22:00:58 +03:00
|
|
|
, MonadQueryLog m
|
2020-06-19 09:42:32 +03:00
|
|
|
, WS.MonadWSLog m
|
2020-07-15 13:40:48 +03:00
|
|
|
, MonadExecuteQuery m
|
|
|
|
, Tracing.HasReporter m
|
2020-12-03 07:06:22 +03:00
|
|
|
, HasResourceLimits m
|
2020-11-25 13:56:44 +03:00
|
|
|
, MonadMetadataStorage (MetadataStorageT m)
|
2020-12-28 15:56:00 +03:00
|
|
|
, MonadResolveSource m
|
2019-11-26 15:14:21 +03:00
|
|
|
)
|
2021-02-13 03:05:23 +03:00
|
|
|
=> (ServerCtx -> Spock.SpockT m ())
|
|
|
|
-> Env.Environment
|
2020-07-14 22:00:58 +03:00
|
|
|
-> ServeOptions impl
|
2020-11-24 09:10:04 +03:00
|
|
|
-> ServeCtx
|
2020-06-16 20:44:59 +03:00
|
|
|
-- and mutations
|
2019-11-26 15:14:21 +03:00
|
|
|
-> UTCTime
|
|
|
|
-- ^ start time
|
2020-07-16 16:19:42 +03:00
|
|
|
-> Maybe EL.LiveQueryPostPollHook
|
2020-12-02 09:16:05 +03:00
|
|
|
-> ServerMetrics
|
2020-08-18 22:53:12 +03:00
|
|
|
-> EKG.Store
|
2020-12-21 21:56:00 +03:00
|
|
|
-> ManagedT m ()
|
2021-02-13 03:05:23 +03:00
|
|
|
runHGEServer setupHook env ServeOptions{..} ServeCtx{..} initTime postPollHook serverMetrics ekgStore = do
|
2020-06-16 20:44:59 +03:00
|
|
|
-- Comment this to enable expensive assertions from "GHC.AssertNF". These
|
|
|
|
-- will log lines to STDOUT containing "not in normal form". In the future we
|
|
|
|
-- could try to integrate this into our tests. For now this is a development
|
|
|
|
-- tool.
|
2020-03-18 04:31:22 +03:00
|
|
|
--
|
|
|
|
-- NOTE: be sure to compile WITHOUT code coverage, for this to work properly.
|
Rewrite GraphQL schema generation and query parsing (close #2801) (#4111)
Aka “the PDV refactor.” History is preserved on the branch 2801-graphql-schema-parser-refactor.
* [skip ci] remove stale benchmark commit from commit_diff
* [skip ci] Check for root field name conflicts between remotes
* [skip ci] Additionally check for conflicts between remotes and DB
* [skip ci] Check for conflicts in schema when tracking a table
* [skip ci] Fix equality checking in GraphQL AST
* server: fix mishandling of GeoJSON inputs in subscriptions (fix #3239) (#4551)
* Add support for multiple top-level fields in a subscription to improve testability of subscriptions
* Add an internal flag to enable multiple subscriptions
* Add missing call to withConstructorFn in live queries (fix #3239)
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
* Scheduled triggers (close #1914) (#3553)
server: add scheduled triggers
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
* dev.sh: bump version due to addition of croniter python dependency
* server: fix an introspection query caching issue (fix #4547) (#4661)
Introspection queries accept variables, but we need to make sure to
also touch the variables that we ignore, so that an introspection
query is marked not reusable if we are not able to build a correct
query plan for it.
A better solution here would be to deal with such unused variables
correctly, so that more introspection queries become reusable.
An even better solution would be to type-safely track *how* to reuse
which variables, rather than to split the reusage marking from the
planning.
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* flush log buffer on exception in mkWaiApp ( fix #4772 ) (#4801)
* flush log buffer on exception in mkWaiApp
* add comment to explain the introduced change
* add changelog
* allow logging details of a live query polling thread (#4959)
* changes for poller-log
add various multiplexed query info in poller-log
* minor cleanup, also fixes a bug which will return duplicate data
* Live query poller stats can now be logged
This also removes in-memory stats that are collected about batched
query execution as the log lines when piped into an monitoring tool
will give us better insights.
* allow poller-log to be configurable
* log minimal information in the livequery-poller-log
Other information can be retrieved from /dev/subscriptions/extended
* fix few review comments
* avoid marshalling and unmarshalling from ByteString to EncJSON
* separate out SubscriberId and SubscriberMetadata
Co-authored-by: Anon Ray <rayanon004@gmail.com>
* Don't compile in developer APIs by default
* Tighten up handling of admin secret, more docs
Store the admin secret only as a hash to prevent leaking the secret
inadvertently, and to prevent timing attacks on the secret.
NOTE: best practice for stored user passwords is a function with a
tunable cost like bcrypt, but our threat model is quite different (even
if we thought we could reasonably protect the secret from an attacker
who could read arbitrary regions of memory), and bcrypt is far too slow
(by design) to perform on each request. We'd have to rely on our
(technically savvy) users to choose high entropy passwords in any case.
Referencing #4736
* server/docs: add instructions to fix loss of float precision in PostgreSQL <= 11 (#5187)
This adds a server flag, --pg-connection-options, that can be used to set a PostgreSQL connection parameter, extra_float_digits, that needs to be used to avoid loss of data on older versions of PostgreSQL, which have odd default behavior when returning float values. (fixes #5092)
* [skip ci] Add new commits from master to the commit diff
* [skip ci] serve default directives (skip & include) over introspection
* [skip ci] Update non-Haskell assets with the version on master
* server: refactor GQL execution check and config API (#5094)
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix js issues in tests by pinning dependencies version
* [skip ci] bump graphql version
* [skip ci] Add note about memory usage
* generalize query execution logic on Postgres (#5110)
* generalize PGExecCtx to support specialized functions for various operations
* fix tests compilation
* allow customising PGExecCtx when starting the web server
* server: changes catalog initialization and logging for pro customization (#5139)
* new typeclass to abstract the logic of QueryLog-ing
* abstract the logic of logging websocket-server logs
introduce a MonadWSLog typeclass
* move catalog initialization to init step
expose a helper function to migrate catalog
create schema cache in initialiseCtx
* expose various modules and functions for pro
* [skip ci] cosmetic change
* [skip ci] fix test calling a mutation that does not exist
* [skip ci] minor text change
* [skip ci] refactored input values
* [skip ci] remove VString Origin
* server: fix updating of headers behaviour in the update cron trigger API and create future events immediately (#5151)
* server: fix bug to update headers in an existing cron trigger and create future events
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Lower stack chunk size in RTS to reduce thread STACK memory (closes #5190)
This reduces memory consumption for new idle subscriptions significantly
(see linked ticket).
The hypothesis is: we fork a lot of threads per websocket, and some of
these use slightly more than the initial 1K stack size, so the first
overflow balloons to 32K, when significantly less is required.
However: running with `+RTS -K1K -xc` did not seem to show evidence of
any overflows! So it's a mystery why this improves things.
GHC should probably also be doubling the stack buffer at each overflow
or doing something even smarter; the knobs we have aren't so helpful.
* [skip ci] fix todo and schema generation for aggregate fields
* 5087 libpq pool leak (#5089)
Shrink libpq buffers to 1MB before returning connection to pool. Closes #5087
See: https://github.com/hasura/pg-client-hs/pull/19
Also related: #3388 #4077
* bump pg-client-hs version (fixes a build issue on some environments) (#5267)
* do not use prepared statements for mutations
* server: unlock scheduled events on graceful shutdown (#4928)
* Fix buggy parsing of new --conn-lifetime flag in 2b0e3774
* [skip ci] remove cherry-picked commit from commit_diff.txt
* server: include additional fields in scheduled trigger webhook payload (#5262)
* include scheduled triggers metadata in the webhook body
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* [skip ci] fix cast exp parser & few TODOs
* [skip ci] fix remote fields arguments
* [skip ci] fix few more TODO, no-op refactor, move resolve/action.hs to execute/action.hs
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix: restrict remote relationship field generation for hasura queries
* [skip ci] no-op refactor; move insert execution code from schema parser module
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] implement header checking
Probably closes #14 and #3659.
* server: refactor 'pollQuery' to have a hook to process 'PollDetails' (#5391)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* update pg-client (#5421)
* [skip ci] update commit_diff
* Fix latency buckets for telemetry data
These must have gotten messed up during a refactor. As a consequence
almost all samples received so far fall into the single erroneous 0 to
1K seconds (originally supposed to be 1ms?) bucket.
I also re-thought what the numbers should be, but these are still
arbitrary and might want adjusting in the future.
* [skip ci] include the latest commit compared against master in commit_diff
* [skip ci] include new commits from master in commit_diff
* [skip ci] improve description generation
* [skip ci] sort all introspect arrays
* [skip ci] allow parsers to specify error codes
* [skip ci] fix integer and float parsing error code
* [skip ci] scalar from json errors are now parse errors
* [skip ci] fixed negative integer error message and code
* [skip ci] Re-fix nullability in relationships
* [skip ci] no-op refactor and removed couple of FIXMEs
* [skip ci] uncomment code in 'deleteMetadataObject'
* [skip ci] Fix re-fix of nullability for relationships
* [skip ci] fix default arguments error code
* [skip ci] updated test error message
!!! WARNING !!!
Since all fields accept `null`, they all are technically optional in
the new schema. Meaning there's no such thing as a missing mandatory
field anymore: a field that doesn't have a default value, and which
therefore isn't labelled as "optional" in the schema, will be assumed
to be null if it's missing, meaning it isn't possible anymore to have
an error for a missing mandatory field. The only possible error is now
when a optional positional argument is omitted but is not the last
positional argument.
* [skip ci] cleanup of int scalar parser
* [skip ci] retro-compatibility of offset as string
* [skip ci] Remove commit from commit_diff.txt
Although strictly speaking we don't know if this will work correctly in PDV
if we would implement query plan caching, the fact is that in the theoretical
case that we would have the same issue in PDV, it would probably apply not just
to introspection, and the fix would be written completely differently. So this
old commit is of no value to us other than the heads-up "make sure query plan
caching works correctly even in the presence of unused variables", which is
already part of the test suite.
* Add MonadTrace and MonadExecuteQuery abstractions (#5383)
* [skip ci] Fix accumulation of input object types
Just like object types, interface types, and union types, we have to avoid
circularities when collecting input types from the GraphQL AST.
Additionally, this fixes equality checks for input object types (whose fields
are unordered, and hence should be compared as sets) and enum types (ditto).
* [skip ci] fix fragment error path
* [skip ci] fix node error code
* [skip ci] fix paths in insert queries
* [skip ci] fix path in objects
* [skip ci] manually alter node id path for consistency
* [skip ci] more node error fixups
* [skip ci] one last relay error message fix
* [skip ci] update commit_diff
* Propagate the trace context to event triggers (#5409)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: log request/response sizes for event triggers (#5463)
* server: log request/response sizes for event triggers
event triggers (and scheduled triggers) now have request/response size
in their logs.
* add changelog entry
* Tracing: Simplify HTTP traced request (#5451)
Remove the Inversion of Control (SuspendRequest) and simplify
the tracing of HTTP Requests.
Co-authored-by: Phil Freeman <phil@hasura.io>
* Attach request ID as tracing metadata (#5456)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* Include the request ID as trace metadata
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
* Typo
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: add logging for action handlers (#5471)
* server: add logging for action handlers
* add changelog entry
* change action-handler log type from internal to non-internal
* fix action-handler-log name
* server: pass http and websocket request to logging context (#5470)
* pass request body to logging context in all cases
* add message size logging on the websocket API
this is required by graphql-engine-pro/#416
* message size logging on websocket API
As we need to log all messages recieved/sent by the websocket server,
it makes sense to log them as part of the websocket server event logs.
Previously message recieved were logged inside the onMessage handler,
and messages sent were logged only for "data" messages (as a server event log)
* fix review comments
Co-authored-by: Phil Freeman <phil@hasura.io>
* server: stop eventing subsystem threads when shutting down (#5479)
* server: stop eventing subsystem threads when shutting down
* Apply suggestions from code review
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
* [skip ci] update commit_diff with new commits added in master
* Bugfix to support 0-size HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE
Also some minor refactoring of bounded cache module:
- the maxBound check in `trim` was confusing and unnecessary
- consequently trim was unnecessary for lookupPure
Also add some basic tests
* Support only the bounded cache, with default HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE of 4000. Closes #5363
* [skip ci] remove merge commit from commit_diff
* server: Fix compiler warning caused by GHC upgrade (#5489)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] update all non server code from master
* [skip ci] aligned object field error message with master
* [skip ci] fix remaining undefined?
* [skip ci] remove unused import
* [skip ci] revert to previous error message, fix tests
* Move nullableType/nonNullableType to Schema.hs
These are functions on Types, not on Parsers.
* [skip ci] fix setup to fix backend only test
the order in which permission checks are performed on the branch is
slightly different than on master, resulting in a slightly different
error if there are no other mutations the user has access to. By
adding update permissions, we go back to the expected case.
* [skip ci] fix insert geojson tests to reflect new paths
* [skip ci] fix enum test for better error message
* [skip ci] fix header test for better error message
* [skip ci] fix fragment cycle test for better error message
* [skip ci] fix error message for type mismatch
* [skip ci] fix variable path in test
* [skip ci] adjust tests after bug fix
* [skip ci] more tests fixing
* Add hdb_catalog.current_setting abstraction for reading Hasura settings
As the comment in the function’s definition explains, this is needed to
work around an awkward Postgres behavior.
* [skip ci] Update CONTRIBUTING.md to mention Node setup for Python tests
* [skip ci] Add missing Python tests env var to CONTRIBUTING.md
* [skip ci] fix order of result when subscription is run with multiple nodes
* [skip ci] no-op refactor: fix a warning in Internal/Parser.hs
* [skip ci] throw error when a subscription contains remote joins
* [skip ci] Enable easier profiling by hiding AssertNF behind a flag
In order to compile a profiling build, run:
$ cabal new-build -f profiling --enable-profiling
* [skip ci] Fix two warnings
We used to lookup the objects that implement a given interface by filtering all
objects in the schema document. However, one of the tests expects us to
generate a warning if the provided `implements` field of an introspection query
specifies an object not implementing some interface. So we use that field
instead.
* [skip ci] Fix warnings by commenting out query plan caching
* [skip ci] improve masking/commenting query caching related code & few warning fixes
* [skip ci] Fixed compiler warnings in graphql-parser-hs
* Sync non-Haskell assets with master
* [skip ci] add a test inserting invalid GraphQL but valid JSON value in a jsonb column
* [skip ci] Avoid converting to/from Map
* [skip ci] Apply some hlint suggestions
* [skip ci] remove redundant constraints from buildLiveQueryPlan and explainGQLQuery
* [skip ci] add NOTEs about missing Tracing constraints in PDV from master
* Remove -fdefer-typed-holes, fix warnings
* Update cabal.project.freeze
* Limit GHC’s heap size to 8GB in CI to avoid the OOM killer
* Commit package-lock.json for Python tests’ remote schema server
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* add test for table_by_pk node when roles doesn't have permission to PK
* [skip ci] fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* [skip ci] test case fix for a6450e126bc2d98bcfd3791501986e4627ce6c6f
* [skip ci] add tests to agg queries when role doesn't have access to any cols
* fix backend test
* Simplify subscription execution
* [skip ci] add test to check if required headers are present while querying
* Suppose, table B is related to table A and to query B certain headers are
necessary, then the test checks that we are throwing error when the header
is not set when B is queried through A
* fix mutations not checking for view mutability
* [skip ci] add variable type checking and corresponding tests
* [skip ci] add test to check if update headers are present while doing an upsert
* [skip ci] add positive counterparts to some of the negative permission tests
* fix args missing their description in introspect
* [skip ci] Remove unused function; insert missing markNotReusable call
* [skip ci] Add a Note about InputValue
* [skip ci] Delete LegacySchema/ 🎉
* [skip ci] Delete GraphQL/{Resolve,Validate}/ 🎉
* [skip ci] Delete top-level Resolve/Validate modules; tidy .cabal file
* [skip ci] Delete LegacySchema top-level module
Somehow I missed this one.
* fix input value to json
* [skip ci] elaborate on JSON objects in GraphQL
* [skip ci] add missing file
* [skip ci] add a test with subscription containing remote joins
* add a test with remote joins in mutation output
* [skip ci] Add some comments to Schema/Mutation.hs
* [skip ci] Remove no longer needed code from RemoteServer.hs
* [skip ci] Use a helper function to generate conflict clause parsers
* [skip ci] fix type checker error in fields with default value
* capitalize the header keys in select_articles_without_required_headers
* Somehow, this was the reason the tests were failing. I have no idea, why!
* [skip ci] Add a long Note about optional fields and nullability
* Improve comments a bit; simplify Schema/Common.hs a bit
* [skip ci] full implementation of 5.8.5 type checking.
* [skip ci] fix validation test teardown
* [skip ci] fix schema stitching test
* fix remote schema ignoring enum nullability
* [skip ci] fix fieldOptional to not discard nullability
* revert nullability of use_spheroid
* fix comment
* add required remote fields with arguments for tests
* [skip ci] add missing docstrings
* [skip ci] fixed description of remote fields
* [skip ci] change docstring for consistency
* fix several schema inconsistencies
* revert behaviour change in function arguments parsing
* fix remaining nullability issues in new schema
* minor no-op refactor; use isListType from graphql-parser-hs
* use nullability of remote schema node, while creating a Remote reln
* fix 'ID' input coercing & action 'ID' type relationship mapping
* include ASTs in MonadExecuteQuery
* needed for PRO code-base
* Delete code for "interfaces implementing ifaces" (draft GraphQL spec)
Previously I started writing some code that adds support for a future GraphQL
feature where interfaces may themselves be sub-types of other interfaces.
However, this code was incomplete, and partially incorrect. So this commit
deletes support for that entirely.
* Ignore a remote schema test during the upgrade/downgrade test
The PDV refactor does a better job at exposing a minimal set of types through
introspection. In particular, not every type that is present in a remote schema
is re-exposed by Hasura. The test
test_schema_stitching.py::TestRemoteSchemaBasic::test_introspection assumed that
all types were re-exposed, which is not required for GraphQL compatibility, in
order to test some aspect of our support for remote schemas.
So while this particular test has been updated on PDV, the PDV branch now does
not pass the old test, which we argue to be incorrect. Hence this test is
disabled while we await a release, after which we can re-enable it.
This also re-enables a test that was previously disabled for similar, though
unrelated, reasons.
* add haddock documentation to the action's field parsers
* Deslecting some tests in server-upgrade
Some tests with current build are failing on server upgrade
which it should not. The response is more accurate than
what it was.
Also the upgrade tests were not throwing errors when the test is
expected to return an error, but succeeds. The test framework is
patched to catch this case.
* [skip ci] Add a long Note about interfaces and object types
* send the response headers back to client after running a query
* Deselect a few more tests during upgrade/downgrade test
* Update commit_diff.txt
* change log kind from db_migrate to catalog_migrate (#5531)
* Show method and complete URI in traced HTTP calls (#5525)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* Fix telemetry reporting of transport (websocket was reported as http)
* add log kinds in cli-migrations image (#5529)
* add log kinds in cli-migrations image
* give hint to resolve timeout error
* minor changes and CHANGELOG
* server: set hasura.tracecontext in RQL mutations [#5542] (#5555)
* server: set hasura.tracecontext in RQL mutations [#5542]
* Update test suite
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Add bulldozer auto-merge and -update configuration
We still need to add the github app (as of time of opening this PR)
Afterwards devs should be able to allow bulldozer to automatically
"update" the branch, merging in parent when it changes, as well as
automatically merge when all checks pass.
This is opt-in by adding the `auto-update-auto-merge` label to the PR.
* Remove 'bulldozer' config, try 'kodiak' for auto-merge
see: https://github.com/chdsbd/kodiak
The main issue that bit us was not being able to auto update forked
branches, also:
https://github.com/palantir/bulldozer/issues/66
https://github.com/palantir/bulldozer/issues/145
* Cherry-picked all commits
* [skip ci] Slightly improve formatting
* Revert "fix introspection query if any enum column present in primary key (fix #5200) (#5522)"
This reverts commit 0f9a5afa59a88f6824f4d63d58db246a5ba3fb03.
This undoes a cherry-pick of 34288e1eb5f2c5dad9e6d1e05453dd52397dc970 that was
already done previously in a6450e126bc2d98bcfd3791501986e4627ce6c6f, and
subsequently fixed for PDV in 70e89dc250f8ddc6e2b7930bbe2b3eeaa6dbe1db
* Do a small bit of tidying in Hasura.GraphQL.Parser.Collect
* Fix cherry-picking work
Some previous cherry-picks ended up modifying code that is commented out
* [skip ci] clarified comment regarding insert representation
* [skip ci] removed obsolete todos
* cosmetic change
* fix action error message
* [skip ci] remove obsolete comment
* [skip ci] synchronize stylish haskell extensions list
* use previously defined scalar names in parsers rather than ad-hoc literals
* Apply most syntax hlint hints.
* Clarify comment on update mutation.
* [skip ci] Clarify what fields should be specified for objects
* Update "_inc" description.
* Use record types rather than tuples fo IntrospectionResult and ParsedIntrospection
* Get rid of checkFieldNamesUnique (use Data.List.Extended.duplicates)
* Throw more errors when collecting query root names
* [skip ci] clean column parser comment
* Remove dead code inserted in ab65b39
* avoid converting to non-empty list where not needed
* add note and TODO about the disabled checks in PDV
* minor refactor in remoteField' function
* Unify two getObject methods
* Nitpicks in Remote.hs
* Update CHANGELOG.md
* Revert "Unify two getObject methods"
This reverts commit bd6bb40355b3d189a46c0312eb52225e18be57b3.
We do need two different getObject functions as the corresponding error message is different
* Fix error message in Remote.hs
* Update CHANGELOG.md
Co-authored-by: Auke Booij <auke@tulcod.com>
* Apply suggested Changelog fix.
Co-authored-by: Auke Booij <auke@tulcod.com>
* Fix typo in Changelog.
* [skip ci] Update changelog.
* reuse type names to avoid duplication
* Fix Hashable instance for Definition
The presence of `Maybe Unique`, and an optional description, as part of
`Definition`s, means that `Definition`s that are considered `Eq`ual may get
different hashes. This can happen, for instance, when one object is memoized
but another is not.
* [skip ci] Update commit_diff.txt
* Bump parser version.
* Bump freeze file after changes in parser.
* [skip ci] Incorporate commits from master
* Fix developer flag in server/cabal.project.freeze
Co-authored-by: Auke Booij <auke@tulcod.com>
* Deselect a changed ENUM test for upgrade/downgrade CI
* Deselect test here as well
* [skip ci] remove dead code
* Disable more tests for upgrade/downgrade
* Fix which test gets deselected
* Revert "Add hdb_catalog.current_setting abstraction for reading Hasura settings"
This reverts commit 66e85ab9fbd56cca2c28a80201f6604fbe811b85.
* Remove circular reference in cabal.project.freeze
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Auke Booij <auke@hasura.io>
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
Co-authored-by: Brandon Simmons <brandon.m.simmons@gmail.com>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
Co-authored-by: Anon Ray <rayanon004@gmail.com>
Co-authored-by: rakeshkky <12475069+rakeshkky@users.noreply.github.com>
Co-authored-by: Anon Ray <ecthiender@users.noreply.github.com>
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Antoine Leblanc <antoine@hasura.io>
Co-authored-by: Brandon Simmons <brandon@hasura.io>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Lyndon Maydwell <lyndon@sordina.net>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Naveen Naidu <naveennaidu479@gmail.com>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Nizar Malangadan <nizar-m@users.noreply.github.com>
Co-authored-by: Antoine Leblanc <crucuny@gmail.com>
Co-authored-by: Auke Booij <auke@tulcod.com>
2020-08-21 20:27:01 +03:00
|
|
|
#ifndef PROFILING
|
2020-03-18 04:31:22 +03:00
|
|
|
liftIO disableAssertNF
|
Rewrite GraphQL schema generation and query parsing (close #2801) (#4111)
Aka “the PDV refactor.” History is preserved on the branch 2801-graphql-schema-parser-refactor.
* [skip ci] remove stale benchmark commit from commit_diff
* [skip ci] Check for root field name conflicts between remotes
* [skip ci] Additionally check for conflicts between remotes and DB
* [skip ci] Check for conflicts in schema when tracking a table
* [skip ci] Fix equality checking in GraphQL AST
* server: fix mishandling of GeoJSON inputs in subscriptions (fix #3239) (#4551)
* Add support for multiple top-level fields in a subscription to improve testability of subscriptions
* Add an internal flag to enable multiple subscriptions
* Add missing call to withConstructorFn in live queries (fix #3239)
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
* Scheduled triggers (close #1914) (#3553)
server: add scheduled triggers
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
* dev.sh: bump version due to addition of croniter python dependency
* server: fix an introspection query caching issue (fix #4547) (#4661)
Introspection queries accept variables, but we need to make sure to
also touch the variables that we ignore, so that an introspection
query is marked not reusable if we are not able to build a correct
query plan for it.
A better solution here would be to deal with such unused variables
correctly, so that more introspection queries become reusable.
An even better solution would be to type-safely track *how* to reuse
which variables, rather than to split the reusage marking from the
planning.
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* flush log buffer on exception in mkWaiApp ( fix #4772 ) (#4801)
* flush log buffer on exception in mkWaiApp
* add comment to explain the introduced change
* add changelog
* allow logging details of a live query polling thread (#4959)
* changes for poller-log
add various multiplexed query info in poller-log
* minor cleanup, also fixes a bug which will return duplicate data
* Live query poller stats can now be logged
This also removes in-memory stats that are collected about batched
query execution as the log lines when piped into an monitoring tool
will give us better insights.
* allow poller-log to be configurable
* log minimal information in the livequery-poller-log
Other information can be retrieved from /dev/subscriptions/extended
* fix few review comments
* avoid marshalling and unmarshalling from ByteString to EncJSON
* separate out SubscriberId and SubscriberMetadata
Co-authored-by: Anon Ray <rayanon004@gmail.com>
* Don't compile in developer APIs by default
* Tighten up handling of admin secret, more docs
Store the admin secret only as a hash to prevent leaking the secret
inadvertently, and to prevent timing attacks on the secret.
NOTE: best practice for stored user passwords is a function with a
tunable cost like bcrypt, but our threat model is quite different (even
if we thought we could reasonably protect the secret from an attacker
who could read arbitrary regions of memory), and bcrypt is far too slow
(by design) to perform on each request. We'd have to rely on our
(technically savvy) users to choose high entropy passwords in any case.
Referencing #4736
* server/docs: add instructions to fix loss of float precision in PostgreSQL <= 11 (#5187)
This adds a server flag, --pg-connection-options, that can be used to set a PostgreSQL connection parameter, extra_float_digits, that needs to be used to avoid loss of data on older versions of PostgreSQL, which have odd default behavior when returning float values. (fixes #5092)
* [skip ci] Add new commits from master to the commit diff
* [skip ci] serve default directives (skip & include) over introspection
* [skip ci] Update non-Haskell assets with the version on master
* server: refactor GQL execution check and config API (#5094)
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix js issues in tests by pinning dependencies version
* [skip ci] bump graphql version
* [skip ci] Add note about memory usage
* generalize query execution logic on Postgres (#5110)
* generalize PGExecCtx to support specialized functions for various operations
* fix tests compilation
* allow customising PGExecCtx when starting the web server
* server: changes catalog initialization and logging for pro customization (#5139)
* new typeclass to abstract the logic of QueryLog-ing
* abstract the logic of logging websocket-server logs
introduce a MonadWSLog typeclass
* move catalog initialization to init step
expose a helper function to migrate catalog
create schema cache in initialiseCtx
* expose various modules and functions for pro
* [skip ci] cosmetic change
* [skip ci] fix test calling a mutation that does not exist
* [skip ci] minor text change
* [skip ci] refactored input values
* [skip ci] remove VString Origin
* server: fix updating of headers behaviour in the update cron trigger API and create future events immediately (#5151)
* server: fix bug to update headers in an existing cron trigger and create future events
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Lower stack chunk size in RTS to reduce thread STACK memory (closes #5190)
This reduces memory consumption for new idle subscriptions significantly
(see linked ticket).
The hypothesis is: we fork a lot of threads per websocket, and some of
these use slightly more than the initial 1K stack size, so the first
overflow balloons to 32K, when significantly less is required.
However: running with `+RTS -K1K -xc` did not seem to show evidence of
any overflows! So it's a mystery why this improves things.
GHC should probably also be doubling the stack buffer at each overflow
or doing something even smarter; the knobs we have aren't so helpful.
* [skip ci] fix todo and schema generation for aggregate fields
* 5087 libpq pool leak (#5089)
Shrink libpq buffers to 1MB before returning connection to pool. Closes #5087
See: https://github.com/hasura/pg-client-hs/pull/19
Also related: #3388 #4077
* bump pg-client-hs version (fixes a build issue on some environments) (#5267)
* do not use prepared statements for mutations
* server: unlock scheduled events on graceful shutdown (#4928)
* Fix buggy parsing of new --conn-lifetime flag in 2b0e3774
* [skip ci] remove cherry-picked commit from commit_diff.txt
* server: include additional fields in scheduled trigger webhook payload (#5262)
* include scheduled triggers metadata in the webhook body
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* [skip ci] fix cast exp parser & few TODOs
* [skip ci] fix remote fields arguments
* [skip ci] fix few more TODO, no-op refactor, move resolve/action.hs to execute/action.hs
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix: restrict remote relationship field generation for hasura queries
* [skip ci] no-op refactor; move insert execution code from schema parser module
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] implement header checking
Probably closes #14 and #3659.
* server: refactor 'pollQuery' to have a hook to process 'PollDetails' (#5391)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* update pg-client (#5421)
* [skip ci] update commit_diff
* Fix latency buckets for telemetry data
These must have gotten messed up during a refactor. As a consequence
almost all samples received so far fall into the single erroneous 0 to
1K seconds (originally supposed to be 1ms?) bucket.
I also re-thought what the numbers should be, but these are still
arbitrary and might want adjusting in the future.
* [skip ci] include the latest commit compared against master in commit_diff
* [skip ci] include new commits from master in commit_diff
* [skip ci] improve description generation
* [skip ci] sort all introspect arrays
* [skip ci] allow parsers to specify error codes
* [skip ci] fix integer and float parsing error code
* [skip ci] scalar from json errors are now parse errors
* [skip ci] fixed negative integer error message and code
* [skip ci] Re-fix nullability in relationships
* [skip ci] no-op refactor and removed couple of FIXMEs
* [skip ci] uncomment code in 'deleteMetadataObject'
* [skip ci] Fix re-fix of nullability for relationships
* [skip ci] fix default arguments error code
* [skip ci] updated test error message
!!! WARNING !!!
Since all fields accept `null`, they all are technically optional in
the new schema. Meaning there's no such thing as a missing mandatory
field anymore: a field that doesn't have a default value, and which
therefore isn't labelled as "optional" in the schema, will be assumed
to be null if it's missing, meaning it isn't possible anymore to have
an error for a missing mandatory field. The only possible error is now
when a optional positional argument is omitted but is not the last
positional argument.
* [skip ci] cleanup of int scalar parser
* [skip ci] retro-compatibility of offset as string
* [skip ci] Remove commit from commit_diff.txt
Although strictly speaking we don't know if this will work correctly in PDV
if we would implement query plan caching, the fact is that in the theoretical
case that we would have the same issue in PDV, it would probably apply not just
to introspection, and the fix would be written completely differently. So this
old commit is of no value to us other than the heads-up "make sure query plan
caching works correctly even in the presence of unused variables", which is
already part of the test suite.
* Add MonadTrace and MonadExecuteQuery abstractions (#5383)
* [skip ci] Fix accumulation of input object types
Just like object types, interface types, and union types, we have to avoid
circularities when collecting input types from the GraphQL AST.
Additionally, this fixes equality checks for input object types (whose fields
are unordered, and hence should be compared as sets) and enum types (ditto).
* [skip ci] fix fragment error path
* [skip ci] fix node error code
* [skip ci] fix paths in insert queries
* [skip ci] fix path in objects
* [skip ci] manually alter node id path for consistency
* [skip ci] more node error fixups
* [skip ci] one last relay error message fix
* [skip ci] update commit_diff
* Propagate the trace context to event triggers (#5409)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: log request/response sizes for event triggers (#5463)
* server: log request/response sizes for event triggers
event triggers (and scheduled triggers) now have request/response size
in their logs.
* add changelog entry
* Tracing: Simplify HTTP traced request (#5451)
Remove the Inversion of Control (SuspendRequest) and simplify
the tracing of HTTP Requests.
Co-authored-by: Phil Freeman <phil@hasura.io>
* Attach request ID as tracing metadata (#5456)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* Include the request ID as trace metadata
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
* Typo
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: add logging for action handlers (#5471)
* server: add logging for action handlers
* add changelog entry
* change action-handler log type from internal to non-internal
* fix action-handler-log name
* server: pass http and websocket request to logging context (#5470)
* pass request body to logging context in all cases
* add message size logging on the websocket API
this is required by graphql-engine-pro/#416
* message size logging on websocket API
As we need to log all messages recieved/sent by the websocket server,
it makes sense to log them as part of the websocket server event logs.
Previously message recieved were logged inside the onMessage handler,
and messages sent were logged only for "data" messages (as a server event log)
* fix review comments
Co-authored-by: Phil Freeman <phil@hasura.io>
* server: stop eventing subsystem threads when shutting down (#5479)
* server: stop eventing subsystem threads when shutting down
* Apply suggestions from code review
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
* [skip ci] update commit_diff with new commits added in master
* Bugfix to support 0-size HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE
Also some minor refactoring of bounded cache module:
- the maxBound check in `trim` was confusing and unnecessary
- consequently trim was unnecessary for lookupPure
Also add some basic tests
* Support only the bounded cache, with default HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE of 4000. Closes #5363
* [skip ci] remove merge commit from commit_diff
* server: Fix compiler warning caused by GHC upgrade (#5489)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] update all non server code from master
* [skip ci] aligned object field error message with master
* [skip ci] fix remaining undefined?
* [skip ci] remove unused import
* [skip ci] revert to previous error message, fix tests
* Move nullableType/nonNullableType to Schema.hs
These are functions on Types, not on Parsers.
* [skip ci] fix setup to fix backend only test
the order in which permission checks are performed on the branch is
slightly different than on master, resulting in a slightly different
error if there are no other mutations the user has access to. By
adding update permissions, we go back to the expected case.
* [skip ci] fix insert geojson tests to reflect new paths
* [skip ci] fix enum test for better error message
* [skip ci] fix header test for better error message
* [skip ci] fix fragment cycle test for better error message
* [skip ci] fix error message for type mismatch
* [skip ci] fix variable path in test
* [skip ci] adjust tests after bug fix
* [skip ci] more tests fixing
* Add hdb_catalog.current_setting abstraction for reading Hasura settings
As the comment in the function’s definition explains, this is needed to
work around an awkward Postgres behavior.
* [skip ci] Update CONTRIBUTING.md to mention Node setup for Python tests
* [skip ci] Add missing Python tests env var to CONTRIBUTING.md
* [skip ci] fix order of result when subscription is run with multiple nodes
* [skip ci] no-op refactor: fix a warning in Internal/Parser.hs
* [skip ci] throw error when a subscription contains remote joins
* [skip ci] Enable easier profiling by hiding AssertNF behind a flag
In order to compile a profiling build, run:
$ cabal new-build -f profiling --enable-profiling
* [skip ci] Fix two warnings
We used to lookup the objects that implement a given interface by filtering all
objects in the schema document. However, one of the tests expects us to
generate a warning if the provided `implements` field of an introspection query
specifies an object not implementing some interface. So we use that field
instead.
* [skip ci] Fix warnings by commenting out query plan caching
* [skip ci] improve masking/commenting query caching related code & few warning fixes
* [skip ci] Fixed compiler warnings in graphql-parser-hs
* Sync non-Haskell assets with master
* [skip ci] add a test inserting invalid GraphQL but valid JSON value in a jsonb column
* [skip ci] Avoid converting to/from Map
* [skip ci] Apply some hlint suggestions
* [skip ci] remove redundant constraints from buildLiveQueryPlan and explainGQLQuery
* [skip ci] add NOTEs about missing Tracing constraints in PDV from master
* Remove -fdefer-typed-holes, fix warnings
* Update cabal.project.freeze
* Limit GHC’s heap size to 8GB in CI to avoid the OOM killer
* Commit package-lock.json for Python tests’ remote schema server
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* add test for table_by_pk node when roles doesn't have permission to PK
* [skip ci] fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* [skip ci] test case fix for a6450e126bc2d98bcfd3791501986e4627ce6c6f
* [skip ci] add tests to agg queries when role doesn't have access to any cols
* fix backend test
* Simplify subscription execution
* [skip ci] add test to check if required headers are present while querying
* Suppose, table B is related to table A and to query B certain headers are
necessary, then the test checks that we are throwing error when the header
is not set when B is queried through A
* fix mutations not checking for view mutability
* [skip ci] add variable type checking and corresponding tests
* [skip ci] add test to check if update headers are present while doing an upsert
* [skip ci] add positive counterparts to some of the negative permission tests
* fix args missing their description in introspect
* [skip ci] Remove unused function; insert missing markNotReusable call
* [skip ci] Add a Note about InputValue
* [skip ci] Delete LegacySchema/ 🎉
* [skip ci] Delete GraphQL/{Resolve,Validate}/ 🎉
* [skip ci] Delete top-level Resolve/Validate modules; tidy .cabal file
* [skip ci] Delete LegacySchema top-level module
Somehow I missed this one.
* fix input value to json
* [skip ci] elaborate on JSON objects in GraphQL
* [skip ci] add missing file
* [skip ci] add a test with subscription containing remote joins
* add a test with remote joins in mutation output
* [skip ci] Add some comments to Schema/Mutation.hs
* [skip ci] Remove no longer needed code from RemoteServer.hs
* [skip ci] Use a helper function to generate conflict clause parsers
* [skip ci] fix type checker error in fields with default value
* capitalize the header keys in select_articles_without_required_headers
* Somehow, this was the reason the tests were failing. I have no idea, why!
* [skip ci] Add a long Note about optional fields and nullability
* Improve comments a bit; simplify Schema/Common.hs a bit
* [skip ci] full implementation of 5.8.5 type checking.
* [skip ci] fix validation test teardown
* [skip ci] fix schema stitching test
* fix remote schema ignoring enum nullability
* [skip ci] fix fieldOptional to not discard nullability
* revert nullability of use_spheroid
* fix comment
* add required remote fields with arguments for tests
* [skip ci] add missing docstrings
* [skip ci] fixed description of remote fields
* [skip ci] change docstring for consistency
* fix several schema inconsistencies
* revert behaviour change in function arguments parsing
* fix remaining nullability issues in new schema
* minor no-op refactor; use isListType from graphql-parser-hs
* use nullability of remote schema node, while creating a Remote reln
* fix 'ID' input coercing & action 'ID' type relationship mapping
* include ASTs in MonadExecuteQuery
* needed for PRO code-base
* Delete code for "interfaces implementing ifaces" (draft GraphQL spec)
Previously I started writing some code that adds support for a future GraphQL
feature where interfaces may themselves be sub-types of other interfaces.
However, this code was incomplete, and partially incorrect. So this commit
deletes support for that entirely.
* Ignore a remote schema test during the upgrade/downgrade test
The PDV refactor does a better job at exposing a minimal set of types through
introspection. In particular, not every type that is present in a remote schema
is re-exposed by Hasura. The test
test_schema_stitching.py::TestRemoteSchemaBasic::test_introspection assumed that
all types were re-exposed, which is not required for GraphQL compatibility, in
order to test some aspect of our support for remote schemas.
So while this particular test has been updated on PDV, the PDV branch now does
not pass the old test, which we argue to be incorrect. Hence this test is
disabled while we await a release, after which we can re-enable it.
This also re-enables a test that was previously disabled for similar, though
unrelated, reasons.
* add haddock documentation to the action's field parsers
* Deslecting some tests in server-upgrade
Some tests with current build are failing on server upgrade
which it should not. The response is more accurate than
what it was.
Also the upgrade tests were not throwing errors when the test is
expected to return an error, but succeeds. The test framework is
patched to catch this case.
* [skip ci] Add a long Note about interfaces and object types
* send the response headers back to client after running a query
* Deselect a few more tests during upgrade/downgrade test
* Update commit_diff.txt
* change log kind from db_migrate to catalog_migrate (#5531)
* Show method and complete URI in traced HTTP calls (#5525)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* Fix telemetry reporting of transport (websocket was reported as http)
* add log kinds in cli-migrations image (#5529)
* add log kinds in cli-migrations image
* give hint to resolve timeout error
* minor changes and CHANGELOG
* server: set hasura.tracecontext in RQL mutations [#5542] (#5555)
* server: set hasura.tracecontext in RQL mutations [#5542]
* Update test suite
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Add bulldozer auto-merge and -update configuration
We still need to add the github app (as of time of opening this PR)
Afterwards devs should be able to allow bulldozer to automatically
"update" the branch, merging in parent when it changes, as well as
automatically merge when all checks pass.
This is opt-in by adding the `auto-update-auto-merge` label to the PR.
* Remove 'bulldozer' config, try 'kodiak' for auto-merge
see: https://github.com/chdsbd/kodiak
The main issue that bit us was not being able to auto update forked
branches, also:
https://github.com/palantir/bulldozer/issues/66
https://github.com/palantir/bulldozer/issues/145
* Cherry-picked all commits
* [skip ci] Slightly improve formatting
* Revert "fix introspection query if any enum column present in primary key (fix #5200) (#5522)"
This reverts commit 0f9a5afa59a88f6824f4d63d58db246a5ba3fb03.
This undoes a cherry-pick of 34288e1eb5f2c5dad9e6d1e05453dd52397dc970 that was
already done previously in a6450e126bc2d98bcfd3791501986e4627ce6c6f, and
subsequently fixed for PDV in 70e89dc250f8ddc6e2b7930bbe2b3eeaa6dbe1db
* Do a small bit of tidying in Hasura.GraphQL.Parser.Collect
* Fix cherry-picking work
Some previous cherry-picks ended up modifying code that is commented out
* [skip ci] clarified comment regarding insert representation
* [skip ci] removed obsolete todos
* cosmetic change
* fix action error message
* [skip ci] remove obsolete comment
* [skip ci] synchronize stylish haskell extensions list
* use previously defined scalar names in parsers rather than ad-hoc literals
* Apply most syntax hlint hints.
* Clarify comment on update mutation.
* [skip ci] Clarify what fields should be specified for objects
* Update "_inc" description.
* Use record types rather than tuples fo IntrospectionResult and ParsedIntrospection
* Get rid of checkFieldNamesUnique (use Data.List.Extended.duplicates)
* Throw more errors when collecting query root names
* [skip ci] clean column parser comment
* Remove dead code inserted in ab65b39
* avoid converting to non-empty list where not needed
* add note and TODO about the disabled checks in PDV
* minor refactor in remoteField' function
* Unify two getObject methods
* Nitpicks in Remote.hs
* Update CHANGELOG.md
* Revert "Unify two getObject methods"
This reverts commit bd6bb40355b3d189a46c0312eb52225e18be57b3.
We do need two different getObject functions as the corresponding error message is different
* Fix error message in Remote.hs
* Update CHANGELOG.md
Co-authored-by: Auke Booij <auke@tulcod.com>
* Apply suggested Changelog fix.
Co-authored-by: Auke Booij <auke@tulcod.com>
* Fix typo in Changelog.
* [skip ci] Update changelog.
* reuse type names to avoid duplication
* Fix Hashable instance for Definition
The presence of `Maybe Unique`, and an optional description, as part of
`Definition`s, means that `Definition`s that are considered `Eq`ual may get
different hashes. This can happen, for instance, when one object is memoized
but another is not.
* [skip ci] Update commit_diff.txt
* Bump parser version.
* Bump freeze file after changes in parser.
* [skip ci] Incorporate commits from master
* Fix developer flag in server/cabal.project.freeze
Co-authored-by: Auke Booij <auke@tulcod.com>
* Deselect a changed ENUM test for upgrade/downgrade CI
* Deselect test here as well
* [skip ci] remove dead code
* Disable more tests for upgrade/downgrade
* Fix which test gets deselected
* Revert "Add hdb_catalog.current_setting abstraction for reading Hasura settings"
This reverts commit 66e85ab9fbd56cca2c28a80201f6604fbe811b85.
* Remove circular reference in cabal.project.freeze
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Auke Booij <auke@hasura.io>
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
Co-authored-by: Brandon Simmons <brandon.m.simmons@gmail.com>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
Co-authored-by: Anon Ray <rayanon004@gmail.com>
Co-authored-by: rakeshkky <12475069+rakeshkky@users.noreply.github.com>
Co-authored-by: Anon Ray <ecthiender@users.noreply.github.com>
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Antoine Leblanc <antoine@hasura.io>
Co-authored-by: Brandon Simmons <brandon@hasura.io>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Lyndon Maydwell <lyndon@sordina.net>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Naveen Naidu <naveennaidu479@gmail.com>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Nizar Malangadan <nizar-m@users.noreply.github.com>
Co-authored-by: Antoine Leblanc <crucuny@gmail.com>
Co-authored-by: Auke Booij <auke@tulcod.com>
2020-08-21 20:27:01 +03:00
|
|
|
#endif
|
2020-03-18 04:31:22 +03:00
|
|
|
|
2021-04-08 11:25:11 +03:00
|
|
|
let sqlGenCtx = SQLGenCtx soStringifyNum soDangerousBooleanCollapse
|
2020-11-24 09:10:04 +03:00
|
|
|
Loggers loggerCtx logger _ = _scLoggers
|
2021-04-06 06:25:02 +03:00
|
|
|
--SchemaSyncCtx{..} = _scSchemaSyncCtx
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2020-05-19 17:48:49 +03:00
|
|
|
authModeRes <- runExceptT $ setupAuthMode soAdminSecret soAuthHook soJwtSecret soUnAuthRole
|
2020-11-24 09:10:04 +03:00
|
|
|
_scHttpManager logger
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2020-10-28 19:40:33 +03:00
|
|
|
authMode <- onLeft authModeRes (printErrExit AuthConfigurationError . T.unpack)
|
2020-07-14 22:00:58 +03:00
|
|
|
|
2021-03-31 13:39:01 +03:00
|
|
|
HasuraApp app cacheRef actionSubState stopWsServer <- lift $ flip onException (flushLogger loggerCtx) $
|
2021-02-13 03:05:23 +03:00
|
|
|
mkWaiApp setupHook env
|
2020-04-24 10:55:51 +03:00
|
|
|
logger
|
|
|
|
sqlGenCtx
|
|
|
|
soEnableAllowlist
|
2020-11-24 09:10:04 +03:00
|
|
|
_scHttpManager
|
2020-04-24 10:55:51 +03:00
|
|
|
authMode
|
|
|
|
soCorsConfig
|
|
|
|
soEnableConsole
|
|
|
|
soConsoleAssetsDir
|
|
|
|
soEnableTelemetry
|
2020-11-24 09:10:04 +03:00
|
|
|
_scInstanceId
|
2020-04-24 10:55:51 +03:00
|
|
|
soEnabledAPIs
|
|
|
|
soLiveQueryOpts
|
|
|
|
soPlanCacheOptions
|
|
|
|
soResponseInternalErrorsConfig
|
2020-07-16 16:19:42 +03:00
|
|
|
postPollHook
|
2021-02-11 20:54:25 +03:00
|
|
|
_scSchemaCacheRef
|
2020-08-18 22:53:12 +03:00
|
|
|
ekgStore
|
2021-04-29 13:31:09 +03:00
|
|
|
serverMetrics
|
2020-12-21 12:11:37 +03:00
|
|
|
soEnableRemoteSchemaPermissions
|
2021-01-29 08:48:17 +03:00
|
|
|
soInferFunctionPermissions
|
2020-10-12 12:14:23 +03:00
|
|
|
soConnectionOptions
|
2020-11-12 12:25:48 +03:00
|
|
|
soWebsocketKeepAlive
|
2021-02-18 19:46:14 +03:00
|
|
|
soEnableMaintenanceMode
|
[Preview] Inherited roles for postgres read queries
fixes #3868
docker image - `hasura/graphql-engine:inherited-roles-preview-48b73a2de`
Note:
To be able to use the inherited roles feature, the graphql-engine should be started with the env variable `HASURA_GRAPHQL_EXPERIMENTAL_FEATURES` set to `inherited_roles`.
Introduction
------------
This PR implements the idea of multiple roles as presented in this [paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/FGALanguageICDE07.pdf). The multiple roles feature in this PR can be used via inherited roles. An inherited role is a role which can be created by combining multiple singular roles. For example, if there are two roles `author` and `editor` configured in the graphql-engine, then we can create a inherited role with the name of `combined_author_editor` role which will combine the select permissions of the `author` and `editor` roles and then make GraphQL queries using the `combined_author_editor`.
How are select permissions of different roles are combined?
------------------------------------------------------------
A select permission includes 5 things:
1. Columns accessible to the role
2. Row selection filter
3. Limit
4. Allow aggregation
5. Scalar computed fields accessible to the role
Suppose there are two roles, `role1` gives access to the `address` column with row filter `P1` and `role2` gives access to both the `address` and the `phone` column with row filter `P2` and we create a new role `combined_roles` which combines `role1` and `role2`.
Let's say the following GraphQL query is queried with the `combined_roles` role.
```graphql
query {
employees {
address
phone
}
}
```
This will translate to the following SQL query:
```sql
select
(case when (P1 or P2) then address else null end) as address,
(case when P2 then phone else null end) as phone
from employee
where (P1 or P2)
```
The other parameters of the select permission will be combined in the following manner:
1. Limit - Minimum of the limits will be the limit of the inherited role
2. Allow aggregations - If any of the role allows aggregation, then the inherited role will allow aggregation
3. Scalar computed fields - same as table column fields, as in the above example
APIs for inherited roles:
----------------------
1. `add_inherited_role`
`add_inherited_role` is the [metadata API](https://hasura.io/docs/1.0/graphql/core/api-reference/index.html#schema-metadata-api) to create a new inherited role. It accepts two arguments
`role_name`: the name of the inherited role to be added (String)
`role_set`: list of roles that need to be combined (Array of Strings)
Example:
```json
{
"type": "add_inherited_role",
"args": {
"role_name":"combined_user",
"role_set":[
"user",
"user1"
]
}
}
```
After adding the inherited role, the inherited role can be used like single roles like earlier
Note:
An inherited role can only be created with non-inherited/singular roles.
2. `drop_inherited_role`
The `drop_inherited_role` API accepts the name of the inherited role and drops it from the metadata. It accepts a single argument:
`role_name`: name of the inherited role to be dropped
Example:
```json
{
"type": "drop_inherited_role",
"args": {
"role_name":"combined_user"
}
}
```
Metadata
---------
The derived roles metadata will be included under the `experimental_features` key while exporting the metadata.
```json
{
"experimental_features": {
"derived_roles": [
{
"role_name": "manager_is_employee_too",
"role_set": [
"employee",
"manager"
]
}
]
}
}
```
Scope
------
Only postgres queries and subscriptions are supported in this PR.
Important points:
-----------------
1. All columns exposed to an inherited role will be marked as `nullable`, this is done so that cell value nullification can be done.
TODOs
-------
- [ ] Tests
- [ ] Test a GraphQL query running with a inherited role without enabling inherited roles in experimental features
- [] Tests for aggregate queries, limit, computed fields, functions, subscriptions (?)
- [ ] Introspection test with a inherited role (nullability changes in a inherited role)
- [ ] Docs
- [ ] Changelog
Co-authored-by: Vamshi Surabhi <6562944+0x777@users.noreply.github.com>
GitOrigin-RevId: 3b8ee1e11f5ceca80fe294f8c074d42fbccfec63
2021-03-08 14:14:13 +03:00
|
|
|
soExperimentalFeatures
|
2021-02-18 19:46:14 +03:00
|
|
|
|
|
|
|
let serverConfigCtx =
|
[Preview] Inherited roles for postgres read queries
fixes #3868
docker image - `hasura/graphql-engine:inherited-roles-preview-48b73a2de`
Note:
To be able to use the inherited roles feature, the graphql-engine should be started with the env variable `HASURA_GRAPHQL_EXPERIMENTAL_FEATURES` set to `inherited_roles`.
Introduction
------------
This PR implements the idea of multiple roles as presented in this [paper](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/FGALanguageICDE07.pdf). The multiple roles feature in this PR can be used via inherited roles. An inherited role is a role which can be created by combining multiple singular roles. For example, if there are two roles `author` and `editor` configured in the graphql-engine, then we can create a inherited role with the name of `combined_author_editor` role which will combine the select permissions of the `author` and `editor` roles and then make GraphQL queries using the `combined_author_editor`.
How are select permissions of different roles are combined?
------------------------------------------------------------
A select permission includes 5 things:
1. Columns accessible to the role
2. Row selection filter
3. Limit
4. Allow aggregation
5. Scalar computed fields accessible to the role
Suppose there are two roles, `role1` gives access to the `address` column with row filter `P1` and `role2` gives access to both the `address` and the `phone` column with row filter `P2` and we create a new role `combined_roles` which combines `role1` and `role2`.
Let's say the following GraphQL query is queried with the `combined_roles` role.
```graphql
query {
employees {
address
phone
}
}
```
This will translate to the following SQL query:
```sql
select
(case when (P1 or P2) then address else null end) as address,
(case when P2 then phone else null end) as phone
from employee
where (P1 or P2)
```
The other parameters of the select permission will be combined in the following manner:
1. Limit - Minimum of the limits will be the limit of the inherited role
2. Allow aggregations - If any of the role allows aggregation, then the inherited role will allow aggregation
3. Scalar computed fields - same as table column fields, as in the above example
APIs for inherited roles:
----------------------
1. `add_inherited_role`
`add_inherited_role` is the [metadata API](https://hasura.io/docs/1.0/graphql/core/api-reference/index.html#schema-metadata-api) to create a new inherited role. It accepts two arguments
`role_name`: the name of the inherited role to be added (String)
`role_set`: list of roles that need to be combined (Array of Strings)
Example:
```json
{
"type": "add_inherited_role",
"args": {
"role_name":"combined_user",
"role_set":[
"user",
"user1"
]
}
}
```
After adding the inherited role, the inherited role can be used like single roles like earlier
Note:
An inherited role can only be created with non-inherited/singular roles.
2. `drop_inherited_role`
The `drop_inherited_role` API accepts the name of the inherited role and drops it from the metadata. It accepts a single argument:
`role_name`: name of the inherited role to be dropped
Example:
```json
{
"type": "drop_inherited_role",
"args": {
"role_name":"combined_user"
}
}
```
Metadata
---------
The derived roles metadata will be included under the `experimental_features` key while exporting the metadata.
```json
{
"experimental_features": {
"derived_roles": [
{
"role_name": "manager_is_employee_too",
"role_set": [
"employee",
"manager"
]
}
]
}
}
```
Scope
------
Only postgres queries and subscriptions are supported in this PR.
Important points:
-----------------
1. All columns exposed to an inherited role will be marked as `nullable`, this is done so that cell value nullification can be done.
TODOs
-------
- [ ] Tests
- [ ] Test a GraphQL query running with a inherited role without enabling inherited roles in experimental features
- [] Tests for aggregate queries, limit, computed fields, functions, subscriptions (?)
- [ ] Introspection test with a inherited role (nullability changes in a inherited role)
- [ ] Docs
- [ ] Changelog
Co-authored-by: Vamshi Surabhi <6562944+0x777@users.noreply.github.com>
GitOrigin-RevId: 3b8ee1e11f5ceca80fe294f8c074d42fbccfec63
2021-03-08 14:14:13 +03:00
|
|
|
ServerConfigCtx soInferFunctionPermissions
|
|
|
|
soEnableRemoteSchemaPermissions
|
|
|
|
sqlGenCtx
|
|
|
|
soEnableMaintenanceMode
|
|
|
|
soExperimentalFeatures
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2021-05-25 13:49:59 +03:00
|
|
|
-- Log Warning if deprecated environment variables are used
|
|
|
|
sources <- scSources <$> liftIO (getSCFromRef cacheRef)
|
|
|
|
liftIO $ logDeprecatedEnvVars logger env sources
|
|
|
|
|
2019-11-26 15:14:21 +03:00
|
|
|
-- log inconsistent schema objects
|
|
|
|
inconsObjs <- scInconsistentObjs <$> liftIO (getSCFromRef cacheRef)
|
2019-11-20 21:21:30 +03:00
|
|
|
liftIO $ logInconsObjs logger inconsObjs
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2020-11-24 09:10:04 +03:00
|
|
|
-- Start a background thread for processing schema sync event present in the '_sscSyncEventRef'
|
2021-04-06 06:25:02 +03:00
|
|
|
_ <- startSchemaSyncProcessorThread logger _scHttpManager _scMetaVersionRef
|
|
|
|
cacheRef _scInstanceId
|
2021-02-18 19:46:14 +03:00
|
|
|
serverConfigCtx
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2020-07-14 22:00:58 +03:00
|
|
|
let
|
|
|
|
maxEvThrds = fromMaybe defaultMaxEventThreads soEventsHttpPoolSize
|
|
|
|
fetchI = milliseconds $ fromMaybe (Milliseconds defaultFetchInterval) soEventsFetchInterval
|
|
|
|
logEnvHeaders = soLogHeadersFromEnv
|
2021-04-22 00:44:37 +03:00
|
|
|
allPgSources = mapMaybe (unsafeSourceConfiguration @('Postgres 'Vanilla)) $ HM.elems $ scSources $ lastBuiltSchemaCache _scSchemaCache
|
2021-05-27 09:51:19 +03:00
|
|
|
eventResponseLogBehaviour = if soDevMode then LogEntireResponse else LogSanitisedResponse
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2021-05-14 12:38:37 +03:00
|
|
|
lockedEventsCtx <-
|
|
|
|
liftIO $
|
|
|
|
LockedEventsCtx
|
|
|
|
<$> STM.newTVarIO mempty
|
|
|
|
<*> STM.newTVarIO mempty
|
|
|
|
<*> STM.newTVarIO mempty
|
|
|
|
<*> STM.newTVarIO mempty
|
2021-04-27 20:22:54 +03:00
|
|
|
|
|
|
|
unless (getNonNegativeInt soEventsFetchBatchSize == 0 || soEventsFetchInterval == Just 0) $ do
|
|
|
|
-- Don't start the events poller thread when fetchBatchSize or fetchInterval is 0
|
|
|
|
-- prepare event triggers data
|
|
|
|
eventEngineCtx <- liftIO $ atomically $ initEventEngineCtx maxEvThrds fetchI soEventsFetchBatchSize
|
2021-05-14 12:38:37 +03:00
|
|
|
let eventsGracefulShutdownAction =
|
|
|
|
waitForProcessingAction logger
|
|
|
|
"event_triggers"
|
|
|
|
(length <$> readTVarIO (leEvents lockedEventsCtx))
|
|
|
|
(EventTriggerShutdownAction (shutdownEventTriggerEvents allPgSources logger lockedEventsCtx))
|
|
|
|
soGracefulShutdownTimeout
|
2021-04-27 20:22:54 +03:00
|
|
|
unLogger logger $ mkGenericStrLog LevelInfo "event_triggers" "starting workers"
|
2021-05-14 12:38:37 +03:00
|
|
|
void $
|
|
|
|
C.forkManagedTWithGracefulShutdown
|
|
|
|
"processEventQueue"
|
|
|
|
logger
|
|
|
|
(C.ThreadShutdown (liftIO eventsGracefulShutdownAction)) $
|
|
|
|
processEventQueue logger
|
|
|
|
logEnvHeaders
|
|
|
|
_scHttpManager
|
|
|
|
(getSCFromRef cacheRef)
|
|
|
|
eventEngineCtx
|
|
|
|
lockedEventsCtx
|
|
|
|
serverMetrics
|
|
|
|
soEnableMaintenanceMode
|
|
|
|
eventResponseLogBehaviour
|
|
|
|
|
|
|
|
|
|
|
|
-- start a background thread to handle async actions
|
2021-03-31 13:39:01 +03:00
|
|
|
case soAsyncActionsFetchInterval of
|
2021-04-07 12:59:48 +03:00
|
|
|
Skip -> pure () -- Don't start the poller thread
|
|
|
|
Interval sleepTime -> do
|
2021-05-14 12:38:37 +03:00
|
|
|
let label = "asyncActionsProcessor"
|
|
|
|
asyncActionGracefulShutdownAction =
|
|
|
|
(liftWithStateless \lowerIO ->
|
|
|
|
(waitForProcessingAction logger
|
|
|
|
"async_actions"
|
|
|
|
(length <$> readTVarIO (leActionEvents lockedEventsCtx))
|
|
|
|
(MetadataDBShutdownAction (hoist lowerIO (shutdownAsyncActions lockedEventsCtx)))
|
|
|
|
soGracefulShutdownTimeout))
|
|
|
|
|
|
|
|
void $ C.forkManagedTWithGracefulShutdown label
|
|
|
|
logger
|
|
|
|
(C.ThreadShutdown asyncActionGracefulShutdownAction) $
|
|
|
|
asyncActionsProcessor env logger (_scrCache cacheRef)
|
|
|
|
(leActionEvents lockedEventsCtx) _scHttpManager sleepTime
|
|
|
|
|
|
|
|
|
|
|
|
-- start a background thread to handle async action live queries
|
2021-03-31 13:39:01 +03:00
|
|
|
_asyncActionsSubThread <- C.forkManagedT "asyncActionSubscriptionsProcessor" logger $
|
|
|
|
asyncActionSubscriptionsProcessor actionSubState
|
2020-02-13 20:38:23 +03:00
|
|
|
|
2020-05-13 15:33:16 +03:00
|
|
|
-- start a background thread to create new cron events
|
2020-12-21 21:56:00 +03:00
|
|
|
_cronEventsThread <- C.forkManagedT "runCronEventsGenerator" logger $
|
2020-11-25 13:56:44 +03:00
|
|
|
runCronEventsGenerator logger (getSCFromRef cacheRef)
|
2020-05-13 15:33:16 +03:00
|
|
|
|
2020-07-02 14:57:09 +03:00
|
|
|
-- prepare scheduled triggers
|
2020-12-21 21:56:00 +03:00
|
|
|
lift $ prepareScheduledEvents logger
|
2020-07-02 14:57:09 +03:00
|
|
|
|
2020-05-13 15:33:16 +03:00
|
|
|
-- start a background thread to deliver the scheduled events
|
2021-05-14 12:38:37 +03:00
|
|
|
_scheduledEventsThread <- do
|
|
|
|
let scheduledEventsGracefulShutdownAction =
|
|
|
|
(liftWithStateless \lowerIO ->
|
|
|
|
(waitForProcessingAction logger
|
|
|
|
"scheduled_events"
|
|
|
|
(getProcessingScheduledEventsCount lockedEventsCtx)
|
|
|
|
(MetadataDBShutdownAction (hoist lowerIO unlockAllLockedScheduledEvents))
|
|
|
|
soGracefulShutdownTimeout))
|
|
|
|
|
|
|
|
C.forkManagedTWithGracefulShutdown "processScheduledTriggers"
|
|
|
|
logger
|
|
|
|
(C.ThreadShutdown scheduledEventsGracefulShutdownAction) $
|
|
|
|
processScheduledTriggers env logger logEnvHeaders _scHttpManager
|
|
|
|
(getSCFromRef cacheRef) lockedEventsCtx
|
|
|
|
eventResponseLogBehaviour
|
|
|
|
|
2020-05-13 15:33:16 +03:00
|
|
|
|
2019-11-26 15:14:21 +03:00
|
|
|
-- start a background thread to check for updates
|
2021-05-14 12:38:37 +03:00
|
|
|
_updateThread <- C.forkManagedT "checkForUpdates" logger $
|
|
|
|
liftIO $ checkForUpdates loggerCtx _scHttpManager
|
2019-11-26 15:14:21 +03:00
|
|
|
|
|
|
|
-- start a background thread for telemetry
|
2021-01-07 12:04:22 +03:00
|
|
|
dbUidE <- runMetadataStorageT getDatabaseUid
|
2020-12-21 21:56:00 +03:00
|
|
|
_telemetryThread <- if soEnableTelemetry
|
2020-07-30 05:34:50 +03:00
|
|
|
then do
|
2020-12-21 21:56:00 +03:00
|
|
|
lift . unLogger logger $ mkGenericStrLog LevelInfo "telemetry" telemetryNotice
|
2020-07-30 05:34:50 +03:00
|
|
|
|
2020-12-28 15:56:00 +03:00
|
|
|
(dbId, pgVersion) <- liftIO $ runTxIO _scMetadataDbPool (Q.ReadCommitted, Nothing) $
|
2021-01-07 12:04:22 +03:00
|
|
|
(,) <$> liftEither dbUidE <*> getPgVersion
|
2020-07-30 05:34:50 +03:00
|
|
|
|
2021-05-14 12:38:37 +03:00
|
|
|
telemetryThread <- C.forkManagedT "runTelemetry" logger $
|
|
|
|
liftIO $ runTelemetry logger _scHttpManager (getSCFromRef cacheRef) dbId _scInstanceId pgVersion
|
2020-07-30 05:34:50 +03:00
|
|
|
return $ Just telemetryThread
|
|
|
|
else return Nothing
|
|
|
|
|
2019-11-26 15:14:21 +03:00
|
|
|
finishTime <- liftIO Clock.getCurrentTime
|
|
|
|
let apiInitTime = realToFrac $ Clock.diffUTCTime finishTime initTime
|
|
|
|
unLogger logger $
|
|
|
|
mkGenericLog LevelInfo "server" $ StartupTimeInfo "starting API server" apiInitTime
|
2020-11-25 13:56:44 +03:00
|
|
|
|
2020-12-02 09:16:05 +03:00
|
|
|
let setForkIOWithMetrics :: Warp.Settings -> Warp.Settings
|
|
|
|
setForkIOWithMetrics = Warp.setFork \f -> do
|
|
|
|
void $ C.forkIOWithUnmask (\unmask ->
|
2020-12-14 07:30:19 +03:00
|
|
|
bracket_
|
2020-12-02 09:16:05 +03:00
|
|
|
(EKG.Gauge.inc $ smWarpThreads serverMetrics)
|
|
|
|
(EKG.Gauge.dec $ smWarpThreads serverMetrics)
|
|
|
|
(f unmask))
|
2020-12-28 15:56:00 +03:00
|
|
|
|
2020-12-21 21:56:00 +03:00
|
|
|
let shutdownHandler closeSocket = LA.link =<< LA.async do
|
|
|
|
waitForShutdown _scShutdownLatch
|
|
|
|
unLogger logger $ mkGenericStrLog LevelInfo "server" "gracefully shutting down server"
|
|
|
|
closeSocket
|
2020-12-28 15:56:00 +03:00
|
|
|
|
2020-04-14 09:01:50 +03:00
|
|
|
let warpSettings = Warp.setPort soPort
|
|
|
|
. Warp.setHost soHost
|
|
|
|
. Warp.setGracefulShutdownTimeout (Just 30) -- 30s graceful shutdown
|
2020-12-21 21:56:00 +03:00
|
|
|
. Warp.setInstallShutdownHandler shutdownHandler
|
2020-12-02 09:16:05 +03:00
|
|
|
. setForkIOWithMetrics
|
2020-04-14 09:01:50 +03:00
|
|
|
$ Warp.defaultSettings
|
2020-12-28 15:56:00 +03:00
|
|
|
|
2020-12-21 21:56:00 +03:00
|
|
|
-- Here we block until the shutdown latch 'MVar' is filled, and then
|
|
|
|
-- shut down the server. Once this blocking call returns, we'll tidy up
|
|
|
|
-- any resources using the finalizers attached using 'ManagedT' above.
|
2020-12-28 15:56:00 +03:00
|
|
|
-- Structuring things using the shutdown latch in this way lets us decide
|
2020-12-21 21:56:00 +03:00
|
|
|
-- elsewhere exactly how we want to control shutdown.
|
|
|
|
liftIO $ Warp.runSettings warpSettings app `LE.finally` do
|
|
|
|
-- These cleanup actions are not directly associated with any
|
|
|
|
-- resource, but we still need to make sure we clean them up here.
|
|
|
|
stopWsServer
|
2019-11-26 15:14:21 +03:00
|
|
|
|
|
|
|
where
|
2020-07-30 22:33:43 +03:00
|
|
|
-- | prepareScheduledEvents is a function to unlock all the scheduled trigger
|
2020-10-07 11:55:39 +03:00
|
|
|
-- events that are locked and unprocessed, which is called while hasura is
|
2020-07-30 22:33:43 +03:00
|
|
|
-- started.
|
|
|
|
--
|
2020-04-14 09:01:50 +03:00
|
|
|
-- Locked and unprocessed events can occur in 2 ways
|
|
|
|
-- 1.
|
|
|
|
-- Hasura's shutdown was not graceful in which all the fetched
|
|
|
|
-- events will remain locked and unprocessed(TODO: clean shutdown)
|
|
|
|
-- state.
|
|
|
|
-- 2.
|
|
|
|
-- There is another hasura instance which is processing events and
|
|
|
|
-- it will lock events to process them.
|
|
|
|
-- So, unlocking all the locked events might re-deliver an event(due to #2).
|
2020-11-25 13:56:44 +03:00
|
|
|
prepareScheduledEvents (Logger logger) = do
|
2020-07-02 14:57:09 +03:00
|
|
|
liftIO $ logger $ mkGenericStrLog LevelInfo "scheduled_triggers" "preparing data"
|
2020-11-25 13:56:44 +03:00
|
|
|
res <- runMetadataStorageT unlockAllLockedScheduledEvents
|
|
|
|
onLeft res $ printErrJExit EventSubSystemError
|
2020-07-02 14:57:09 +03:00
|
|
|
|
2021-05-14 12:38:37 +03:00
|
|
|
getProcessingScheduledEventsCount :: LockedEventsCtx -> IO Int
|
|
|
|
getProcessingScheduledEventsCount LockedEventsCtx {..} = do
|
|
|
|
processingCronEvents <- readTVarIO leCronEvents
|
|
|
|
processingOneOffEvents <- readTVarIO leOneOffEvents
|
|
|
|
return $ length processingOneOffEvents + length processingCronEvents
|
|
|
|
|
|
|
|
-- | shutdownEventTriggerEvents will be triggered when a graceful shutdown has been inititiated, it will
|
2020-07-02 14:57:09 +03:00
|
|
|
-- get the locked events from the event engine context and the scheduled event engine context
|
|
|
|
-- then it will unlock all those events.
|
2020-04-14 09:01:50 +03:00
|
|
|
-- It may happen that an event may be processed more than one time, an event that has been already
|
2021-05-14 12:38:37 +03:00
|
|
|
-- processed but not been marked as delivered in the db will be unlocked by `shutdownEventTriggerEvents`
|
2020-04-14 09:01:50 +03:00
|
|
|
-- and will be processed when the events are proccessed next time.
|
2021-05-14 12:38:37 +03:00
|
|
|
shutdownEventTriggerEvents
|
2021-04-22 00:44:37 +03:00
|
|
|
:: [SourceConfig ('Postgres 'Vanilla)]
|
2020-07-02 14:57:09 +03:00
|
|
|
-> Logger Hasura
|
|
|
|
-> LockedEventsCtx
|
|
|
|
-> IO ()
|
2021-05-14 12:38:37 +03:00
|
|
|
shutdownEventTriggerEvents pgSources hasuraLogger@(Logger logger) LockedEventsCtx {..} = do
|
|
|
|
-- TODO: is this correct?
|
|
|
|
-- event triggers should be tied to the life cycle of a source
|
2020-12-28 15:56:00 +03:00
|
|
|
forM_ pgSources $ \pgSource -> do
|
|
|
|
logger $ mkGenericStrLog LevelInfo "event_triggers" "unlocking events that are locked by the HGE"
|
|
|
|
let unlockEvents' l = MetadataStorageT $ runLazyTx (_pscExecCtx pgSource) Q.ReadWrite $ liftTx $ unlockEvents l
|
|
|
|
unlockEventsForShutdown hasuraLogger "event_triggers" "" unlockEvents' leEvents
|
|
|
|
|
2021-05-14 12:38:37 +03:00
|
|
|
shutdownAsyncActions
|
|
|
|
:: LockedEventsCtx
|
|
|
|
-> MetadataStorageT m ()
|
|
|
|
shutdownAsyncActions lockedEventsCtx = do
|
|
|
|
lockedActionEvents <- liftIO $ readTVarIO $ leActionEvents lockedEventsCtx
|
|
|
|
setProcessingActionLogsToPending (LockedActionIdArray $ toList lockedActionEvents)
|
2020-07-02 14:57:09 +03:00
|
|
|
|
|
|
|
unlockEventsForShutdown
|
2020-11-25 13:56:44 +03:00
|
|
|
:: Logger Hasura
|
2020-07-02 14:57:09 +03:00
|
|
|
-> Text -- ^ trigger type
|
|
|
|
-> Text -- ^ event type
|
2020-11-25 13:56:44 +03:00
|
|
|
-> ([eventId] -> MetadataStorageT IO Int)
|
2020-07-02 14:57:09 +03:00
|
|
|
-> TVar (Set.Set eventId)
|
|
|
|
-> IO ()
|
2020-11-25 13:56:44 +03:00
|
|
|
unlockEventsForShutdown (Logger logger) triggerType eventType doUnlock lockedIdsVar = do
|
2021-05-14 12:38:37 +03:00
|
|
|
logger $ mkGenericStrLog LevelInfo "scheduled_triggers" "unlocking scheduled events that are locked by the HGE"
|
2020-07-02 14:57:09 +03:00
|
|
|
lockedIds <- readTVarIO lockedIdsVar
|
2020-07-30 05:34:50 +03:00
|
|
|
unless (Set.null lockedIds) $ do
|
2020-11-25 13:56:44 +03:00
|
|
|
result <- runMetadataStorageT $ doUnlock $ toList lockedIds
|
2020-07-02 14:57:09 +03:00
|
|
|
case result of
|
|
|
|
Left err -> logger $ mkGenericStrLog LevelWarn triggerType $
|
|
|
|
"Error while unlocking " ++ T.unpack eventType ++ " events: " ++ show err
|
|
|
|
Right count -> logger $ mkGenericStrLog LevelInfo triggerType $
|
|
|
|
show count ++ " " ++ T.unpack eventType ++ " events successfully unlocked"
|
2020-04-14 09:01:50 +03:00
|
|
|
|
2021-05-14 12:38:37 +03:00
|
|
|
-- This function is a helper function to do couple of things:
|
|
|
|
--
|
|
|
|
-- 1. When the value of the `graceful-shutdown-timeout` > 0, we poll
|
|
|
|
-- the in-flight events queue we maintain using the `processingEventsCountAction`
|
|
|
|
-- number of in-flight processing events, in case of actions it is the
|
|
|
|
-- actions which are in 'processing' state and in scheduled events
|
|
|
|
-- it is the events which are in 'locked' state. The in-flight events queue is polled
|
|
|
|
-- every 5 seconds until either the graceful shutdown time is exhausted
|
|
|
|
-- or the number of in-flight processing events is 0.
|
|
|
|
-- 2. After step 1, we unlock all the events which were attempted to process by the current
|
|
|
|
-- graphql-engine instance that are still in the processing
|
|
|
|
-- state. In actions, it means to set the status of such actions to 'pending'
|
|
|
|
-- and in scheduled events, the status will be set to 'unlocked'.
|
|
|
|
waitForProcessingAction
|
|
|
|
:: Logger Hasura
|
|
|
|
-> String
|
|
|
|
-> IO Int
|
|
|
|
-> ShutdownAction
|
|
|
|
-> Seconds
|
|
|
|
-> IO ()
|
|
|
|
waitForProcessingAction l@(Logger logger) actionType processingEventsCountAction' shutdownAction maxTimeout
|
|
|
|
| maxTimeout <= 0 = do
|
|
|
|
case shutdownAction of
|
|
|
|
EventTriggerShutdownAction userDBShutdownAction -> userDBShutdownAction
|
|
|
|
MetadataDBShutdownAction metadataDBShutdownAction ->
|
|
|
|
runMetadataStorageT metadataDBShutdownAction >>= \case
|
|
|
|
Left err ->
|
|
|
|
logger $ mkGenericStrLog LevelWarn (T.pack actionType) $
|
|
|
|
"Error while unlocking the processing " <>
|
|
|
|
show actionType <> " err - "<> show err
|
|
|
|
Right () -> pure ()
|
|
|
|
| otherwise = do
|
|
|
|
processingEventsCount <- processingEventsCountAction'
|
|
|
|
if (processingEventsCount == 0)
|
|
|
|
then logger $ mkGenericStrLog LevelInfo (T.pack actionType) $
|
|
|
|
"All in-flight events have finished processing"
|
|
|
|
else
|
|
|
|
unless (processingEventsCount == 0) $ do
|
|
|
|
C.sleep (5) -- sleep for 5 seconds and then repeat
|
|
|
|
waitForProcessingAction l actionType processingEventsCountAction' shutdownAction (maxTimeout - (Seconds 5))
|
|
|
|
|
2019-11-26 15:14:21 +03:00
|
|
|
runAsAdmin
|
2021-02-18 19:46:14 +03:00
|
|
|
:: HTTP.Manager
|
|
|
|
-> ServerConfigCtx
|
2020-12-14 07:30:19 +03:00
|
|
|
-> RunT m a
|
2019-11-26 15:14:21 +03:00
|
|
|
-> m (Either QErr a)
|
2021-02-18 19:46:14 +03:00
|
|
|
runAsAdmin httpManager serverConfigCtx m = do
|
|
|
|
let runCtx = RunCtx adminUserInfo httpManager serverConfigCtx
|
2020-12-28 15:56:00 +03:00
|
|
|
runExceptT $ peelRun runCtx m
|
|
|
|
|
2019-11-26 15:14:21 +03:00
|
|
|
execQuery
|
2020-01-23 00:55:55 +03:00
|
|
|
:: ( HasVersion
|
|
|
|
, CacheRWM m
|
2019-11-26 15:14:21 +03:00
|
|
|
, MonadIO m
|
2020-12-28 15:56:00 +03:00
|
|
|
, MonadBaseControl IO m
|
Rewrite GraphQL schema generation and query parsing (close #2801) (#4111)
Aka “the PDV refactor.” History is preserved on the branch 2801-graphql-schema-parser-refactor.
* [skip ci] remove stale benchmark commit from commit_diff
* [skip ci] Check for root field name conflicts between remotes
* [skip ci] Additionally check for conflicts between remotes and DB
* [skip ci] Check for conflicts in schema when tracking a table
* [skip ci] Fix equality checking in GraphQL AST
* server: fix mishandling of GeoJSON inputs in subscriptions (fix #3239) (#4551)
* Add support for multiple top-level fields in a subscription to improve testability of subscriptions
* Add an internal flag to enable multiple subscriptions
* Add missing call to withConstructorFn in live queries (fix #3239)
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
* Scheduled triggers (close #1914) (#3553)
server: add scheduled triggers
Co-authored-by: Alexis King <lexi.lambda@gmail.com>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
* dev.sh: bump version due to addition of croniter python dependency
* server: fix an introspection query caching issue (fix #4547) (#4661)
Introspection queries accept variables, but we need to make sure to
also touch the variables that we ignore, so that an introspection
query is marked not reusable if we are not able to build a correct
query plan for it.
A better solution here would be to deal with such unused variables
correctly, so that more introspection queries become reusable.
An even better solution would be to type-safely track *how* to reuse
which variables, rather than to split the reusage marking from the
planning.
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* flush log buffer on exception in mkWaiApp ( fix #4772 ) (#4801)
* flush log buffer on exception in mkWaiApp
* add comment to explain the introduced change
* add changelog
* allow logging details of a live query polling thread (#4959)
* changes for poller-log
add various multiplexed query info in poller-log
* minor cleanup, also fixes a bug which will return duplicate data
* Live query poller stats can now be logged
This also removes in-memory stats that are collected about batched
query execution as the log lines when piped into an monitoring tool
will give us better insights.
* allow poller-log to be configurable
* log minimal information in the livequery-poller-log
Other information can be retrieved from /dev/subscriptions/extended
* fix few review comments
* avoid marshalling and unmarshalling from ByteString to EncJSON
* separate out SubscriberId and SubscriberMetadata
Co-authored-by: Anon Ray <rayanon004@gmail.com>
* Don't compile in developer APIs by default
* Tighten up handling of admin secret, more docs
Store the admin secret only as a hash to prevent leaking the secret
inadvertently, and to prevent timing attacks on the secret.
NOTE: best practice for stored user passwords is a function with a
tunable cost like bcrypt, but our threat model is quite different (even
if we thought we could reasonably protect the secret from an attacker
who could read arbitrary regions of memory), and bcrypt is far too slow
(by design) to perform on each request. We'd have to rely on our
(technically savvy) users to choose high entropy passwords in any case.
Referencing #4736
* server/docs: add instructions to fix loss of float precision in PostgreSQL <= 11 (#5187)
This adds a server flag, --pg-connection-options, that can be used to set a PostgreSQL connection parameter, extra_float_digits, that needs to be used to avoid loss of data on older versions of PostgreSQL, which have odd default behavior when returning float values. (fixes #5092)
* [skip ci] Add new commits from master to the commit diff
* [skip ci] serve default directives (skip & include) over introspection
* [skip ci] Update non-Haskell assets with the version on master
* server: refactor GQL execution check and config API (#5094)
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix js issues in tests by pinning dependencies version
* [skip ci] bump graphql version
* [skip ci] Add note about memory usage
* generalize query execution logic on Postgres (#5110)
* generalize PGExecCtx to support specialized functions for various operations
* fix tests compilation
* allow customising PGExecCtx when starting the web server
* server: changes catalog initialization and logging for pro customization (#5139)
* new typeclass to abstract the logic of QueryLog-ing
* abstract the logic of logging websocket-server logs
introduce a MonadWSLog typeclass
* move catalog initialization to init step
expose a helper function to migrate catalog
create schema cache in initialiseCtx
* expose various modules and functions for pro
* [skip ci] cosmetic change
* [skip ci] fix test calling a mutation that does not exist
* [skip ci] minor text change
* [skip ci] refactored input values
* [skip ci] remove VString Origin
* server: fix updating of headers behaviour in the update cron trigger API and create future events immediately (#5151)
* server: fix bug to update headers in an existing cron trigger and create future events
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Lower stack chunk size in RTS to reduce thread STACK memory (closes #5190)
This reduces memory consumption for new idle subscriptions significantly
(see linked ticket).
The hypothesis is: we fork a lot of threads per websocket, and some of
these use slightly more than the initial 1K stack size, so the first
overflow balloons to 32K, when significantly less is required.
However: running with `+RTS -K1K -xc` did not seem to show evidence of
any overflows! So it's a mystery why this improves things.
GHC should probably also be doubling the stack buffer at each overflow
or doing something even smarter; the knobs we have aren't so helpful.
* [skip ci] fix todo and schema generation for aggregate fields
* 5087 libpq pool leak (#5089)
Shrink libpq buffers to 1MB before returning connection to pool. Closes #5087
See: https://github.com/hasura/pg-client-hs/pull/19
Also related: #3388 #4077
* bump pg-client-hs version (fixes a build issue on some environments) (#5267)
* do not use prepared statements for mutations
* server: unlock scheduled events on graceful shutdown (#4928)
* Fix buggy parsing of new --conn-lifetime flag in 2b0e3774
* [skip ci] remove cherry-picked commit from commit_diff.txt
* server: include additional fields in scheduled trigger webhook payload (#5262)
* include scheduled triggers metadata in the webhook body
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* [skip ci] fix cast exp parser & few TODOs
* [skip ci] fix remote fields arguments
* [skip ci] fix few more TODO, no-op refactor, move resolve/action.hs to execute/action.hs
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] fix: restrict remote relationship field generation for hasura queries
* [skip ci] no-op refactor; move insert execution code from schema parser module
* server: call the webhook asynchronously in event triggers (#5352)
* server: call the webhook asynchronosly in event triggers
* Expose all modules in Cabal file (#5371)
* [skip ci] update commit_diff.txt
* Pass environment variables around as a data structure, via @sordina (#5374)
* Pass environment variables around as a data structure, via @sordina
* Resolving build error
* Adding Environment passing note to changelog
* Removing references to ILTPollerLog as this seems to have been reintroduced from a bad merge
* removing commented-out imports
* Language pragmas already set by project
* Linking async thread
* Apply suggestions from code review
Use `runQueryTx` instead of `runLazyTx` for queries.
* remove the non-user facing entry in the changelog
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] implement header checking
Probably closes #14 and #3659.
* server: refactor 'pollQuery' to have a hook to process 'PollDetails' (#5391)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* update pg-client (#5421)
* [skip ci] update commit_diff
* Fix latency buckets for telemetry data
These must have gotten messed up during a refactor. As a consequence
almost all samples received so far fall into the single erroneous 0 to
1K seconds (originally supposed to be 1ms?) bucket.
I also re-thought what the numbers should be, but these are still
arbitrary and might want adjusting in the future.
* [skip ci] include the latest commit compared against master in commit_diff
* [skip ci] include new commits from master in commit_diff
* [skip ci] improve description generation
* [skip ci] sort all introspect arrays
* [skip ci] allow parsers to specify error codes
* [skip ci] fix integer and float parsing error code
* [skip ci] scalar from json errors are now parse errors
* [skip ci] fixed negative integer error message and code
* [skip ci] Re-fix nullability in relationships
* [skip ci] no-op refactor and removed couple of FIXMEs
* [skip ci] uncomment code in 'deleteMetadataObject'
* [skip ci] Fix re-fix of nullability for relationships
* [skip ci] fix default arguments error code
* [skip ci] updated test error message
!!! WARNING !!!
Since all fields accept `null`, they all are technically optional in
the new schema. Meaning there's no such thing as a missing mandatory
field anymore: a field that doesn't have a default value, and which
therefore isn't labelled as "optional" in the schema, will be assumed
to be null if it's missing, meaning it isn't possible anymore to have
an error for a missing mandatory field. The only possible error is now
when a optional positional argument is omitted but is not the last
positional argument.
* [skip ci] cleanup of int scalar parser
* [skip ci] retro-compatibility of offset as string
* [skip ci] Remove commit from commit_diff.txt
Although strictly speaking we don't know if this will work correctly in PDV
if we would implement query plan caching, the fact is that in the theoretical
case that we would have the same issue in PDV, it would probably apply not just
to introspection, and the fix would be written completely differently. So this
old commit is of no value to us other than the heads-up "make sure query plan
caching works correctly even in the presence of unused variables", which is
already part of the test suite.
* Add MonadTrace and MonadExecuteQuery abstractions (#5383)
* [skip ci] Fix accumulation of input object types
Just like object types, interface types, and union types, we have to avoid
circularities when collecting input types from the GraphQL AST.
Additionally, this fixes equality checks for input object types (whose fields
are unordered, and hence should be compared as sets) and enum types (ditto).
* [skip ci] fix fragment error path
* [skip ci] fix node error code
* [skip ci] fix paths in insert queries
* [skip ci] fix path in objects
* [skip ci] manually alter node id path for consistency
* [skip ci] more node error fixups
* [skip ci] one last relay error message fix
* [skip ci] update commit_diff
* Propagate the trace context to event triggers (#5409)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: log request/response sizes for event triggers (#5463)
* server: log request/response sizes for event triggers
event triggers (and scheduled triggers) now have request/response size
in their logs.
* add changelog entry
* Tracing: Simplify HTTP traced request (#5451)
Remove the Inversion of Control (SuspendRequest) and simplify
the tracing of HTTP Requests.
Co-authored-by: Phil Freeman <phil@hasura.io>
* Attach request ID as tracing metadata (#5456)
* Propagate the trace context to event triggers
* Handle missing trace and span IDs
* Store trace context as one LOCAL
* Add migrations
* Documentation
* Include the request ID as trace metadata
* changelog
* Fix warnings
* Respond to code review suggestions
* Respond to code review
* Undo changelog
* Update CHANGELOG.md
* Typo
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* server: add logging for action handlers (#5471)
* server: add logging for action handlers
* add changelog entry
* change action-handler log type from internal to non-internal
* fix action-handler-log name
* server: pass http and websocket request to logging context (#5470)
* pass request body to logging context in all cases
* add message size logging on the websocket API
this is required by graphql-engine-pro/#416
* message size logging on websocket API
As we need to log all messages recieved/sent by the websocket server,
it makes sense to log them as part of the websocket server event logs.
Previously message recieved were logged inside the onMessage handler,
and messages sent were logged only for "data" messages (as a server event log)
* fix review comments
Co-authored-by: Phil Freeman <phil@hasura.io>
* server: stop eventing subsystem threads when shutting down (#5479)
* server: stop eventing subsystem threads when shutting down
* Apply suggestions from code review
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
* [skip ci] update commit_diff with new commits added in master
* Bugfix to support 0-size HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE
Also some minor refactoring of bounded cache module:
- the maxBound check in `trim` was confusing and unnecessary
- consequently trim was unnecessary for lookupPure
Also add some basic tests
* Support only the bounded cache, with default HASURA_GRAPHQL_QUERY_PLAN_CACHE_SIZE of 4000. Closes #5363
* [skip ci] remove merge commit from commit_diff
* server: Fix compiler warning caused by GHC upgrade (#5489)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* [skip ci] update all non server code from master
* [skip ci] aligned object field error message with master
* [skip ci] fix remaining undefined?
* [skip ci] remove unused import
* [skip ci] revert to previous error message, fix tests
* Move nullableType/nonNullableType to Schema.hs
These are functions on Types, not on Parsers.
* [skip ci] fix setup to fix backend only test
the order in which permission checks are performed on the branch is
slightly different than on master, resulting in a slightly different
error if there are no other mutations the user has access to. By
adding update permissions, we go back to the expected case.
* [skip ci] fix insert geojson tests to reflect new paths
* [skip ci] fix enum test for better error message
* [skip ci] fix header test for better error message
* [skip ci] fix fragment cycle test for better error message
* [skip ci] fix error message for type mismatch
* [skip ci] fix variable path in test
* [skip ci] adjust tests after bug fix
* [skip ci] more tests fixing
* Add hdb_catalog.current_setting abstraction for reading Hasura settings
As the comment in the function’s definition explains, this is needed to
work around an awkward Postgres behavior.
* [skip ci] Update CONTRIBUTING.md to mention Node setup for Python tests
* [skip ci] Add missing Python tests env var to CONTRIBUTING.md
* [skip ci] fix order of result when subscription is run with multiple nodes
* [skip ci] no-op refactor: fix a warning in Internal/Parser.hs
* [skip ci] throw error when a subscription contains remote joins
* [skip ci] Enable easier profiling by hiding AssertNF behind a flag
In order to compile a profiling build, run:
$ cabal new-build -f profiling --enable-profiling
* [skip ci] Fix two warnings
We used to lookup the objects that implement a given interface by filtering all
objects in the schema document. However, one of the tests expects us to
generate a warning if the provided `implements` field of an introspection query
specifies an object not implementing some interface. So we use that field
instead.
* [skip ci] Fix warnings by commenting out query plan caching
* [skip ci] improve masking/commenting query caching related code & few warning fixes
* [skip ci] Fixed compiler warnings in graphql-parser-hs
* Sync non-Haskell assets with master
* [skip ci] add a test inserting invalid GraphQL but valid JSON value in a jsonb column
* [skip ci] Avoid converting to/from Map
* [skip ci] Apply some hlint suggestions
* [skip ci] remove redundant constraints from buildLiveQueryPlan and explainGQLQuery
* [skip ci] add NOTEs about missing Tracing constraints in PDV from master
* Remove -fdefer-typed-holes, fix warnings
* Update cabal.project.freeze
* Limit GHC’s heap size to 8GB in CI to avoid the OOM killer
* Commit package-lock.json for Python tests’ remote schema server
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* add test for table_by_pk node when roles doesn't have permission to PK
* [skip ci] fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* [skip ci] test case fix for a6450e126bc2d98bcfd3791501986e4627ce6c6f
* [skip ci] add tests to agg queries when role doesn't have access to any cols
* fix backend test
* Simplify subscription execution
* [skip ci] add test to check if required headers are present while querying
* Suppose, table B is related to table A and to query B certain headers are
necessary, then the test checks that we are throwing error when the header
is not set when B is queried through A
* fix mutations not checking for view mutability
* [skip ci] add variable type checking and corresponding tests
* [skip ci] add test to check if update headers are present while doing an upsert
* [skip ci] add positive counterparts to some of the negative permission tests
* fix args missing their description in introspect
* [skip ci] Remove unused function; insert missing markNotReusable call
* [skip ci] Add a Note about InputValue
* [skip ci] Delete LegacySchema/ 🎉
* [skip ci] Delete GraphQL/{Resolve,Validate}/ 🎉
* [skip ci] Delete top-level Resolve/Validate modules; tidy .cabal file
* [skip ci] Delete LegacySchema top-level module
Somehow I missed this one.
* fix input value to json
* [skip ci] elaborate on JSON objects in GraphQL
* [skip ci] add missing file
* [skip ci] add a test with subscription containing remote joins
* add a test with remote joins in mutation output
* [skip ci] Add some comments to Schema/Mutation.hs
* [skip ci] Remove no longer needed code from RemoteServer.hs
* [skip ci] Use a helper function to generate conflict clause parsers
* [skip ci] fix type checker error in fields with default value
* capitalize the header keys in select_articles_without_required_headers
* Somehow, this was the reason the tests were failing. I have no idea, why!
* [skip ci] Add a long Note about optional fields and nullability
* Improve comments a bit; simplify Schema/Common.hs a bit
* [skip ci] full implementation of 5.8.5 type checking.
* [skip ci] fix validation test teardown
* [skip ci] fix schema stitching test
* fix remote schema ignoring enum nullability
* [skip ci] fix fieldOptional to not discard nullability
* revert nullability of use_spheroid
* fix comment
* add required remote fields with arguments for tests
* [skip ci] add missing docstrings
* [skip ci] fixed description of remote fields
* [skip ci] change docstring for consistency
* fix several schema inconsistencies
* revert behaviour change in function arguments parsing
* fix remaining nullability issues in new schema
* minor no-op refactor; use isListType from graphql-parser-hs
* use nullability of remote schema node, while creating a Remote reln
* fix 'ID' input coercing & action 'ID' type relationship mapping
* include ASTs in MonadExecuteQuery
* needed for PRO code-base
* Delete code for "interfaces implementing ifaces" (draft GraphQL spec)
Previously I started writing some code that adds support for a future GraphQL
feature where interfaces may themselves be sub-types of other interfaces.
However, this code was incomplete, and partially incorrect. So this commit
deletes support for that entirely.
* Ignore a remote schema test during the upgrade/downgrade test
The PDV refactor does a better job at exposing a minimal set of types through
introspection. In particular, not every type that is present in a remote schema
is re-exposed by Hasura. The test
test_schema_stitching.py::TestRemoteSchemaBasic::test_introspection assumed that
all types were re-exposed, which is not required for GraphQL compatibility, in
order to test some aspect of our support for remote schemas.
So while this particular test has been updated on PDV, the PDV branch now does
not pass the old test, which we argue to be incorrect. Hence this test is
disabled while we await a release, after which we can re-enable it.
This also re-enables a test that was previously disabled for similar, though
unrelated, reasons.
* add haddock documentation to the action's field parsers
* Deslecting some tests in server-upgrade
Some tests with current build are failing on server upgrade
which it should not. The response is more accurate than
what it was.
Also the upgrade tests were not throwing errors when the test is
expected to return an error, but succeeds. The test framework is
patched to catch this case.
* [skip ci] Add a long Note about interfaces and object types
* send the response headers back to client after running a query
* Deselect a few more tests during upgrade/downgrade test
* Update commit_diff.txt
* change log kind from db_migrate to catalog_migrate (#5531)
* Show method and complete URI in traced HTTP calls (#5525)
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* restrict env variables start with HASURA_GRAPHQL_ for headers configuration in actions, event triggers & remote schemas (#5519)
* restrict env variables start with HASURA_GRAPHQL_ for headers definition in actions & event triggers
* update CHANGELOG.md
* Apply suggestions from code review
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
* fix introspection query if any enum column present in primary key (fix #5200) (#5522)
* Fix telemetry reporting of transport (websocket was reported as http)
* add log kinds in cli-migrations image (#5529)
* add log kinds in cli-migrations image
* give hint to resolve timeout error
* minor changes and CHANGELOG
* server: set hasura.tracecontext in RQL mutations [#5542] (#5555)
* server: set hasura.tracecontext in RQL mutations [#5542]
* Update test suite
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
* Add bulldozer auto-merge and -update configuration
We still need to add the github app (as of time of opening this PR)
Afterwards devs should be able to allow bulldozer to automatically
"update" the branch, merging in parent when it changes, as well as
automatically merge when all checks pass.
This is opt-in by adding the `auto-update-auto-merge` label to the PR.
* Remove 'bulldozer' config, try 'kodiak' for auto-merge
see: https://github.com/chdsbd/kodiak
The main issue that bit us was not being able to auto update forked
branches, also:
https://github.com/palantir/bulldozer/issues/66
https://github.com/palantir/bulldozer/issues/145
* Cherry-picked all commits
* [skip ci] Slightly improve formatting
* Revert "fix introspection query if any enum column present in primary key (fix #5200) (#5522)"
This reverts commit 0f9a5afa59a88f6824f4d63d58db246a5ba3fb03.
This undoes a cherry-pick of 34288e1eb5f2c5dad9e6d1e05453dd52397dc970 that was
already done previously in a6450e126bc2d98bcfd3791501986e4627ce6c6f, and
subsequently fixed for PDV in 70e89dc250f8ddc6e2b7930bbe2b3eeaa6dbe1db
* Do a small bit of tidying in Hasura.GraphQL.Parser.Collect
* Fix cherry-picking work
Some previous cherry-picks ended up modifying code that is commented out
* [skip ci] clarified comment regarding insert representation
* [skip ci] removed obsolete todos
* cosmetic change
* fix action error message
* [skip ci] remove obsolete comment
* [skip ci] synchronize stylish haskell extensions list
* use previously defined scalar names in parsers rather than ad-hoc literals
* Apply most syntax hlint hints.
* Clarify comment on update mutation.
* [skip ci] Clarify what fields should be specified for objects
* Update "_inc" description.
* Use record types rather than tuples fo IntrospectionResult and ParsedIntrospection
* Get rid of checkFieldNamesUnique (use Data.List.Extended.duplicates)
* Throw more errors when collecting query root names
* [skip ci] clean column parser comment
* Remove dead code inserted in ab65b39
* avoid converting to non-empty list where not needed
* add note and TODO about the disabled checks in PDV
* minor refactor in remoteField' function
* Unify two getObject methods
* Nitpicks in Remote.hs
* Update CHANGELOG.md
* Revert "Unify two getObject methods"
This reverts commit bd6bb40355b3d189a46c0312eb52225e18be57b3.
We do need two different getObject functions as the corresponding error message is different
* Fix error message in Remote.hs
* Update CHANGELOG.md
Co-authored-by: Auke Booij <auke@tulcod.com>
* Apply suggested Changelog fix.
Co-authored-by: Auke Booij <auke@tulcod.com>
* Fix typo in Changelog.
* [skip ci] Update changelog.
* reuse type names to avoid duplication
* Fix Hashable instance for Definition
The presence of `Maybe Unique`, and an optional description, as part of
`Definition`s, means that `Definition`s that are considered `Eq`ual may get
different hashes. This can happen, for instance, when one object is memoized
but another is not.
* [skip ci] Update commit_diff.txt
* Bump parser version.
* Bump freeze file after changes in parser.
* [skip ci] Incorporate commits from master
* Fix developer flag in server/cabal.project.freeze
Co-authored-by: Auke Booij <auke@tulcod.com>
* Deselect a changed ENUM test for upgrade/downgrade CI
* Deselect test here as well
* [skip ci] remove dead code
* Disable more tests for upgrade/downgrade
* Fix which test gets deselected
* Revert "Add hdb_catalog.current_setting abstraction for reading Hasura settings"
This reverts commit 66e85ab9fbd56cca2c28a80201f6604fbe811b85.
* Remove circular reference in cabal.project.freeze
Co-authored-by: Karthikeyan Chinnakonda <karthikeyan@hasura.io>
Co-authored-by: Auke Booij <auke@hasura.io>
Co-authored-by: Tirumarai Selvan <tiru@hasura.io>
Co-authored-by: Marion Schleifer <marion@hasura.io>
Co-authored-by: Aleksandra Sikora <ola.zxcvbnm@gmail.com>
Co-authored-by: Brandon Simmons <brandon.m.simmons@gmail.com>
Co-authored-by: Vamshi Surabhi <0x777@users.noreply.github.com>
Co-authored-by: Anon Ray <rayanon004@gmail.com>
Co-authored-by: rakeshkky <12475069+rakeshkky@users.noreply.github.com>
Co-authored-by: Anon Ray <ecthiender@users.noreply.github.com>
Co-authored-by: Vamshi Surabhi <vamshi@hasura.io>
Co-authored-by: Antoine Leblanc <antoine@hasura.io>
Co-authored-by: Brandon Simmons <brandon@hasura.io>
Co-authored-by: Phil Freeman <phil@hasura.io>
Co-authored-by: Lyndon Maydwell <lyndon@sordina.net>
Co-authored-by: Phil Freeman <paf31@cantab.net>
Co-authored-by: Naveen Naidu <naveennaidu479@gmail.com>
Co-authored-by: Karthikeyan Chinnakonda <chkarthikeyan95@gmail.com>
Co-authored-by: Nizar Malangadan <nizar-m@users.noreply.github.com>
Co-authored-by: Antoine Leblanc <crucuny@gmail.com>
Co-authored-by: Auke Booij <auke@tulcod.com>
2020-08-21 20:27:01 +03:00
|
|
|
, MonadUnique m
|
2021-01-09 02:09:15 +03:00
|
|
|
, HasHttpManagerM m
|
2019-11-26 15:14:21 +03:00
|
|
|
, UserInfoM m
|
2020-07-15 13:40:48 +03:00
|
|
|
, Tracing.MonadTrace m
|
2021-01-29 08:48:17 +03:00
|
|
|
, HasServerConfigCtx m
|
2020-12-08 17:22:31 +03:00
|
|
|
, MetadataM m
|
2020-12-28 15:56:00 +03:00
|
|
|
, MonadMetadataStorageQueryAPI m
|
2019-11-26 15:14:21 +03:00
|
|
|
)
|
2020-07-14 22:00:58 +03:00
|
|
|
=> Env.Environment
|
|
|
|
-> BLC.ByteString
|
2019-11-26 15:14:21 +03:00
|
|
|
-> m BLC.ByteString
|
2020-07-14 22:00:58 +03:00
|
|
|
execQuery env queryBs = do
|
2019-11-26 15:14:21 +03:00
|
|
|
query <- case A.decode queryBs of
|
|
|
|
Just jVal -> decodeValue jVal
|
|
|
|
Nothing -> throw400 InvalidJSON "invalid json"
|
|
|
|
buildSchemaCacheStrict
|
2021-01-07 12:04:22 +03:00
|
|
|
encJToLBS <$> runQueryM env query
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (Monad m) => Tracing.HasReporter (PGMetadataStorageAppT m)
|
2020-07-15 13:40:48 +03:00
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (Monad m) => HasResourceLimits (PGMetadataStorageAppT m) where
|
2020-12-03 07:06:22 +03:00
|
|
|
askResourceLimits = pure (ResourceLimits id)
|
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (MonadIO m) => HttpLog (PGMetadataStorageAppT m) where
|
2021-04-06 20:52:55 +03:00
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
type HTTPLoggingMetadata (PGMetadataStorageAppT m) = ()
|
2021-04-06 20:52:55 +03:00
|
|
|
|
|
|
|
buildHTTPLoggingMetadata _ = ()
|
|
|
|
|
2020-07-29 17:48:36 +03:00
|
|
|
logHttpError logger userInfoM reqId waiReq req qErr headers =
|
2019-11-26 15:14:21 +03:00
|
|
|
unLogger logger $ mkHttpLog $
|
2020-07-29 17:48:36 +03:00
|
|
|
mkHttpErrorLogContext userInfoM reqId waiReq req qErr Nothing Nothing headers
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2021-04-06 20:52:55 +03:00
|
|
|
logHttpSuccess logger userInfoM reqId waiReq _reqBody _response compressedResponse qTime cType headers () =
|
2019-11-26 15:14:21 +03:00
|
|
|
unLogger logger $ mkHttpLog $
|
2020-07-29 17:48:36 +03:00
|
|
|
mkHttpAccessLogContext userInfoM reqId waiReq compressedResponse qTime cType headers
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (Monad m) => MonadExecuteQuery (PGMetadataStorageAppT m) where
|
2021-04-13 10:00:43 +03:00
|
|
|
cacheLookup _ _ _ = pure ([], Nothing)
|
2020-10-07 11:55:39 +03:00
|
|
|
cacheStore _ _ = pure ()
|
2020-07-15 13:40:48 +03:00
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (MonadIO m, MonadBaseControl IO m) => UserAuthentication (Tracing.TraceT (PGMetadataStorageAppT m)) where
|
2021-02-03 10:10:39 +03:00
|
|
|
resolveUserInfo logger manager headers authMode reqs =
|
|
|
|
runExceptT $ getUserInfoWithExpTime logger manager headers authMode reqs
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2021-01-07 12:04:22 +03:00
|
|
|
accessDeniedErrMsg :: Text
|
|
|
|
accessDeniedErrMsg =
|
|
|
|
"restricted access : admin only"
|
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (Monad m) => MonadMetadataApiAuthorization (PGMetadataStorageAppT m) where
|
2021-01-07 12:04:22 +03:00
|
|
|
authorizeV1QueryApi query handlerCtx = runExceptT do
|
2020-12-14 07:30:19 +03:00
|
|
|
let currRole = _uiRole $ hcUser handlerCtx
|
2020-04-24 12:10:53 +03:00
|
|
|
when (requiresAdmin query && currRole /= adminRoleName) $
|
2021-01-07 12:04:22 +03:00
|
|
|
withPathK "args" $ throw400 AccessDenied accessDeniedErrMsg
|
|
|
|
|
|
|
|
authorizeV1MetadataApi _ handlerCtx = runExceptT do
|
|
|
|
let currRole = _uiRole $ hcUser handlerCtx
|
|
|
|
when (currRole /= adminRoleName) $
|
|
|
|
withPathK "args" $ throw400 AccessDenied accessDeniedErrMsg
|
|
|
|
|
2021-04-16 16:26:11 +03:00
|
|
|
authorizeV2QueryApi _ handlerCtx = runExceptT do
|
2021-01-07 12:04:22 +03:00
|
|
|
let currRole = _uiRole $ hcUser handlerCtx
|
2021-04-16 16:26:11 +03:00
|
|
|
when (currRole /= adminRoleName) $
|
2021-01-07 12:04:22 +03:00
|
|
|
withPathK "args" $ throw400 AccessDenied accessDeniedErrMsg
|
2019-11-26 15:14:21 +03:00
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (Monad m) => ConsoleRenderer (PGMetadataStorageAppT m) where
|
2019-11-26 15:14:21 +03:00
|
|
|
renderConsole path authMode enableTelemetry consoleAssetsDir =
|
|
|
|
return $ mkConsoleHTML path authMode enableTelemetry consoleAssetsDir
|
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (Monad m) => MonadGQLExecutionCheck (PGMetadataStorageAppT m) where
|
2020-06-16 18:23:06 +03:00
|
|
|
checkGQLExecution userInfo _ enableAL sc query = runExceptT $ do
|
|
|
|
req <- toParsed query
|
|
|
|
checkQueryInAllowlist enableAL userInfo req sc
|
|
|
|
return req
|
|
|
|
|
2021-05-05 15:25:27 +03:00
|
|
|
executeIntrospection _ introspectionQuery _ =
|
|
|
|
pure $ Right $ ExecStepRaw introspectionQuery
|
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (MonadIO m, MonadBaseControl IO m) => MonadConfigApiHandler (PGMetadataStorageAppT m) where
|
2020-06-16 18:23:06 +03:00
|
|
|
runConfigApiHandler = configApiGetHandler
|
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (MonadIO m) => MonadQueryLog (PGMetadataStorageAppT m) where
|
2021-03-13 17:40:50 +03:00
|
|
|
logQueryLog = unLogger
|
2020-06-19 09:42:32 +03:00
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (MonadIO m) => WS.MonadWSLog (PGMetadataStorageAppT m) where
|
2020-06-19 09:42:32 +03:00
|
|
|
logWSLog = unLogger
|
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance (Monad m) => MonadResolveSource (PGMetadataStorageAppT m) where
|
2020-12-28 15:56:00 +03:00
|
|
|
getSourceResolver = mkPgSourceResolver <$> asks snd
|
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
runInSeparateTx
|
|
|
|
:: (MonadIO m)
|
|
|
|
=> Q.TxE QErr a -> MetadataStorageT (PGMetadataStorageAppT m) a
|
2020-11-25 13:56:44 +03:00
|
|
|
runInSeparateTx tx = do
|
2020-12-28 15:56:00 +03:00
|
|
|
pool <- lift $ asks fst
|
2020-11-25 13:56:44 +03:00
|
|
|
liftEitherM $ liftIO $ runExceptT $ Q.runTx pool (Q.RepeatableRead, Nothing) tx
|
|
|
|
|
2021-04-06 06:25:02 +03:00
|
|
|
notifySchemaCacheSyncTx :: MetadataResourceVersion -> InstanceId -> CacheInvalidations -> Q.TxE QErr ()
|
|
|
|
notifySchemaCacheSyncTx (MetadataResourceVersion resourceVersion) instanceId invalidations = do
|
2020-12-14 07:30:19 +03:00
|
|
|
Q.Discard () <- Q.withQE defaultTxErrorHandler [Q.sql|
|
2021-04-06 06:25:02 +03:00
|
|
|
INSERT INTO hdb_catalog.hdb_schema_notifications(id, notification, resource_version, instance_id)
|
|
|
|
VALUES (1, $1::json, $2, $3::uuid)
|
|
|
|
ON CONFLICT (id) DO UPDATE SET
|
|
|
|
notification = $1::json,
|
|
|
|
resource_version = $2,
|
|
|
|
instance_id = $3::uuid
|
|
|
|
|] (Q.AltJ invalidations, resourceVersion, instanceId) True
|
2020-12-14 07:30:19 +03:00
|
|
|
pure ()
|
|
|
|
|
2021-01-07 12:04:22 +03:00
|
|
|
getCatalogStateTx :: Q.TxE QErr CatalogState
|
|
|
|
getCatalogStateTx =
|
|
|
|
mkCatalogState . Q.getRow <$> Q.withQE defaultTxErrorHandler [Q.sql|
|
|
|
|
SELECT hasura_uuid::text, cli_state::json, console_state::json
|
|
|
|
FROM hdb_catalog.hdb_version
|
|
|
|
|] () False
|
|
|
|
where
|
|
|
|
mkCatalogState (dbId, Q.AltJ cliState, Q.AltJ consoleState) =
|
|
|
|
CatalogState dbId cliState consoleState
|
|
|
|
|
|
|
|
setCatalogStateTx :: CatalogStateType -> A.Value -> Q.TxE QErr ()
|
|
|
|
setCatalogStateTx stateTy stateValue =
|
|
|
|
case stateTy of
|
|
|
|
CSTCli ->
|
|
|
|
Q.unitQE defaultTxErrorHandler [Q.sql|
|
|
|
|
UPDATE hdb_catalog.hdb_version
|
|
|
|
SET cli_state = $1
|
|
|
|
|] (Identity $ Q.AltJ stateValue) False
|
|
|
|
CSTConsole ->
|
|
|
|
Q.unitQE defaultTxErrorHandler [Q.sql|
|
|
|
|
UPDATE hdb_catalog.hdb_version
|
|
|
|
SET console_state = $1
|
|
|
|
|] (Identity $ Q.AltJ stateValue) False
|
|
|
|
|
2021-02-18 19:46:14 +03:00
|
|
|
|
2020-11-25 13:56:44 +03:00
|
|
|
-- | Each of the function in the type class is executed in a totally separate transaction.
|
|
|
|
--
|
|
|
|
-- To learn more about why the instance is derived as following, see Note [Generic MetadataStorageT transformer]
|
2021-05-26 19:19:26 +03:00
|
|
|
instance {-# OVERLAPPING #-} MonadIO m => MonadMetadataStorage (MetadataStorageT (PGMetadataStorageAppT m)) where
|
2021-04-06 06:25:02 +03:00
|
|
|
|
|
|
|
fetchMetadataResourceVersion = runInSeparateTx fetchMetadataResourceVersionFromCatalog
|
|
|
|
fetchMetadata = runInSeparateTx fetchMetadataAndResourceVersionFromCatalog
|
|
|
|
fetchMetadataNotifications a b = runInSeparateTx $ fetchMetadataNotificationsFromCatalog a b
|
|
|
|
setMetadata r = runInSeparateTx . setMetadataInCatalog (Just r)
|
|
|
|
notifySchemaCacheSync a b c = runInSeparateTx $ notifySchemaCacheSyncTx a b c
|
2021-01-07 12:04:22 +03:00
|
|
|
getCatalogState = runInSeparateTx getCatalogStateTx
|
|
|
|
setCatalogState a b = runInSeparateTx $ setCatalogStateTx a b
|
2020-12-14 07:30:19 +03:00
|
|
|
|
2021-01-07 12:04:22 +03:00
|
|
|
getDatabaseUid = runInSeparateTx getDbId
|
2021-03-16 20:35:35 +03:00
|
|
|
checkMetadataStorageHealth = lift (asks fst) >>= checkDbConnection
|
2020-12-28 15:56:00 +03:00
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
getDeprivedCronTriggerStats = runInSeparateTx . getDeprivedCronTriggerStatsTx
|
2020-11-25 13:56:44 +03:00
|
|
|
getScheduledEventsForDelivery = runInSeparateTx getScheduledEventsForDeliveryTx
|
|
|
|
insertScheduledEvent = runInSeparateTx . insertScheduledEventTx
|
|
|
|
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
|
2020-12-14 07:30:19 +03:00
|
|
|
clearFutureCronEvents = runInSeparateTx . dropFutureCronEventsTx
|
2021-01-07 12:04:22 +03:00
|
|
|
getOneOffScheduledEvents a b = runInSeparateTx $ getOneOffScheduledEventsTx a b
|
|
|
|
getCronEvents a b c = runInSeparateTx $ getCronEventsTx a b c
|
|
|
|
getInvocations a b = runInSeparateTx $ getInvocationsTx a b
|
|
|
|
deleteScheduledEvent a b = runInSeparateTx $ deleteScheduledEventTx a b
|
2020-12-14 07:30:19 +03:00
|
|
|
|
2021-05-14 12:38:37 +03:00
|
|
|
insertAction a b c d = runInSeparateTx $ insertActionTx a b c d
|
|
|
|
fetchUndeliveredActionEvents = runInSeparateTx fetchUndeliveredActionEventsTx
|
|
|
|
setActionStatus a b = runInSeparateTx $ setActionStatusTx a b
|
|
|
|
fetchActionResponse = runInSeparateTx . fetchActionResponseTx
|
|
|
|
clearActionData = runInSeparateTx . clearActionDataTx
|
|
|
|
setProcessingActionLogsToPending = runInSeparateTx . setProcessingActionLogsToPendingTx
|
2020-11-25 13:56:44 +03:00
|
|
|
|
2021-05-26 19:19:26 +03:00
|
|
|
instance MonadMetadataStorageQueryAPI (MetadataStorageT (PGMetadataStorageAppT CacheBuild))
|
|
|
|
|
2020-06-16 18:23:06 +03:00
|
|
|
--- helper functions ---
|
|
|
|
|
2020-01-23 00:55:55 +03:00
|
|
|
mkConsoleHTML :: HasVersion => Text -> AuthMode -> Bool -> Maybe Text -> Either String Text
|
2019-11-26 15:14:21 +03:00
|
|
|
mkConsoleHTML path authMode enableTelemetry consoleAssetsDir =
|
|
|
|
renderHtmlTemplate consoleTmplt $
|
|
|
|
-- variables required to render the template
|
2020-12-21 21:56:00 +03:00
|
|
|
A.object [ "isAdminSecretSet" A..= isAdminSecretSet authMode
|
|
|
|
, "consolePath" A..= consolePath
|
|
|
|
, "enableTelemetry" A..= boolToText enableTelemetry
|
|
|
|
, "cdnAssets" A..= boolToText (isNothing consoleAssetsDir)
|
|
|
|
, "assetsVersion" A..= consoleAssetsVersion
|
|
|
|
, "serverVersion" A..= currentVersion
|
2019-11-26 15:14:21 +03:00
|
|
|
]
|
|
|
|
where
|
|
|
|
consolePath = case path of
|
|
|
|
"" -> "/console"
|
|
|
|
r -> "/console/" <> r
|
|
|
|
|
2021-03-16 20:35:35 +03:00
|
|
|
consoleTmplt = $(makeRelativeToProject "src-rsr/console.html" >>= M.embedSingleTemplate)
|
2019-11-26 15:14:21 +03:00
|
|
|
|
|
|
|
telemetryNotice :: String
|
|
|
|
telemetryNotice =
|
|
|
|
"Help us improve Hasura! The graphql-engine server collects anonymized "
|
|
|
|
<> "usage stats which allows us to keep improving Hasura at warp speed. "
|
2021-03-01 21:50:24 +03:00
|
|
|
<> "To read more or opt-out, visit https://hasura.io/docs/latest/graphql/core/guides/telemetry.html"
|