From 97a09e73ad65e98b706931405df12b6ee1988034 Mon Sep 17 00:00:00 2001 From: Gannon McGibbon Date: Fri, 22 Sep 2023 15:20:51 -0500 Subject: [PATCH] Make GraphQL parser cache opt-in The cache has nothing to do with bootsnap, so we don't need to piggyback off of it at all. This will prevent bootsnap cache to be polluted by the graphql gem, and allow more apps to leverage GQL caching. The parser cache is also now opt-in, which will make this behaviour more expected. --- guides/parser_cache.md | 12 ++++++++++++ lib/graphql/railtie.rb | 25 +++++++++++++++++++------ 2 files changed, 31 insertions(+), 6 deletions(-) create mode 100644 guides/parser_cache.md diff --git a/guides/parser_cache.md b/guides/parser_cache.md new file mode 100644 index 00000000000..b0c9a58913c --- /dev/null +++ b/guides/parser_cache.md @@ -0,0 +1,12 @@ +--- +layout: guide +doc_stub: false +search: true +title: GraphQL Parser cache +section: Other +desc: How to make parsing GraphQL faster with caching +--- + +Parser caching may be optionally enabled by setting `config.graphql.parser_cache = true` in your Rails application. The cache may be manually built by assigning `GraphQL::Language::Parser.cache = GraphQL::Language::Cache.new("some_dir")`. This will create a directory (`tmp/cache/graphql` by default) that stores a cache of parsed files. + +Much like [bootsnap](https://github.com/Shopify/bootsnap), the parser cache needs to be cleaned up manually. You will need to clear the cache directory for each new deployment of your application. Also note that the parser cache will grow as your schema is loaded, so the cache directory must be writable. diff --git a/lib/graphql/railtie.rb b/lib/graphql/railtie.rb index 36b11c1d689..34b1984c144 100644 --- a/lib/graphql/railtie.rb +++ b/lib/graphql/railtie.rb @@ -1,12 +1,25 @@ # frozen_string_literal: true + module GraphQL class Railtie < Rails::Railtie - config.before_configuration do - # Bootsnap compile cache has similar expiration properties, - # so we assume that if the user has bootsnap setup it's ok - # to piggy back on it. - if ::Object.const_defined?("Bootsnap::CompileCache::ISeq") && Bootsnap::CompileCache::ISeq.cache_dir - Language::Parser.cache ||= Language::Cache.new(Pathname.new(Bootsnap::CompileCache::ISeq.cache_dir).join('graphql')) + config.graphql = ActiveSupport::OrderedOptions.new + config.graphql.parser_cache = nil + + config.before_initialize do + if config.graphql.parser_cache.nil? && ::Object.const_defined?("Bootsnap::CompileCache::ISeq") && Bootsnap::CompileCache::ISeq.cache_dir + Deprecation.warn <<~MSG.squish + The GraphQL parser cache must be explicitly enabled in your application. + Please add `config.graphql.parser_cache = true` to your application config. + MSG + config.graphql.parser_cache = true + end + end + + initializer("graphql.cache") do |app| + if config.graphql.parser_cache + Language::Parser.cache ||= Language::Cache.new( + app.root.join("tmp/cache/graphql") + ) end end end