Class: Protobuf::Nats::SuperSubscriptionManager

Inherits:
Object
  • Object
show all
Defined in:
lib/protobuf/nats/super_subscription_manager.rb

Constant Summary collapse

DEFAULT_INTAKE_QUEUE_BYTES =

Byte ceiling for the shared intake queue -- the aggregate-heap bound the message count alone can't give (65,536 large requests is a lot of heap). Bounds resident bytes across ALL subscriptions; the ByteBoundedQueue drops a message that would exceed it rather than block nats-pure's read thread. Default 128 MiB: higher than the client muxer's 64 MiB because the server fans requests across many handler threads and its count cap is higher too.

128 * 1024 * 1024

Instance Method Summary collapse

Constructor Details

#initialize(nats, &cb) ⇒ SuperSubscriptionManager

Returns a new instance of SuperSubscriptionManager.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 13

def initialize(nats, &cb)
  # Central queue used by all subscriptions, bounded by both message count
  # and total bytes (see intake_queue_size / intake_queue_bytes). A byte-cap
  # drop is surfaced here as server.intake_bytes_dropped.
  @pending_queue = ::Protobuf::Nats::ByteBoundedQueue.new(
    intake_queue_size, intake_queue_bytes,
    :on_drop => lambda { |bytes| ::Protobuf::Nats.instrument("server.intake_bytes_dropped", bytes) }
  )
  @subscriptions = []
  @subscriptions_mutex = ::Mutex.new
  @nats = nats
  @callback = cb

  # Fan out the intake across several handler threads. A single thread is a
  # throughput ceiling on JRuby and lets one slow publish (ACK) inside the
  # callback head-of-line block every other subject. Each handler pops the
  # shared SizedQueue (thread-safe) independently.
  @pending_queue_handlers = handler_count.times.map { |i| spawn_handler(i) }

  ::Protobuf::Nats.instrument("server.subscription_handler_count", @pending_queue_handlers.size)
end

Instance Method Details

#handler_countObject

Number of intake handler threads. On JRuby (true parallelism) fan out to processor_count; on CRuby the GVL makes extra handlers pointless, so 1. Overridable via env for tuning/tests. Mirrors ResponseMuxer#dispatcher_count.



42
43
44
45
46
47
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 42

def handler_count
  @handler_count ||= begin
    default = ::RUBY_ENGINE == "jruby" ? ::Concurrent.processor_count : 1
    ::Protobuf::Nats.env_int("PB_NATS_SERVER_SUBSCRIPTION_HANDLERS", default, :min => 1)
  end
end

#intake_queue_bytesObject

Read once, in #initialize, so no memoization is needed.



70
71
72
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 70

def intake_queue_bytes
  ::Protobuf::Nats.env_int("PB_NATS_SERVER_INTAKE_QUEUE_BYTES", DEFAULT_INTAKE_QUEUE_BYTES, :min => 1)
end

#intake_queue_sizeObject

Capacity of the shared intake queue. The nats-pure default (65,536) lets requests queue far longer than any client's ack_timeout under sustained load -- the client has retried or given up long before the message is popped, so the backlog is mostly abandoned work. A smaller size turns overload into prompt drops (and client retries with backoff) instead of a deep stale backlog. Kept at the nats-pure default for compatibility; tune down alongside PB_NATS_SERVER_STALE_REQUEST_MS.



57
58
59
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 57

def intake_queue_size
  @intake_queue_size ||= ::Protobuf::Nats.env_int("PB_NATS_SERVER_INTAKE_QUEUE_SIZE", ::NATS::IO::DEFAULT_SUB_PENDING_MSGS_LIMIT, :min => 1)
end

#loggerObject



35
36
37
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 35

def logger
  ::Protobuf::Logging.logger
end

#pending_queue_bytesObject

Resident bytes in the shared intake queue = heap backpressure (gauge).



175
176
177
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 175

def pending_queue_bytes
  @pending_queue.bytesize
end

#pending_queue_sizeObject

Depth of the shared intake queue = intake backpressure (for observability).



170
171
172
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 170

def pending_queue_size
  @pending_queue.size
end

#queue_subscribe(name) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 74

def queue_subscribe(name)
  logger.debug { "queue_subscribe(#{name})" }
  sub = @nats.subscribe(name, :queue => name)

  # Rationale on Protobuf::Nats.disable_subscription_byte_limit!.
  ::Protobuf::Nats.disable_subscription_byte_limit!(sub)

  # Create a subscription but reset the pending queue to use a central pending queue.
  existing_pending_queue = sub.pending_queue
  sub.pending_queue = @pending_queue

  # Align the slow-consumer message-count limit with the shared queue's
  # capacity. nats-pure's read thread only drops a message (SlowConsumer)
  # when pending_queue.size >= pending_msgs_limit -- otherwise it pushes.
  # With the sub's default limit (65,536) above a smaller tuned intake
  # queue, the drop check never fires and the push into the full
  # SizedQueue BLOCKS the connection's single read thread, stalling
  # PING/PONG and every other subject until a handler pops. limit ==
  # capacity makes the check trip exactly before the push would block, so
  # overload becomes prompt drops (and client NACK-style retries) as
  # intended.
  sub.pending_msgs_limit = intake_queue_size if sub.respond_to?(:pending_msgs_limit=)

  # Push all race-conditioned messages onto the pending queue.
  # Should address a potential race condition. Chances of the round-trip message to an
  # existing queue before this queue swap happens seems extremely low, but possible.
  migrated_count = 0
  max_migrations = 10000  # Safety limit

  while !existing_pending_queue.empty? && migrated_count < max_migrations
    # Non-blocking pop: another consumer could in theory drain it, so don't block.
    begin
      msg = existing_pending_queue.pop(true)
    rescue ThreadError
      break
    end

    # Push with a deadline (see push_with_deadline: no Timeout.timeout,
    # which corrupts the SizedQueue mutex on JRuby).
    if push_with_deadline(msg, 1)
      migrated_count += 1
      logger.warn "Migrated message #{migrated_count} from old queue to central queue"
    else
      logger.error "Failed to migrate message to central queue (queue full), dropping message"
      break
    end
  end

  if migrated_count >= max_migrations
    logger.error "Hit migration limit! Old queue still has #{existing_pending_queue.size} messages"
  end

  @subscriptions_mutex.synchronize { @subscriptions << sub }

  sub
end

#shutdown(timeout = 5) ⇒ Object



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
162
163
164
165
166
167
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 131

def shutdown(timeout = 5)
  handlers = @pending_queue_handlers.select(&:alive?)
  return if handlers.empty?

  # Wake every handler with its own poison pill.
  handlers.size.times do
    # Clear some space if the queue is full so the shutdown signal fits.
    if @pending_queue.num_waiting.zero? && @pending_queue.size >= @pending_queue.max
      logger.warn "Queue full during shutdown, clearing to make room for shutdown signal"
      @pending_queue.clear rescue nil
    end

    # Push with a deadline (see push_with_deadline: no Timeout.timeout,
    # which corrupts the SizedQueue mutex on JRuby).
    unless push_with_deadline(:shutdown, 1)
      logger.error "Failed to send shutdown signal (queue blocked); will force-kill remaining handlers"
      break
    end
  end

  # Join all handlers within a single shared deadline, then force-kill stragglers.
  deadline = monotonic + timeout
  handlers.each do |handler|
    remaining = deadline - monotonic
    handler.join(remaining.positive? ? remaining : 0)
  end

  handlers.each do |handler|
    next unless handler.alive?
    logger.warn "Handler thread did not shut down in time, forcefully killing..."
    handler.kill
    handler.join(1) rescue nil
  end

  # Clean up queue
  @pending_queue.clear rescue nil
end

#unsubscribe_allObject



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/protobuf/nats/super_subscription_manager.rb', line 179

def unsubscribe_all
  # Take ownership and clear: pause/resume cycles re-subscribe from
  # scratch, so keeping the old entries only grew the array without bound
  # and re-unsubscribed dead subscriptions on every later pause.
  subscriptions = @subscriptions_mutex.synchronize do
    subs = @subscriptions.dup
    @subscriptions.clear
    subs
  end
  subscriptions.each do |sub|
    begin
      sub.unsubscribe
    rescue => e
      logger.warn "Failed to unsubscribe #{sub.subject rescue 'unknown'}: #{e.message}"
    end
  end
end