Class: Spring::Application

Inherits:
Object
  • Object
show all
Defined in:
lib/spring/application.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(manager, watcher = Spring.watcher) ⇒ Application

Returns a new instance of Application.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/spring/application.rb', line 9

def initialize(manager, watcher = Spring.watcher)
  @manager    = manager
  @watcher    = watcher
  @setup      = Set.new
  @spring_env = Env.new
  @preloaded  = false
  @mutex      = Mutex.new
  @waiting    = 0
  @exiting    = false

  # Workaround for GC bug in Ruby 2 which causes segfaults if watcher.to_io
  # instances get dereffed.
  @fds = [manager, watcher.to_io]
end

Instance Attribute Details

#managerObject (readonly)

Returns the value of attribute manager.



7
8
9
# File 'lib/spring/application.rb', line 7

def manager
  @manager
end

#spring_envObject (readonly)

Returns the value of attribute spring_env.



7
8
9
# File 'lib/spring/application.rb', line 7

def spring_env
  @spring_env
end

#watcherObject (readonly)

Returns the value of attribute watcher.



7
8
9
# File 'lib/spring/application.rb', line 7

def watcher
  @watcher
end

Instance Method Details

#connect_databaseObject



190
191
192
# File 'lib/spring/application.rb', line 190

def connect_database
  ActiveRecord::Base.establish_connection if defined?(ActiveRecord::Base)
end

#disconnect_databaseObject



186
187
188
# File 'lib/spring/application.rb', line 186

def disconnect_database
  ActiveRecord::Base.remove_connection if defined?(ActiveRecord::Base)
end

#exiting?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/spring/application.rb', line 32

def exiting?
  @exiting
end

#invoke_after_fork_callbacksObject



176
177
178
179
180
# File 'lib/spring/application.rb', line 176

def invoke_after_fork_callbacks
  Spring.after_fork_callbacks.each do |callback|
    callback.call
  end
end

#loaded_application_featuresObject



182
183
184
# File 'lib/spring/application.rb', line 182

def loaded_application_features
  $LOADED_FEATURES.select { |f| f.start_with?(File.realpath(Rails.root)) }
end

#log(message) ⇒ Object



24
25
26
# File 'lib/spring/application.rb', line 24

def log(message)
  spring_env.log "[application:#{ENV['RAILS_ENV']}] #{message}"
end

#preloadObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/spring/application.rb', line 36

def preload
  log "preloading app"

  require Spring.application_root_path.join("config", "application")

  # config/environments/test.rb will have config.cache_classes = true. However
  # we want it to be false so that we can reload files. This is a hack to
  # override the effect of config.cache_classes = true. We can then actually
  # set config.cache_classes = false after loading the environment.
  Rails::Application.initializer :initialize_dependency_mechanism, group: :all do
    ActiveSupport::Dependencies.mechanism = :load
  end

  # Ensure eager loading does not take place, even though it usually would do
  # in test mode with config.cache_classes = true. Eager loading in this situation
  # just makes the initial run take longer without much gain in subsequent runs,
  # at least in my testing.
  Rails::Application::Finisher.initializers.delete_if { |i| i.name == :eager_load! }

  require Spring.application_root_path.join("config", "environment")

  Rails.application.config.cache_classes = false
  disconnect_database

  watcher.add loaded_application_features
  watcher.add Spring.gemfile, "#{Spring.gemfile}.lock"
  watcher.add Rails.application.paths["config/initializers"]

  @preloaded = true
end

#preloaded?Boolean

Returns:

  • (Boolean)


28
29
30
# File 'lib/spring/application.rb', line 28

def preloaded?
  @preloaded
end

#runObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/spring/application.rb', line 67

def run
  log "running"
  watcher.start

  loop do
    IO.select(@fds)

    if watcher.stale?
      log "watcher stale; exiting"
      manager.close
      @exiting = true
      try_exit
      sleep
    else
      serve manager.recv_io(UNIXSocket)
    end
  end
end

#serve(client) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/spring/application.rb', line 92

def serve(client)
  log "got client"
  manager.puts

  streams = 3.times.map { client.recv_io }
  [STDOUT, STDERR].zip(streams).each { |a, b| a.reopen(b) }

  preload unless preloaded?

  args    = JSON.load(client.read(client.gets.to_i))
  command = Spring.command(args.shift)

  connect_database
  setup command

  ActionDispatch::Reloader.cleanup!
  ActionDispatch::Reloader.prepare!

  pid = fork {
    Process.setsid
    STDIN.reopen(streams.last)
    IGNORE_SIGNALS.each { |sig| trap(sig, "DEFAULT") }

    connect_database
    ARGV.replace(args)
    srand

    invoke_after_fork_callbacks
    shush_backtraces

    if command.respond_to?(:call)
      command.call
    else
      exec_name = command.exec_name
      gem_name  = command.gem_name if command.respond_to?(:gem_name)

      exec = Gem.bin_path(gem_name || exec_name, exec_name)
      $0 = exec
      load exec
    end
  }

  disconnect_database
  [STDOUT, STDERR].each { |stream| stream.reopen(spring_env.log_file) }

  log "forked #{pid}"
  manager.puts pid

  # Wait in a separate thread so we can run multiple commands at once
  Thread.new {
    @mutex.synchronize { @waiting += 1 }

    _, status = Process.wait2 pid
    log "#{pid} exited with #{status.exitstatus}"

    streams.each(&:close)
    client.puts(status.exitstatus)
    client.close

    @mutex.synchronize { @waiting -= 1 }
    try_exit
  }

rescue => e
  log "exception: #{e}"
  streams.each(&:close) if streams
  client.puts(1)
  client.close
  raise
end

#setup(command) ⇒ Object

The command might need to require some files in the main process so that they are cached. For example a test command wants to load the helper file once and have it cached.



166
167
168
169
170
171
172
173
174
# File 'lib/spring/application.rb', line 166

def setup(command)
  return if @setup.include?(command.class)
  @setup << command.class

  if command.respond_to?(:setup)
    command.setup
    watcher.add loaded_application_features # loaded features may have changed
  end
end

#shush_backtracesObject

This feels very naughty



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/spring/application.rb', line 195

def shush_backtraces
  Kernel.module_eval do
    old_raise = Kernel.method(:raise)
    remove_method :raise
    define_method :raise do |*args|
      begin
        old_raise.call(*args)
      ensure
        if $!
          lib = File.expand_path("..", __FILE__)
          $!.backtrace.reject! { |line| line.start_with?(lib) }
        end
      end
    end
  end
end

#try_exitObject



86
87
88
89
90
# File 'lib/spring/application.rb', line 86

def try_exit
  @mutex.synchronize {
    exit if exiting? && @waiting == 0
  }
end