Skip to content

Commit

Permalink
Add Bootsnap.unload_cache!
Browse files Browse the repository at this point in the history
  • Loading branch information
byroot committed Jun 1, 2022
1 parent 26fcb55 commit 901c0b7
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

People still using the classic autoloader might want to stick to `bootsnap 1.12`.

* Add `Bootsnap.unload_cache!`. Applications can call it at the end of their boot sequence when they know
no more code will be loaded to reclaim a bit of memory.

# 1.12.0

* `bootsnap precompile` CLI will now also precompile `Rakefile` and `.rake` files.
Expand Down
4 changes: 4 additions & 0 deletions lib/bootsnap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ def setup(
)
end

def self.unload_cache!
LoadPathCache.unload!
end

def iseq_cache_supported?
return @iseq_cache_supported if defined? @iseq_cache_supported

Expand Down
16 changes: 15 additions & 1 deletion lib/bootsnap/load_path_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ module LoadPathCache

CACHED_EXTENSIONS = DLEXT2 ? [DOT_RB, DLEXT, DLEXT2] : [DOT_RB, DLEXT]

@enabled = false

class << self
attr_reader(:load_path_cache, :loaded_features_index)
attr_reader(:load_path_cache, :loaded_features_index, :enabled)
alias_method :enabled?, :enabled
remove_method(:enabled)

def setup(cache_path:, development_mode:)
unless supported?
Expand All @@ -35,10 +39,20 @@ def setup(cache_path:, development_mode:)
@loaded_features_index = LoadedFeaturesIndex.new

@load_path_cache = Cache.new(store, $LOAD_PATH, development_mode: development_mode)
@enabled = true
require_relative("load_path_cache/core_ext/kernel_require")
require_relative("load_path_cache/core_ext/loaded_features")
end

def unload!
@enabled = false
@loaded_features_index = nil
@realpath_cache = nil
@load_path_cache = nil
ChangeObserver.unregister($LOAD_PATH)
::Kernel.alias_method(:require_relative, :require_relative_without_bootsnap)
end

def supported?
RUBY_ENGINE == "ruby" &&
RUBY_PLATFORM =~ /darwin|linux|bsd|mswin|mingw|cygwin/
Expand Down
2 changes: 2 additions & 0 deletions lib/bootsnap/load_path_cache/core_ext/kernel_require.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ module Kernel
alias_method(:require_without_bootsnap, :require)

def require(path)
return require_without_bootsnap(path) unless Bootsnap::LoadPathCache.enabled?

string_path = Bootsnap.rb_get_path(path)
return false if Bootsnap::LoadPathCache.loaded_features_index.key?(string_path)

Expand Down

0 comments on commit 901c0b7

Please # to comment.