| 1 |
|
| 2 |
|
| 3 |
require_relative 'cooldown_time' |
| 4 |
require_relative 'error' |
| 5 |
require_relative 'middleware/chunk_to_line' |
| 6 |
require_relative 'middleware/connection_keeping_stream' |
| 7 |
require_relative 'middleware/server_sent_events_json_parser' |
| 8 |
require_relative 'raw_server_sent_events_stream' |
| 9 |
require_relative 'splitter' |
| 10 |
|
| 11 |
情報を構築し、管理する。 |
| 12 |
、リトライ制御などを行う。 |
| 13 |
module Plugin::MastodonSseStreaming |
| 14 |
class Connection |
| 15 |
def initialize(connection_type) |
| 16 |
@thread_lock = Mutex.new |
| 17 |
@cooldown_time = CooldownTime.new |
| 18 |
@connection = Splitter.new( |
| 19 |
Middleware::ServerSentEventsJSONParser.new( |
| 20 |
Middleware::ChunkToLine.new( |
| 21 |
Middleware::ConnectionKeepingStream.new( |
| 22 |
RawServerSentEventsStream.new( |
| 23 |
connection_type |
| 24 |
), |
| 25 |
keeper: @cooldown_time |
| 26 |
) |
| 27 |
) |
| 28 |
) |
| 29 |
) |
| 30 |
end |
| 31 |
|
| 32 |
するハンドラ |
| 33 |
def add_handler(addition) |
| 34 |
@thread_lock.synchronize do |
| 35 |
@connection.add_handler(addition) |
| 36 |
unless @thread |
| 37 |
run |
| 38 |
end |
| 39 |
end |
| 40 |
self |
| 41 |
end |
| 42 |
|
| 43 |
するハンドラ |
| 44 |
def remove_handler(deletion) |
| 45 |
@thread_lock.synchronize do |
| 46 |
@connection.remove_handler(deletion) |
| 47 |
rescue NoHandlerExsitsError |
| 48 |
case @thread |
| 49 |
when Thread.current |
| 50 |
raise |
| 51 |
when Thread |
| 52 |
@thread.kill |
| 53 |
@thread = nil |
| 54 |
notice "#{@connection_type} loses all handler. disconnect" |
| 55 |
end |
| 56 |
end |
| 57 |
self |
| 58 |
end |
| 59 |
|
| 60 |
private |
| 61 |
|
| 62 |
サーバへ接続する |
| 63 |
ている状態で呼び出すこと |
| 64 |
したときに呼び出すことを期待している |
| 65 |
def run |
| 66 |
raise 'Current thread does not have @thread_lock.' unless @thread_lock.owned? |
| 67 |
@thread&.kill |
| 68 |
@thread = Thread.new do |
| 69 |
Thread.current.abort_on_exception = true |
| 70 |
@connection.run |
| 71 |
rescue NoHandlerExsitsError |
| 72 |
@thread_lock.synchronize do |
| 73 |
@thread = nil if Thread.current == @thread |
| 74 |
notice "#{@connection_type} loses all handler. disconnect" |
| 75 |
end |
| 76 |
end |
| 77 |
end |
| 78 |
end |
| 79 |
end |