mirror of
https://github.com/basecamp/once-campfire.git
synced 2026-10-08 07:40:08 +09:00
53520d4444
Since push delivery was pinned to the IP resolved and guarded for it, every push opens a new TCP and TLS connection: Net::HTTP::Persistent looks the host up itself and can't be pinned. The handshake is one or two extra round trips for every push. WebPush::Connections keeps the pinned connections open for 30 seconds and hands one out again only to a delivery whose own, fresh resolution returned the same address for the same host. Net::HTTP only ever reconnects to that address, so no request goes to an address the guard didn't just approve. A connection the push service closed while idle is replaced before the push is written; once it's written, a dropped connection raises ConnectionLost instead of sending the push twice or invalidating the subscription. A delivery without a resolved IP is no longer sent at all, and net-http-persistent goes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0142qgjggdJ2KDdGk7RF9Xm9
57 lines
1.8 KiB
Ruby
57 lines
1.8 KiB
Ruby
# This is in lib so we can use it in a thread pool without the Rails executor
|
|
class WebPush::Pool
|
|
attr_reader :delivery_pool, :invalidation_pool, :connection, :invalid_subscription_handler
|
|
|
|
def initialize(invalid_subscription_handler:)
|
|
@delivery_pool = Concurrent::ThreadPoolExecutor.new(max_threads: 50, max_queue: 10000)
|
|
@invalidation_pool = Concurrent::FixedThreadPool.new(1)
|
|
@connection = WebPush::Connections.new
|
|
@invalid_subscription_handler = invalid_subscription_handler
|
|
end
|
|
|
|
def queue(payload, subscriptions)
|
|
subscriptions.find_each do |subscription|
|
|
deliver_later(payload, subscription)
|
|
end
|
|
end
|
|
|
|
def shutdown
|
|
connection.shutdown
|
|
shutdown_pool(delivery_pool)
|
|
shutdown_pool(invalidation_pool)
|
|
end
|
|
|
|
private
|
|
def deliver_later(payload, subscription)
|
|
# Ensure any AR operations happen before we post to the thread pool
|
|
notification = subscription.notification(**payload)
|
|
subscription_id = subscription.id
|
|
|
|
delivery_pool.post do
|
|
deliver(notification, subscription_id)
|
|
rescue Exception => e
|
|
Rails.logger.error "Error in WebPush::Pool.deliver: #{e.class} #{e.message}"
|
|
end
|
|
rescue Concurrent::RejectedExecutionError
|
|
end
|
|
|
|
def deliver(notification, id)
|
|
notification.deliver(connection: connection)
|
|
rescue WebPush::ExpiredSubscription, OpenSSL::OpenSSLError => ex
|
|
invalidate_subscription_later(id) if invalid_subscription_handler
|
|
end
|
|
|
|
def invalidate_subscription_later(id)
|
|
invalidation_pool.post do
|
|
invalid_subscription_handler.call(id)
|
|
rescue Exception => e
|
|
Rails.logger.error "Error in WebPush::Pool.invalid_subscription_handler: #{e.class} #{e.message}"
|
|
end
|
|
end
|
|
|
|
def shutdown_pool(pool)
|
|
pool.shutdown
|
|
pool.kill unless pool.wait_for_termination(1)
|
|
end
|
|
end
|