-
Notifications
You must be signed in to change notification settings - Fork 6
/
sse_client.rb
215 lines (191 loc) · 5.49 KB
/
sse_client.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
71
72
73
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
130
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
require 'httpclient'
module Plugin::SseClient
class Parser
attr_reader :buffer
def initialize(plugin, slug)
@plugin = plugin
@slug = slug
@buffer = ''
@records = []
@event = @data = nil
end
def <<(str)
@buffer += str
consume
self
end
def consume
# 改行で分割
lines = @buffer.split("\n", -1)
@buffer = lines.pop # 余りを次回に持ち越し
# SSEのメッセージパース
records = lines
.select{|l| !l.start_with?(":") } # コメント除去
.map{|l|
key, value = l.split(": ", 2)
{ key: key, value: value }
}
.select{|r|
['event', 'data', 'id', 'retry', nil].include?(r[:key])
# これら以外のフィールドは無視する(nilは空行検出のため)
# cf. https://developer.mozilla.org/ja/docs/Server-sent_events/Using_server-sent_events#Event_stream_format
}
@records.concat(records)
last_type = nil
while r = @records.shift
if last_type == 'data' && r[:key] != 'data'
if @event.nil?
@event = ''
end
Plugin.call(:sse_message_type_event, @slug, @event, @data)
Plugin.call(:"sse_on_#{@event}", @slug, @data) # 利便性のため
@event = @data = nil # 一応リセット
end
case r[:key]
when nil
# 空行→次の処理単位へ移動
@event = @data = nil
last_type = nil
when 'event'
# イベントタイプ指定
@event = r[:value]
last_type = 'event'
when 'data'
# データ本体
if @data.empty?
@data = ''
else
@data += "\n"
end
@data += r[:value]
last_type = 'data'
when 'id'
# EventSource オブジェクトの last event ID の値に設定する、イベント ID です。
Plugin.call(:sse_message_type_id, @slug, id)
@event = @data = nil # 一応リセット
last_type = 'id'
when 'retry'
# イベントの送信を試みるときに使用する reconnection time です。[What code handles this?]
# これは整数値であることが必要で、reconnection time をミリ秒単位で指定します。
# 整数値ではない値が指定されると、このフィールドは無視されます。
#
# [What code handles this?]じゃねんじゃw
if r[:value] =~ /\A-?(0|[1-9][0-9]*)\Z/
Plugin.call(:sse_message_type_retry, @slug, r[:value].to_i)
end
@event = @data = nil # 一応リセット
last_type = 'retry'
else
end
end
end
end
end
Plugin.create(:sse_client) do
pm = Plugin::Worldon
connections = {}
mutex = Thread::Mutex.new
on_sse_create do |slug, method, uri, headers = {}, params = {}, **opts|
begin
mutex.synchronize {
if connections.has_key? slug
warn "\n!!!! sse_client streaming duplicate !!!!\n"
thread = connections[slug][:thread]
connections.delete(slug)
thread.kill
end
}
conv = []
params.each do |key, val|
if val.is_a? Array
val.each do |v|
conv << [key.to_s + '[]', v]
end
else
conv << [key.to_s, val]
end
end
query = {}
body = {}
case method
when :get
query = conv
when :post
body = conv
end
Plugin.call(:sse_connection_opening, slug)
client = HTTPClient.new
thread = Thread.new {
begin
parser = Plugin::SseClient::Parser.new(self, slug)
response = client.request(method, uri.to_s, query, body, headers) do |fragment|
parser << fragment
end
case response.status
when 200
else
Plugin.call(:sse_connection_failure, slug, response)
error "ServerSentEvents connection failure"
pp response if Mopt.error_level >= 1
$stdout.flush
next
end
Plugin.call(:sse_connection_closed, slug)
rescue => e
Plugin.call(:sse_connection_error, slug, e)
error "ServerSentEvents connection error"
pp e if Mopt.error_level >= 1
$stdout.flush
next
end
}
mutex.synchronize {
connections[slug] = {
method: method,
uri: uri,
headers: headers,
params: params,
opts: opts,
thread: thread,
}
}
rescue => e
Plugin.call(:sse_connection_error, slug, e)
error "ServerSentEvents connection error"
pp e if Mopt.error_level >= 1
$stdout.flush
nil
end
end
on_sse_kill_connection do |slug|
thread = nil
mutex.synchronize {
if connections.has_key? slug
thread = connections[slug][:thread]
connections.delete(slug)
end
}
if thread
thread.kill
end
end
on_sse_kill_all do |event_sym|
threads = []
mutex.synchronize {
connections.each do |slug, hash|
threads << hash[:thread]
end
connections = {}
}
threads.each do |thread|
thread.kill
end
Plugin.call(event_sym) if event_sym
end
filter_sse_connection do |slug|
[connections[slug]]
end
filter_sse_connection_all do |_|
[connections]
end
end