Debian Codegraph @

plugin/mastodon_sse_streaming/middleware/server_sent_events_json_parser.rb

raw symbols SCIP
1 # frozen_string_literal: true
2
3 module Plugin::MastodonSseStreaming::Middleware
4 =begin yard
5 SSEのレスポンスを行ごとに分割して列挙されたものを [イベント種別, JSONをパースしたHash] 形式のデータの列挙に変換する
6 @example
7 入力
8 [
9 "event: status",
10 "data: {\"body\":\"みくのおっぱいにおかおをうずめてすーはーすーはーいいかおり!\"}",
11 "",
12 "event: status",
13 "data:{\"body\":\"みくのおっぱい柔らかぁい。柔軟剤使ったのか?\"}",
14 ""
15 ]
16 出力
17 [
18 [
19 "status",
20 {
21 body: "みくのおっぱいにおかおをうずめてすーはーすーはーいいかおり!"
22 }
23 ],
24 [
25 "status",
26 {
27 body: "みくのおっぱい柔らかぁい。柔軟剤使ったのか?"
28 }
29 ]
30 ]
31 =end
32 class ServerSentEventsJSONParser
33 # これら以外のフィールドは無視する(nilは空行検出のため)
34 # cf. https://developer.mozilla.org/ja/docs/Server-sent_events/Using_server-sent_events#Event_stream_formata
35 EVENT_TYPE_WHITELIST = ['event', 'data', 'id', 'retry', nil].freeze
36
37 # @params [Enumerable[String]] lined_string_stream 行ごとに区切られた文字列を列挙する。ただし、要素となるStringは末尾に改行文字がないこと
38 def initialize(lined_string_stream)
39 @stream = lined_string_stream
40 end
41
42 # 接続する
43 def to_enum
44 Enumerator.new do |yielder|
45 last_type = nil
46 data_accumlator = []
47 event_type = nil
48 @stream.to_enum.lazy.map { |l|
49 l.split(':', 2).map(&:strip)
50 }.select { |key, _|
51 EVENT_TYPE_WHITELIST.include?(key)
52 }.each do |type, payload|
53 if last_type == 'data' && type != 'data'
54 parsed =
55 begin
56 JSON.parse(data_accumlator.join("\n"), symbolize_names: true)
57 rescue StandardError => exception
58 notice exception
59 nil
60 end
61 yielder << [event_type, parsed] if parsed
62 event_type = nil
63 data_accumlator = []
64 end
65
66 case type
67 when nil, 'id', 'retry'
68 # noop
69 event_type = nil
70 data_accumlator = []
71 when 'event'
72 # イベントタイプ指定
73 event_type = payload
74 when 'data'
75 # データ本体
76 data_accumlator << payload
77 end
78 last_type = type
79 end
80 end
81 end
82 end
83 end