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, original_env, spring_env = Env.new) ⇒ Application

Returns a new instance of Application.



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

def initialize(manager, original_env, spring_env = Env.new)
  @manager      = manager
  @original_env = original_env
  @spring_env   = spring_env
  @mutex        = Mutex.new
  @waiting      = {}
  @clients      = {}
  @preloaded    = false
  @state        = :initialized
  @interrupt    = IO.pipe
end

Instance Attribute Details

#managerObject (readonly)

Returns the value of attribute manager.



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

def manager
  @manager
end

#original_envObject (readonly)

Returns the value of attribute original_env.



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

def original_env
  @original_env
end

#spring_envObject (readonly)

Returns the value of attribute spring_env.



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

def spring_env
  @spring_env
end

#watcherObject (readonly)

Returns the value of attribute watcher.



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

def watcher
  @watcher
end

Instance Method Details

#app_envObject



36
37
38
# File 'lib/spring/application.rb', line 36

def app_env
  ENV['RAILS_ENV']
end

#app_nameObject



40
41
42
# File 'lib/spring/application.rb', line 40

def app_name
  spring_env.app_name
end

#connect_databaseObject



301
302
303
# File 'lib/spring/application.rb', line 301

def connect_database
  ActiveRecord::Base.establish_connection if active_record_configured?
end

#disconnect_databaseObject



297
298
299
# File 'lib/spring/application.rb', line 297

def disconnect_database
  ActiveRecord::Base.remove_connection if active_record_configured?
end

#eager_preloadObject



134
135
136
137
138
139
140
141
# File 'lib/spring/application.rb', line 134

def eager_preload
  with_pty do
    # we can't see stderr and there could be issues when it's overflown
    # see https://github.com/rails/spring/issues/396
    STDERR.reopen("/dev/null")
    preload
  end
end

#exitObject



264
265
266
267
268
269
# File 'lib/spring/application.rb', line 264

def exit
  state :exiting
  manager.shutdown(:RDWR)
  exit_if_finished
  sleep
end

#exit_if_finishedObject



271
272
273
274
275
# File 'lib/spring/application.rb', line 271

def exit_if_finished
  @mutex.synchronize {
    Kernel.exit if exiting? && @waiting.empty?
  }
end

#exiting?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/spring/application.rb', line 56

def exiting?
  @state == :exiting
end

#initialized?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/spring/application.rb', line 68

def initialized?
  @state == :initialized
end

#invoke_after_fork_callbacksObject



286
287
288
289
290
# File 'lib/spring/application.rb', line 286

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

#loaded_application_featuresObject



292
293
294
295
# File 'lib/spring/application.rb', line 292

def loaded_application_features
  root = Spring.application_root_path.to_s
  $LOADED_FEATURES.select { |f| f.start_with?(root) }
end

#log(message) ⇒ Object



44
45
46
# File 'lib/spring/application.rb', line 44

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

#preloadObject



88
89
90
91
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
# File 'lib/spring/application.rb', line 88

def preload
  log "preloading app"

  begin
    require "spring/commands"
  ensure
    start_watcher
  end

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

  unless Rails.respond_to?(:gem_version) && Rails.gem_version >= Gem::Version.new('6.0.0')
    raise "Spring only supports Rails >= 6.0.0"
  end

  Rails::Application.initializer :ensure_reloading_is_enabled, group: :all do
    if Rails.application.config.cache_classes
      raise <<-MSG.strip_heredoc
        Spring reloads, and therefore needs the application to have reloading enabled.
        Please, set config.cache_classes to false in config/environments/#{Rails.env}.rb.
      MSG
    end
  end

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

  disconnect_database

  @preloaded = :success
rescue Exception => e
  @preloaded = :failure
  watcher.add e.backtrace.map { |line| line[/^(.*)\:\d+/, 1] }
  raise e unless initialized?
ensure
  watcher.add loaded_application_features
  watcher.add Spring.gemfile, Spring.gemfile_lock

  if defined?(Rails) && Rails.application
    watcher.add Rails.application.paths["config/initializers"]
    watcher.add Rails.application.paths["config/database"]
    if secrets_path = Rails.application.paths["config/secrets"]
      watcher.add secrets_path
    end
  end
end

#preload_failed?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/spring/application.rb', line 52

def preload_failed?
  @preloaded == :failure
end

#preloaded?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/spring/application.rb', line 48

def preloaded?
  @preloaded
end


337
338
339
340
341
# File 'lib/spring/application.rb', line 337

def print_exception(stream, error)
  first, rest = error.backtrace.first, error.backtrace.drop(1)
  stream.puts("#{first}: #{error} (#{error.class})")
  rest.each { |line| stream.puts("\tfrom #{line}") }
end

#reset_streamsObject



356
357
358
359
# File 'lib/spring/application.rb', line 356

def reset_streams
  [STDOUT, STDERR].each { |stream| stream.reopen(spring_env.log_file) }
  STDIN.reopen("/dev/null")
end

#runObject



143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/spring/application.rb', line 143

def run
  state :running
  manager.puts

  loop do
    IO.select [manager, @interrupt.first]

    if terminating? || watcher_stale? || preload_failed?
      exit
    else
      serve manager.recv_io(UNIXSocket)
    end
  end
end

#serve(client) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/spring/application.rb', line 158

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

  @clients[client] = true

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

  if preloaded?
    client.puts(0) # preload success
  else
    begin
      preload
      client.puts(0) # preload success
    rescue Exception
      log "preload failed"
      client.puts(1) # preload failure
      raise
    end
  end

  args, env = JSON.load(client.read(client.gets.to_i)).values_at("args", "env")
  command   = Spring.command(args.shift)

  connect_database
  setup command

  if Rails.application.reloaders.any?(&:updated?)
    Rails.application.reloader.reload!
  end

  pid = fork {
    # Make sure to close other clients otherwise their graceful termination
    # will be impossible due to reference from this fork.
    @clients.each_key { |c| c.close if c != client }

    Process.setsid
    IGNORE_SIGNALS.each { |sig| trap(sig, "DEFAULT") }
    trap("TERM", "DEFAULT")

    unless Spring.quiet
      STDERR.puts "Running via Spring preloader in process #{Process.pid}"

      if Rails.env.production?
        STDERR.puts "WARNING: Spring is running in production. To fix "         \
                    "this make sure the spring gem is only present "            \
                    "in `development` and `test` groups in your Gemfile "       \
                    "and make sure you always use "                             \
                    "`bundle install --without development test` in production"
      end
    end

    ARGV.replace(args)
    $0 = command.exec_name

    # Delete all env vars which are unchanged from before Spring started
    original_env.each { |k, v| ENV.delete k if ENV[k] == v }

    # Load in the current env vars, except those which *were* changed when Spring started
    env.each { |k, v| ENV[k] ||= v }

    connect_database
    srand

    invoke_after_fork_callbacks
    shush_backtraces

    command.call
  }

  disconnect_database

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

  wait pid, streams, client
rescue Exception => e
  log "exception: #{e}"
  manager.puts unless pid

  if streams && !e.is_a?(SystemExit)
    print_exception(stderr, e)
    streams.each(&:close)
  end

  client.puts(1) if pid
  client.close
ensure
  # Redirect STDOUT and STDERR to prevent from keeping the original FDs
  # (i.e. to prevent `spring rake -T | grep db` from hanging forever),
  # even when exception is raised before forking (i.e. preloading).
  reset_streams
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.



280
281
282
283
284
# File 'lib/spring/application.rb', line 280

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

#shush_backtracesObject

This feels very naughty



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/spring/application.rb', line 306

def shush_backtraces
  Kernel.module_eval do
    old_raise = Kernel.method(:raise)
    remove_method :raise
    if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('3.2.0')
      define_method :raise do |*args, **kwargs|
        begin
          old_raise.call(*args, **kwargs)
        ensure
          if $!
            lib = File.expand_path("..", __FILE__)
            $!.backtrace.reject! { |line| line.start_with?(lib) } unless $!.backtrace.frozen?
          end
        end
      end
    else
      define_method :raise do |*args|
        begin
          old_raise.call(*args)
        ensure
          if $!
            lib = File.expand_path("..", __FILE__)
            $!.backtrace.reject! { |line| line.start_with?(lib) } unless $!.backtrace.frozen?
          end
        end
      end
    end
    private :raise
  end
end

#spawn_envObject



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

def spawn_env
  env = JSON.load(ENV["SPRING_SPAWN_ENV"].dup).map { |key, value| "#{key}=#{value}" }
  env.join(", ") if env.any?
end

#start_watcherObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/spring/application.rb', line 72

def start_watcher
  @watcher = Spring.watcher

  @watcher.on_stale do
    state! :watcher_stale
  end

  if @watcher.respond_to? :on_debug
    @watcher.on_debug do |message|
      spring_env.log "[watcher:#{app_env}] #{message}"
    end
  end

  @watcher.start
end

#state(val) ⇒ Object



20
21
22
23
24
# File 'lib/spring/application.rb', line 20

def state(val)
  return if exiting?
  log "#{@state} -> #{val}"
  @state = val
end

#state!(val) ⇒ Object



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

def state!(val)
  state val
  @interrupt.last.write "."
end

#terminateObject



253
254
255
256
257
258
259
260
261
262
# File 'lib/spring/application.rb', line 253

def terminate
  if exiting?
    # Ensure that we do not ignore subsequent termination attempts
    log "forced exit"
    @waiting.each_key { |pid| Process.kill("TERM", pid) }
    Kernel.exit
  else
    state! :terminating
  end
end

#terminating?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/spring/application.rb', line 60

def terminating?
  @state == :terminating
end

#wait(pid, streams, client) ⇒ Object



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/spring/application.rb', line 361

def wait(pid, streams, client)
  @mutex.synchronize { @waiting[pid] = true }

  # Wait in a separate thread so we can run multiple commands at once
  Spring.failsafe_thread {
    begin
      _, status = Process.wait2 pid
      log "#{pid} exited with #{status.exitstatus}"

      streams.each(&:close)
      client.puts(status.exitstatus)
      client.close
    ensure
      @mutex.synchronize { @waiting.delete pid }
      exit_if_finished
    end
  }

  Spring.failsafe_thread {
    while signal = client.gets.chomp
      begin
        Process.kill(signal, -Process.getpgid(pid))
        client.puts(0)
      rescue Errno::ESRCH
        client.puts(1)
      end
    end
  }
end

#watcher_stale?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/spring/application.rb', line 64

def watcher_stale?
  @state == :watcher_stale
end

#with_ptyObject



343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/spring/application.rb', line 343

def with_pty
  PTY.open do |master, slave|
    [STDOUT, STDERR, STDIN].each { |s| s.reopen slave }
    reader_thread = Spring.failsafe_thread { master.read }
    begin
      yield
    ensure
      reader_thread.kill
      reset_streams
    end
  end
end