Add async relay transport for Nostr WebSockets
This commit is contained in:
4 files changed
+254
No files matched your search
@@ -46,6 +46,10 @@ gem 'kramdown'
|
||||
gem 'kramdown-parser-gfm'
|
||||
gem 'device_detector'
|
||||
|
||||
# Async I/O for relay WebSockets
|
||||
gem 'async', '~> 2.46'
|
||||
gem 'async-websocket', '~> 0.30'
|
||||
|
||||
# HTTP requests
|
||||
gem 'faraday'
|
||||
gem 'down'
|
||||
|
||||
@@ -80,6 +80,26 @@ GEM
|
||||
addressable (2.8.7)
|
||||
public_suffix (>= 2.0.2, < 7.0)
|
||||
ast (2.4.3)
|
||||
async (2.46.0)
|
||||
console (~> 1.29)
|
||||
fiber-annotation
|
||||
io-event (~> 1.21)
|
||||
async-http (0.105.0)
|
||||
async (>= 2.35.1)
|
||||
async-pool (~> 0.12)
|
||||
io-endpoint (~> 0.18)
|
||||
io-stream (~> 0.14)
|
||||
protocol-http (~> 0.72)
|
||||
protocol-http1 (~> 0.41)
|
||||
protocol-http2 (~> 0.28)
|
||||
protocol-url (~> 0.2)
|
||||
async-pool (0.12.0)
|
||||
async (>= 2.0)
|
||||
async-websocket (0.30.2)
|
||||
async-http (~> 0.76)
|
||||
protocol-http (~> 0.34)
|
||||
protocol-rack (~> 0.7)
|
||||
protocol-websocket (~> 0.17)
|
||||
aws-eventstream (1.3.2)
|
||||
aws-partitions (1.1092.0)
|
||||
aws-sdk-core (3.222.2)
|
||||
@@ -123,6 +143,10 @@ GEM
|
||||
chunky_png (1.4.0)
|
||||
concurrent-ruby (1.3.8)
|
||||
connection_pool (3.0.2)
|
||||
console (1.38.0)
|
||||
fiber-annotation
|
||||
fiber-local (~> 1.1)
|
||||
json
|
||||
crack (1.0.0)
|
||||
bigdecimal
|
||||
rexml
|
||||
@@ -189,6 +213,10 @@ GEM
|
||||
ffi (1.17.2)
|
||||
ffi (1.17.2-arm64-darwin)
|
||||
ffi (1.17.2-x86_64-linux-gnu)
|
||||
fiber-annotation (0.2.0)
|
||||
fiber-local (1.1.0)
|
||||
fiber-storage
|
||||
fiber-storage (1.0.1)
|
||||
flipper (1.3.4)
|
||||
concurrent-ruby (< 2)
|
||||
flipper-active_record (1.3.4)
|
||||
@@ -219,6 +247,11 @@ GEM
|
||||
activesupport (>= 6.0.0)
|
||||
railties (>= 6.0.0)
|
||||
io-console (0.9.2)
|
||||
io-endpoint (0.19.0)
|
||||
openssl (>= 3.3.0)
|
||||
io-event (1.22.3)
|
||||
io-stream (0.14.0)
|
||||
openssl (>= 3.3)
|
||||
irb (1.18.0)
|
||||
pp (>= 0.6.0)
|
||||
prism (>= 1.3.0)
|
||||
@@ -313,6 +346,7 @@ GEM
|
||||
faye-websocket (~> 0.11)
|
||||
json (~> 2.6)
|
||||
observer (0.1.2)
|
||||
openssl (4.0.2)
|
||||
orm_adapter (0.5.0)
|
||||
ostruct (0.6.1)
|
||||
pagy (6.5.0)
|
||||
@@ -329,6 +363,21 @@ GEM
|
||||
actionpack (>= 7.0.0)
|
||||
activesupport (>= 7.0.0)
|
||||
rack
|
||||
protocol-hpack (1.5.1)
|
||||
protocol-http (0.72.1)
|
||||
protocol-http1 (0.41.1)
|
||||
protocol-http (~> 0.68)
|
||||
protocol-http2 (0.29.2)
|
||||
protocol-hpack (~> 1.4)
|
||||
protocol-http (~> 0.62)
|
||||
protocol-rack (0.23.0)
|
||||
console (~> 1.0)
|
||||
io-stream (>= 0.10)
|
||||
protocol-http (~> 0.58)
|
||||
rack (>= 1.0)
|
||||
protocol-url (0.19.0)
|
||||
protocol-websocket (0.21.3)
|
||||
protocol-http (~> 0.2)
|
||||
psych (5.4.0)
|
||||
date
|
||||
stringio
|
||||
@@ -539,6 +588,8 @@ PLATFORMS
|
||||
|
||||
DEPENDENCIES
|
||||
aasm
|
||||
async (~> 2.46)
|
||||
async-websocket (~> 0.30)
|
||||
aws-sdk-s3
|
||||
bcrypt (~> 3.1)
|
||||
capybara
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
require "json"
|
||||
|
||||
module NostrManager
|
||||
module Relay
|
||||
class Connection
|
||||
attr_reader :url
|
||||
|
||||
def initialize(url:, socket:)
|
||||
@url = url
|
||||
@socket = socket
|
||||
end
|
||||
|
||||
def write_json(message)
|
||||
@socket.write(JSON.generate(message))
|
||||
@socket.flush
|
||||
end
|
||||
|
||||
def read_json
|
||||
message = @socket.read
|
||||
return nil if message.nil?
|
||||
|
||||
JSON.parse(message.to_str)
|
||||
rescue JSON::ParserError
|
||||
nil
|
||||
end
|
||||
|
||||
def close
|
||||
@socket.close
|
||||
rescue StandardError
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,165 @@
|
||||
require "async"
|
||||
require "async/http/endpoint"
|
||||
require "async/http/protocol/http11"
|
||||
require "async/queue"
|
||||
require "async/websocket/client"
|
||||
require "securerandom"
|
||||
|
||||
module NostrManager
|
||||
module Relay
|
||||
# Owns one async reactor and one websocket per relay for the duration of a block.
|
||||
class Pool
|
||||
Result = Struct.new(:url, :message, keyword_init: true)
|
||||
|
||||
class TimeoutError < StandardError; end
|
||||
|
||||
DEFAULT_TIMEOUT = 30
|
||||
DEFAULT_CONNECT_TIMEOUT = 5
|
||||
|
||||
def self.with(relays:, timeout: DEFAULT_TIMEOUT, connect_timeout: DEFAULT_CONNECT_TIMEOUT,
|
||||
logger: Rails.logger, &block)
|
||||
Async do |task|
|
||||
pool = new(relays: relays, task: task, connect_timeout: connect_timeout, logger: logger)
|
||||
begin
|
||||
pool.start
|
||||
task.with_timeout(timeout) { block.call(pool) }
|
||||
ensure
|
||||
pool.close
|
||||
end
|
||||
end.wait
|
||||
rescue Async::TimeoutError
|
||||
raise TimeoutError, "relay operation timed out"
|
||||
end
|
||||
|
||||
def initialize(relays:, task:, connect_timeout: DEFAULT_CONNECT_TIMEOUT, logger: Rails.logger)
|
||||
@relays = Array(relays).map(&:to_s).reject(&:blank?).uniq
|
||||
@task = task
|
||||
@connect_timeout = connect_timeout
|
||||
@logger = logger
|
||||
@connections = {}
|
||||
@subscriptions = {}
|
||||
@inbox = Async::Queue.new
|
||||
@ready_connections = 0
|
||||
@closed = false
|
||||
end
|
||||
|
||||
def start
|
||||
raise ArgumentError, "at least one relay is required" if @relays.empty?
|
||||
|
||||
@tasks = @relays.map { |url| @task.async { run(url) } }
|
||||
self
|
||||
end
|
||||
|
||||
def subscribe(filter, id: SecureRandom.hex(8), wait: true, timeout: @connect_timeout)
|
||||
@subscriptions[id] = filter
|
||||
@connections.each_value { |connection| send_request(connection, ["REQ", id, filter.to_h]) }
|
||||
wait_for_subscription(id, timeout: timeout) if wait
|
||||
id
|
||||
end
|
||||
|
||||
def wait_for_subscription(id, timeout: @connect_timeout)
|
||||
deferred = []
|
||||
|
||||
wait_for(timeout: timeout) do |result|
|
||||
message = result.message
|
||||
if message.is_a?(Array) && message[0] == "EOSE" && message[1] == id
|
||||
true
|
||||
else
|
||||
deferred << result
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
true
|
||||
rescue TimeoutError
|
||||
@logger.info "[nostr][relay] no EOSE for subscription #{id} within #{timeout}s"
|
||||
false
|
||||
ensure
|
||||
deferred.reverse_each { |result| @inbox.enqueue(result) } if deferred
|
||||
end
|
||||
|
||||
def unsubscribe(id)
|
||||
@subscriptions.delete(id)
|
||||
@connections.each_value { |connection| send_request(connection, ["CLOSE", id]) }
|
||||
end
|
||||
|
||||
def publish(event)
|
||||
wait_for_connection
|
||||
payload = ["EVENT", event.to_h.transform_keys(&:to_s)]
|
||||
@connections.each_value { |connection| send_request(connection, payload) }
|
||||
true
|
||||
end
|
||||
|
||||
def wait_for(timeout: 10)
|
||||
deadline = monotonic_now + timeout
|
||||
|
||||
loop do
|
||||
remaining = deadline - monotonic_now
|
||||
raise TimeoutError, "timed out waiting for a relay message" if remaining <= 0
|
||||
|
||||
result = @task.with_timeout(remaining) { @inbox.dequeue }
|
||||
return result if yield(result)
|
||||
end
|
||||
rescue Async::TimeoutError
|
||||
raise TimeoutError, "timed out waiting for a relay message"
|
||||
end
|
||||
|
||||
def wait_for_connection(timeout: @connect_timeout)
|
||||
deadline = monotonic_now + timeout
|
||||
@task.sleep(0.01) while @ready_connections.zero? && monotonic_now < deadline
|
||||
|
||||
raise TimeoutError, "no relay connection became ready" if @ready_connections.zero?
|
||||
|
||||
true
|
||||
end
|
||||
|
||||
def close
|
||||
return if @closed
|
||||
|
||||
@closed = true
|
||||
@tasks&.each(&:stop)
|
||||
@connections.each_value(&:close)
|
||||
@connections.clear
|
||||
@subscriptions.clear
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def run(url)
|
||||
endpoint = Async::HTTP::Endpoint.parse(
|
||||
url,
|
||||
alpn_protocols: Async::HTTP::Protocol::HTTP11.names
|
||||
)
|
||||
|
||||
Async::WebSocket::Client.connect(endpoint) do |socket|
|
||||
connection = Connection.new(url: url, socket: socket)
|
||||
@connections[url] = connection
|
||||
@subscriptions.each { |id, filter| send_request(connection, ["REQ", id, filter.to_h]) }
|
||||
@ready_connections += 1
|
||||
|
||||
while (message = connection.read_json)
|
||||
@logger.debug "[nostr][relay] #{url} <- #{message[0]}"
|
||||
@inbox.enqueue(Result.new(url: url, message: message))
|
||||
end
|
||||
rescue StandardError => e
|
||||
@logger.info "[nostr][relay] #{url} error: #{e.class}: #{e.message}"
|
||||
ensure
|
||||
@connections.delete(url)
|
||||
end
|
||||
rescue StandardError => e
|
||||
@logger.info "[nostr][relay] #{url} connection failed: #{e.class}: #{e.message}"
|
||||
end
|
||||
|
||||
def send_request(connection, payload)
|
||||
connection.write_json(payload)
|
||||
rescue StandardError => e
|
||||
@logger.info "[nostr][relay] #{connection.url} write failed: #{e.class}: #{e.message}"
|
||||
@connections.delete(connection.url)
|
||||
end
|
||||
|
||||
def monotonic_now
|
||||
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user