Module: Tina4::Shutdown

Defined in:
lib/tina4/shutdown.rb

Constant Summary collapse

DEFAULT_TIMEOUT =

seconds

30

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.in_flight_countObject (readonly)

Returns the value of attribute in_flight_count.



8
9
10
# File 'lib/tina4/shutdown.rb', line 8

def in_flight_count
  @in_flight_count
end

Class Method Details

.initiate_shutdownObject



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
66
67
68
69
70
# File 'lib/tina4/shutdown.rb', line 37

def initiate_shutdown
  return if @shutting_down

  @shutting_down = true
  Tina4::Log.info("Shutdown signal received, stopping gracefully...")

  # Wait for in-flight requests with timeout
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + @timeout
  @mutex.synchronize do
    while @in_flight_count > 0
      remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
      if remaining <= 0
        Tina4::Log.warning("Shutdown timeout reached with #{@in_flight_count} requests still in flight")
        break
      end
      @in_flight_cv.wait(@mutex, remaining)
    end
  end

  # Close database connections
  if Tina4.database
    begin
      Tina4.database.close
      Tina4::Log.info("Database connections closed")
    rescue => e
      Tina4::Log.error("Error closing database: #{e.message}")
    end
  end

  Tina4::Log.info("Shutdown complete")

  # Stop the server
  @server&.shutdown if @server.respond_to?(:shutdown)
end

.setup(server: nil, timeout: nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/tina4/shutdown.rb', line 10

def setup(server: nil, timeout: nil)
  @server = server
  @timeout = (timeout || ENV["TINA4_SHUTDOWN_TIMEOUT"] || DEFAULT_TIMEOUT).to_i
  @shutting_down = false
  @mutex = Mutex.new
  @in_flight_count = 0
  @in_flight_cv = ConditionVariable.new

  install_signal_handlers
end

.shutting_down?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/tina4/shutdown.rb', line 21

def shutting_down?
  @shutting_down
end

.track_requestObject



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/tina4/shutdown.rb', line 25

def track_request
  @mutex.synchronize { @in_flight_count += 1 }
  begin
    yield
  ensure
    @mutex.synchronize do
      @in_flight_count -= 1
      @in_flight_cv.broadcast if @in_flight_count <= 0
    end
  end
end