Repository navigation
Expand file tree
/
Copy pathwebsocket.py
More file actions
1674 lines (1430 loc) · 86.2 KB
/
Copy pathwebsocket.py
File metadata and controls
1674 lines (1430 loc) · 86.2 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import random
import time
from dataclasses import dataclass
from datetime import datetime
from typing import Annotated, Any, cast
import websockets.exceptions
from fastapi import APIRouter, Path, Query
from starlette.websockets import (
WebSocket,
WebSocketDisconnect,
WebSocketState,
)
from tortoise.backends.base.client import TransactionalDBClient
from tortoise.exceptions import DoesNotExist
from app import logging
from app.constants import (
JST,
KNOWN_JIKKYO_CHANNEL_IDS,
REDIS_CHANNEL_THREAD_COMMENTS_PREFIX,
REDIS_CLIENT,
REDIS_KEY_JIKKYO_FORCE_COUNT,
REDIS_KEY_VIEWER_COUNT,
)
from app.models.comment import (
Comment,
CommentCounter,
Thread,
XMLCompatibleCommentResponse,
XMLCompatibleCommentResponseChat,
)
from app.utils import GenerateClientID
from app.utils.comment_counter_cache import (
GetThreadCommentCounterCache,
UpdateThreadCommentCounterCache,
)
from app.utils.transaction import (
IsDatabaseConnectionUnavailableError,
RunTransactionWithReconnectRetry,
)
# ルーター
router = APIRouter(
tags = ['WebSocket'],
prefix = '/api/v1',
)
# 現在アクティブなスレッドの情報を保存する辞書
__active_threads: dict[int, Thread] = {}
# 接続ごとのコメント送信キューの最大サイズ
COMMENT_QUEUE_MAX_SIZE = 200
# コメントセッションの thread コマンドで、1回に取得できるコメント数 (res_from の絶対値) の上限
## 極端に大きい res_from で DB に重いクエリを実行させられないよう、これを超える値は上限に切り詰める
MAX_COMMENTS_PER_THREAD_COMMAND = 10000
# unknown channel の拒否ログを集約して出力する間隔 (秒)
UNKNOWN_CHANNEL_LOG_INTERVAL_SECONDS = 60.0
# unknown channel ごとの拒否回数
unknown_channel_reject_count_by_channel_id: dict[str, int] = {}
# unknown channel 拒否ログを最後に出力した時刻
last_unknown_channel_summary_log_time = 0.0
# unknown channel 集約カウンタ更新の排他ロック
unknown_channel_summary_lock = asyncio.Lock()
@dataclass(slots=True)
class CommentBroadcastMessage:
"""
Redis Pub/Sub から受信したコメントを接続ごとの送信キューに流すためのメッセージ
Attributes:
raw_json (str): Redis Pub/Sub から受信した生の JSON 文字列
base_comment (XMLCompatibleCommentResponse): JSON をデコードしたコメントデータ
user_id (str): コメント投稿者のユーザー ID
"""
raw_json: str
base_comment: XMLCompatibleCommentResponse
user_id: str
@dataclass(slots=True)
class CommentSubscriber:
"""
リアルタイムコメント配信用の接続情報
Attributes:
client_id (str): コメントセッションのクライアント ID
thread_key (str): thread コマンドで指定された threadkey
queue (asyncio.Queue[CommentBroadcastMessage]): 接続ごとのコメント送信キュー
"""
client_id: str
thread_key: str
queue: asyncio.Queue[CommentBroadcastMessage]
def CopyXMLCompatibleCommentResponse(response: XMLCompatibleCommentResponse) -> XMLCompatibleCommentResponse:
"""
XMLCompatibleCommentResponse を浅くコピーして返す
Args:
response (XMLCompatibleCommentResponse): コピー対象のコメントデータ
Returns:
XMLCompatibleCommentResponse: コピーされたコメントデータ
"""
copied_response = dict(response)
copied_response['chat'] = cast(XMLCompatibleCommentResponseChat, dict(response['chat']))
return cast(XMLCompatibleCommentResponse, copied_response)
def EnqueueBroadcastMessage(
subscriber: CommentSubscriber,
message: CommentBroadcastMessage,
) -> None:
"""
接続ごとの送信キューへコメントを追加する
Args:
subscriber (CommentSubscriber): コメント送信先の接続情報
message (CommentBroadcastMessage): 配信するコメント
"""
if subscriber.queue.full() is True:
# キューが溢れそうな場合は古いコメントを捨てる
try:
subscriber.queue.get_nowait()
except asyncio.QueueEmpty:
pass
try:
subscriber.queue.put_nowait(message)
except asyncio.QueueFull:
# ここに到達するのは非常に稀だが、念のため握りつぶす
pass
class ThreadCommentBroadcaster:
"""
スレッド単位で Redis Pub/Sub を購読し、接続ごとの送信キューにコメントを配信する
"""
def __init__(self, thread_id: int) -> None:
"""
Args:
thread_id (int): コメント配信対象のスレッド ID
"""
self.thread_id = thread_id
self.subscribers: dict[str, CommentSubscriber] = {}
self.lock = asyncio.Lock()
self._run_task: asyncio.Task[None] | None = None
async def addSubscriber(self, subscriber_id: str, subscriber: CommentSubscriber) -> None:
"""
コメント配信対象の接続を追加する
Args:
subscriber_id (str): 接続を識別する ID
subscriber (CommentSubscriber): 追加する接続情報
"""
# 接続一覧は複数タスクから同時に更新されるためロックで保護する
async with self.lock:
# 接続情報を登録する
self.subscribers[subscriber_id] = subscriber
# 配信タスクが未起動または終了済みなら新しいタスクを開始する
# _run_task.done() は正常終了・例外終了・キャンセル済みのいずれも True を返す
## これにより、_run() が予期せぬ例外で終了した場合でも、次の購読者追加時に自動的に再起動される
if self._run_task is None or self._run_task.done():
self._run_task = asyncio.create_task(self._run())
async def removeSubscriber(self, subscriber_id: str, subscriber: CommentSubscriber) -> None:
"""
コメント配信対象の接続を削除する
Args:
subscriber_id (str): 削除する接続の ID
subscriber (CommentSubscriber): 削除対象の接続情報
"""
# 接続一覧は複数タスクから同時に更新されるためロックで保護する
# タスクのキャンセルと待機もロック内で行い、レースコンディションを防ぐ
## キャンセルされたタスクは即座に終了するため、ロック内での await でもデッドロックは発生しない
async with self.lock:
# 接続が登録されている場合のみ削除する
if subscriber_id in self.subscribers and self.subscribers[subscriber_id] is subscriber:
del self.subscribers[subscriber_id]
# 接続が存在しなくなった場合は配信タスクを停止する
if len(self.subscribers) == 0 and self._run_task is not None:
self._run_task.cancel()
try:
await self._run_task
except asyncio.CancelledError:
pass
self._run_task = None
async def getSubscriberCount(self) -> int:
"""
現在の接続数を取得する
Returns:
int: 現在の接続数
"""
# 接続一覧は複数タスクから同時に更新されるためロックで保護する
async with self.lock:
return len(self.subscribers)
async def _getSubscriberSnapshot(self) -> list[CommentSubscriber]:
"""
コメント配信対象の接続一覧をスナップショットとして取得する
Returns:
list[CommentSubscriber]: コメント配信対象の接続一覧
"""
# 配信時は現在の接続一覧のスナップショットを使う
## 配信中に接続一覧が変わっても影響しないようにする
async with self.lock:
return list(self.subscribers.values())
async def _run(self) -> None:
"""
Redis Pub/Sub を購読し、接続ごとの送信キューにコメントを配信する
予期せぬ例外が発生した場合は指数バックオフでリトライし、配信を継続する。
CancelledError が発生した場合のみタスクを終了する。
"""
# リトライ用のバックオフ設定
retry_delay = 1.0 # 初期リトライ間隔 (秒)
max_retry_delay = 30.0 # 最大リトライ間隔 (秒)
while True:
pubsub = REDIS_CLIENT.pubsub()
should_retry = False
try:
# スレッド単位の Pub/Sub でコメントを受信する
await pubsub.subscribe(f'{REDIS_CHANNEL_THREAD_COMMENTS_PREFIX}:{self.thread_id}')
# 正常に接続できたらリトライ間隔をリセット
retry_delay = 1.0
while True:
# コメントが来るまで最大 5 秒待機する
message = await pubsub.get_message(ignore_subscribe_messages=True, timeout=5.0)
if message is None:
continue
# Redis から受信したコメントを JSON 文字列として扱う
raw_payload = message['data']
if isinstance(raw_payload, bytes | bytearray | memoryview):
raw_json = bytes(raw_payload).decode('utf-8')
elif isinstance(raw_payload, str):
raw_json = raw_payload
else:
raw_json = json.dumps(raw_payload, ensure_ascii=False, separators=(',', ':'))
try:
# Redis から受信した JSON をデコードする
base_comment: XMLCompatibleCommentResponse = json.loads(raw_json)
except json.JSONDecodeError:
logging.error('ThreadCommentBroadcaster: Failed to decode comment JSON.')
continue
if 'chat' not in base_comment:
logging.error('ThreadCommentBroadcaster: Comment JSON does not contain chat data.')
continue
# yourpost 判定に必要な情報を先に抽出する
# yourpost が含まれている場合は非 yourpost に流れないように事前に除去する
if 'yourpost' in base_comment['chat']:
del base_comment['chat']['yourpost']
raw_json = json.dumps(base_comment, ensure_ascii=False, separators=(',', ':'))
user_id = str(base_comment['chat'].get('user_id', ''))
broadcast_message = CommentBroadcastMessage(
raw_json = raw_json,
base_comment = base_comment,
user_id = user_id,
)
# 現在接続中の全クライアントへ同一メッセージを配信する
subscribers = await self._getSubscriberSnapshot()
for subscriber in subscribers:
EnqueueBroadcastMessage(subscriber, broadcast_message)
except asyncio.CancelledError:
# キャンセルされた場合はタスクを終了する
raise
except Exception as ex:
# 予期せぬ例外が発生した場合はログを出力してリトライする
logging.error(f'ThreadCommentBroadcaster: Unexpected error occurred while broadcasting. Retrying in {retry_delay} seconds...', exc_info=ex)
should_retry = True
finally:
# 各リトライごとに確実に購読解除する
try:
await pubsub.unsubscribe(f'{REDIS_CHANNEL_THREAD_COMMENTS_PREFIX}:{self.thread_id}')
await pubsub.close()
except Exception as cleanup_ex:
logging.error('ThreadCommentBroadcaster: Failed to cleanup Redis pubsub connection:', exc_info=cleanup_ex)
if should_retry is True:
# 指数バックオフでリトライ間隔を増加させる
await asyncio.sleep(retry_delay)
retry_delay = min(retry_delay * 2, max_retry_delay)
# スレッド単位のコメント配信用 Broadcaster を保存する辞書
__thread_comment_broadcasters: dict[int, ThreadCommentBroadcaster] = {}
__thread_comment_broadcasters_lock = asyncio.Lock()
async def GetThreadCommentBroadcaster(thread_id: int) -> ThreadCommentBroadcaster:
"""
スレッド単位のコメント配信用 Broadcaster を取得する
Args:
thread_id (int): コメント配信対象のスレッド ID
Returns:
ThreadCommentBroadcaster: スレッド単位のコメント配信用 Broadcaster
"""
async with __thread_comment_broadcasters_lock:
broadcaster = __thread_comment_broadcasters.get(thread_id)
if broadcaster is None:
broadcaster = ThreadCommentBroadcaster(thread_id)
__thread_comment_broadcasters[thread_id] = broadcaster
return broadcaster
async def CleanupThreadCommentBroadcaster(thread_id: int, broadcaster: ThreadCommentBroadcaster) -> None:
"""
接続が存在しない Broadcaster を辞書から削除する
Args:
thread_id (int): 対象のスレッド ID
broadcaster (ThreadCommentBroadcaster): 対象の Broadcaster
"""
# デッドロックを防ぐため、ロック取得順序を固定する
# 常に __thread_comment_broadcasters_lock → broadcaster.lock の順で取得する
## getSubscriberCount() は内部で broadcaster.lock を取得するため、
## __thread_comment_broadcasters_lock を保持した状態で呼び出すとネストされたロックになる
## そのため、ここでは直接 subscribers の長さを確認してデッドロックを回避する
async with __thread_comment_broadcasters_lock:
current_broadcaster = __thread_comment_broadcasters.get(thread_id)
if current_broadcaster is not broadcaster:
return
# broadcaster.lock を取得して購読者数を確認し、0 なら削除する
async with broadcaster.lock:
if len(broadcaster.subscribers) == 0:
del __thread_comment_broadcasters[thread_id]
async def LogUnknownChannelRejected(channel_id: str) -> None:
"""
unknown channel 拒否ログを 1 分単位で集約して出力する
Args:
channel_id (str): 拒否対象の実況チャンネル ID
"""
global last_unknown_channel_summary_log_time
# ログ集約判定に使う現在時刻を取得する
current_time = time.time()
# ロック外で使う出力用の値を初期化する
should_log_summary = False
summary_total_count = 0
summary_detail = ''
# 集約カウンタは複数接続から同時に更新されるためロックで保護する
async with unknown_channel_summary_lock:
# チャンネルごとの拒否回数を加算する
current_count = unknown_channel_reject_count_by_channel_id.get(channel_id, 0)
unknown_channel_reject_count_by_channel_id[channel_id] = current_count + 1
# 初回呼び出し時に集約開始時刻を初期化する
if last_unknown_channel_summary_log_time == 0.0:
last_unknown_channel_summary_log_time = current_time
# まだ集約間隔に達していなければ次回へ持ち越す
elapsed_seconds = current_time - last_unknown_channel_summary_log_time
if elapsed_seconds < UNKNOWN_CHANNEL_LOG_INTERVAL_SECONDS:
return
# 現時点の集約結果をスナップショット化してカウンタをリセットする
snapshot = dict(unknown_channel_reject_count_by_channel_id)
unknown_channel_reject_count_by_channel_id.clear()
last_unknown_channel_summary_log_time = current_time
# 出力するチャンネル詳細は件数の多い順に上位 10 件までに絞る
summary_total_count = sum(snapshot.values())
sorted_snapshot = sorted(snapshot.items(), key=lambda item: item[1], reverse=True)
top_channels = sorted_snapshot[:10]
summary_detail = ', '.join(
f'{snapshot_channel_id}: {snapshot_count}'
for snapshot_channel_id, snapshot_count in top_channels
)
if summary_detail == '':
summary_detail = 'none'
should_log_summary = True
# ロック外で warning を出すことで、ロック保持時間を最小化する
if should_log_summary is True:
logging.warning(
'WatchSessionAPI: Rejected unknown channel requests in last 60 seconds. '
f'total: {summary_total_count}, details: {summary_detail}'
)
async def GetActiveThread(channel_id_int: int) -> Thread | None:
"""
現在アクティブな (放送されている) スレッド情報を取得する
Args:
channel_id_int (int): 実況チャンネル ID (jk の prefix を取り除いた数値)
Returns:
Thread | None: 現在アクティブなスレッドの情報。見つからない場合は None を返す
"""
# 現在のサーバー時刻 (datetime)
current_time_datetime = datetime.now(JST)
# 実況チャンネル ID に対応する現在アクティブなスレッド情報が保存されていないか、キャッシュされたスレッド情報がすでに放送を終了している場合は、
# 実況チャンネル ID に対応する現在アクティブなスレッド情報を取得し、__active_threads に保存する
if channel_id_int not in __active_threads or __active_threads[channel_id_int].end_at < current_time_datetime:
thread = await Thread.filter(
channel_id = channel_id_int,
start_at__lte = current_time_datetime,
end_at__gte = current_time_datetime,
).first()
# 実況チャンネル ID に対応するスレッドが見つからなかった
if not thread:
return None
# キャッシュを新しいスレッド情報で更新
__active_threads[channel_id_int] = thread
logging.info(f'GetActiveThread [jk{channel_id_int}]: Active thread has been updated.')
# 現在アクティブなスレッド情報を取得して返す
return __active_threads[channel_id_int]
def ConvertToXMLCompatibleCommentResponse(comment: Comment) -> XMLCompatibleCommentResponse:
"""
コメント情報をニコ生 XML 互換の XMLCompatibleCommentResponse 形式に変換する
戻り値の辞書は SetYourPostFlag() を通した後、await websocket.send_json() に渡してクライアントに送信できる
この関数では yourpost フラグは設定されないので、別途 SetYourPostFlag() を通して設定する必要がある
"""
response: XMLCompatibleCommentResponse = {
'chat': {
'thread': str(comment.thread_id),
'no': comment.no,
'vpos': comment.vpos,
'date': int(comment.date.timestamp()),
'date_usec': int((comment.date.timestamp() - int(comment.date.timestamp())) * 1000000),
'mail': comment.mail,
'user_id': comment.user_id,
'premium': 1 if comment.premium else 0,
'anonymity': 1 if comment.anonymity else 0,
'content': comment.content,
},
}
# 数値を返すフィールドは 0 の場合に省略される本家ニコ生の謎仕様に合わせる
if 'premium' in response['chat'] and response['chat']['premium'] == 0:
del response['chat']['premium']
if 'anonymity' in response['chat'] and response['chat']['anonymity'] == 0:
del response['chat']['anonymity']
return response
def SetYourPostFlag(response: XMLCompatibleCommentResponse, thread_key: str) -> XMLCompatibleCommentResponse:
"""
スレッドキーとユーザー ID が一致する場合のみ、コメント情報に yourpost (自分が投稿したコメントかどうか) フラグを設定する
"""
# スレッドキーとユーザー ID が一致する場合のみ yourpost フラグを設定
response['chat']['yourpost'] = (1 if thread_key == response['chat']['user_id'] else 0)
# 数値を返すフィールドは 0 の場合に省略される本家ニコ生の謎仕様に合わせる
if 'yourpost' in response['chat'] and response['chat']['yourpost'] == 0:
del response['chat']['yourpost']
return response
def IsWebSocketDisconnected(websocket: WebSocket) -> bool:
"""
WebSocket が既に切断済みかどうかを判定する
Args:
websocket (WebSocket): 判定対象の WebSocket
Returns:
bool: 切断済みの場合は True
"""
# Starlette 側とアプリ側のどちらかが切断済みなら、送信処理は中止する
return (
websocket.client_state == WebSocketState.DISCONNECTED
or websocket.application_state == WebSocketState.DISCONNECTED
)
def IsWebSocketClosedError(ex: Exception) -> bool:
"""
WebSocket 切断済みで発生する想定内の送信例外かどうかを判定する
Args:
ex (Exception): 判定対象の例外
Returns:
bool: 想定内の切断例外の場合は True
"""
# FastAPI / Starlette の標準的な切断例外
if isinstance(ex, WebSocketDisconnect):
return True
# websockets ライブラリが送出する切断例外
if isinstance(ex, websockets.exceptions.ConnectionClosed):
return True
# Starlette 実装で多発する close 済み送信例外
if isinstance(ex, RuntimeError):
return 'Cannot call "send" once a close message has been sent.' in str(ex)
# Uvicorn の内部例外はクラスを直接 import しづらいため名前で判定する
return ex.__class__.__name__ == 'ClientDisconnected'
async def SendJSONSafely(websocket: WebSocket, payload: Any) -> bool:
"""
切断済みソケットへの送信例外を抑制しつつ JSON を送信する
Args:
websocket (WebSocket): 送信先 WebSocket
payload (Any): JSON 送信する payload
Returns:
bool: 送信成功時は True、切断済みなどで送信不要な場合は False
"""
# すでに切断済みなら送信せず即終了する
if IsWebSocketDisconnected(websocket) is True:
return False
try:
# 切断前であれば通常どおり送信する
await websocket.send_json(payload)
return True
except Exception as ex:
# 切断済み起因の例外は抑止し、それ以外は上位へ伝搬する
if IsWebSocketClosedError(ex) is True:
return False
raise
async def SendTextSafely(websocket: WebSocket, text: str) -> bool:
"""
切断済みソケットへの送信例外を抑制しつつテキストを送信する
Args:
websocket (WebSocket): 送信先 WebSocket
text (str): 送信するテキスト
Returns:
bool: 送信成功時は True、切断済みなどで送信不要な場合は False
"""
# すでに切断済みなら送信せず即終了する
if IsWebSocketDisconnected(websocket) is True:
return False
try:
# 切断前であれば通常どおり送信する
await websocket.send_text(text)
return True
except Exception as ex:
# 切断済み起因の例外は抑止し、それ以外は上位へ伝搬する
if IsWebSocketClosedError(ex) is True:
return False
raise
async def CloseWebSocketSafely(
websocket: WebSocket,
code: int = 1000,
reason: str | None = None,
) -> bool:
"""
切断済みソケットへの close 例外を抑制しつつ接続を閉じる
Args:
websocket (WebSocket): クローズ対象の WebSocket
code (int, optional): close code. Defaults to 1000.
reason (str | None, optional): close reason. Defaults to None.
Returns:
bool: close 実行時は True、既に切断済みの場合は False
"""
# すでに切断済みなら close を再送しない
if IsWebSocketDisconnected(websocket) is True:
return False
try:
# close は 1 回だけ実行し、成功時は True を返す
await websocket.close(code=code, reason=reason)
return True
except Exception as ex:
# close 済み起因の例外は抑止し、それ以外は上位へ伝搬する
if IsWebSocketClosedError(ex) is True:
return False
raise
@router.websocket('/channels/{channel_id}/ws/watch')
async def WatchSessionAPI(
websocket: WebSocket,
channel_id: Annotated[str, Path(description='実況チャンネル ID 。ex: jk211')],
thread_id: Annotated[int | None, Query(description='スレッド ID 。過去の特定スレッドの過去ログコメントを取得する際に指定する。')] = None,
):
"""
ニコ生の視聴セッション WebSocket 互換 API
"""
# チャンネル ID のリダイレクト処理
## jk263 (BSJapanext) への接続は jk200 (BS10) にリダイレクトする
## ただし、過去ログ取得時 (thread_id が指定されている場合) はリダイレクトしない
original_channel_id = channel_id
if channel_id == 'jk263':
# thread_id が指定されている場合は、そのスレッドが jk263 のものかを確認
if thread_id is not None:
thread = await Thread.filter(id=thread_id).first()
if thread and thread.channel_id == 263:
# jk263 の過去ログの場合はリダイレクトしない
pass
else:
# thread_id が存在しないか、jk263 以外のスレッドの場合は jk200 にリダイレクト
channel_id = 'jk200'
logging.info(f'WatchSessionAPI: Channel {original_channel_id} redirected to {channel_id} (thread not found or not jk263).')
else:
# 通常の接続時は jk200 にリダイレクト
channel_id = 'jk200'
logging.info(f'WatchSessionAPI: Channel {original_channel_id} redirected to {channel_id}.')
# チャンネル ID (jk の prefix 付きなので一旦数値に置換してから) を取得
try:
channel_id_int = int(channel_id.replace('jk', ''))
except ValueError:
logging.error(f'WatchSessionAPI [{channel_id}]: Invalid channel ID.')
await CloseWebSocketSafely(websocket, code=1008, reason=f'[{channel_id}]: Invalid channel ID.')
return
# DB へ到達する前に既知チャンネルかを判定し、無効チャンネルアクセスで DB を消費しないようにする
## サードパーティークライアント由来の jk309 などを早期拒否して、通常トラフィックへの影響を抑える
if channel_id_int not in KNOWN_JIKKYO_CHANNEL_IDS:
await LogUnknownChannelRejected(channel_id)
await CloseWebSocketSafely(websocket, code=1008, reason=f'[{channel_id}]: Invalid channel ID.')
return
# スレッド ID が指定されていなければ、現在アクティブな (放送中の) スレッドを取得
if not thread_id:
thread = await GetActiveThread(channel_id_int)
if not thread:
# 存在しないチャンネル ID を指定された場合にも発生して頻度が多すぎるのでログをコメントアウト中
# logging.error(f'WatchSessionAPI [{channel_id}]: Active thread not found.')
await CloseWebSocketSafely(websocket, code=1002, reason=f'[{channel_id}]: Active thread not found.')
return
# スレッド ID が指定されていれば、そのスレッドを取得
## 放送開始前のスレッドが指定された場合はエラーを返す
else:
thread = await Thread.filter(
id = thread_id,
channel_id = channel_id_int,
).first()
if not thread:
logging.error(f'WatchSessionAPI [{channel_id}]: Thread not found.')
await CloseWebSocketSafely(websocket, code=1002, reason=f'[{channel_id}]: Thread not found.')
return
if datetime.now(JST) < thread.start_at:
logging.error(f'WatchSessionAPI [{channel_id}]: Thread is upcoming.')
await CloseWebSocketSafely(websocket, code=1002, reason=f'[{channel_id}]: Thread is upcoming.')
return
# クライアント ID を生成
## 同一 IP 同一クライアントからなら UA が変更されない限り同一値になるはず
watch_session_client_id = GenerateClientID(websocket)
logging.info(f'WatchSessionAPI [{channel_id}]: Client {watch_session_client_id} connected.')
logging.info(f'WatchSessionAPI [{channel_id}]: Thread ID: {thread.id} User-Agent: {websocket.headers.get("User-Agent", "Unknown")}')
# 接続を受け入れる
await websocket.accept()
# startWatching 時に送信した comments 値を sender task の初期フォールバック値へ引き継ぐ
initial_statistics_comment_count: int | None = None
async def RunReceiverTask() -> None:
""" クライアントからのメッセージを受信するタスク """
nonlocal initial_statistics_comment_count
# 最後にコメントを投稿した時刻
last_comment_time: float = 0
# 短期間の荒らし連投によりサイレントにコメントを破棄する一時 BAN 処理が何回行われたかのカウント
silent_discard_count = 0
SILENT_DISCARD_COUNT_THRESHOLD = 3 # 3回以上一時 BAN されたら、この WebSocket 接続が切断されるまで永久 BAN する
while True:
# クライアントから JSON 形式のメッセージを受信
try:
message = await websocket.receive_json()
except json.JSONDecodeError:
# JSONとしてデコードできないメッセージが送られてきた場合は単に無視する
# これには接続を維持しようと空文字列が送られてくるケースを含む
continue
try:
message_type = message.get('type')
except KeyError:
# メッセージに type がない場合はエラーを返す
is_sent = await SendJSONSafely(websocket, {
'type': 'error',
'data': {
'message': 'INVALID_MESSAGE',
},
})
if is_sent is False:
return
continue
# 視聴開始リクエスト
## リクエストの中身は無視して処理を進める
## 本家ニコ生では stream オブジェクトがオプションとして渡された際に視聴 URL などを送るが、ここでは常にコメントのみとする
## 大元も基本視聴負荷の関係で映像がいらないなら省略してくれという話があった
if message_type == 'startWatching':
# 現在のサーバー時刻 (ISO 8601) を送信
is_sent = await SendJSONSafely(websocket, {
'type': 'serverTime',
'data': {
'currentMs': datetime.now(JST).isoformat(),
},
})
if is_sent is False:
return
# 座席取得が完了した旨を送信
is_sent = await SendJSONSafely(websocket, {
'type': 'seat',
'data': {
# 「座席を維持するために送信する keepSeat メッセージ (クライアントメッセージ) の送信間隔時間(秒)」
'keepIntervalSec': 30,
},
})
if is_sent is False:
return
# スレッドの放送開始時刻・放送終了時刻を送信
is_sent = await SendJSONSafely(websocket, {
'type': 'schedule',
'data': {
'begin': thread.start_at.isoformat(),
'end': thread.end_at.isoformat(),
},
})
if is_sent is False:
return
# リクエスト元の URL を組み立てる
## scheme はそのままだと多段プロキシの場合に ws:// になってしまうので、
## X-Forwarded-Proto ヘッダから scheme を取得してから URI を組み立てる
## X-Forwarded-Proto が https 固定の場合も考慮して wss に変換している
scheme = websocket.headers.get('X-Forwarded-Proto', websocket.url.scheme).replace('https', 'wss')
uri = f'{scheme}://{websocket.url.netloc}/api/v1/channels/{channel_id}/ws/comment'
# コメント部屋情報を送信
is_sent = await SendJSONSafely(websocket, {
'type': 'room',
'data': {
'messageServer': {
# 「メッセージサーバーの URI (WebSocket)」
'uri': uri,
# 「メッセージサーバの種類 (現在常に `niwavided`)」
'type': 'niwavided',
},
# 「部屋名」
'name': 'アリーナ',
# 「メッセージサーバーのスレッド ID」
'threadId': str(thread.id),
# 「(互換性確保のためのダミー値, 現在常に `true`)」
'isFirst': True,
# 「(互換性確保のためのダミー文字列)」
'waybackkey': 'DUMMY_TOKEN',
# 「メッセージサーバーから受信するコメント(chatメッセージ)に yourpost フラグを付けるためのキー。
# thread メッセージの threadkey パラメータに設定する」
## NX-Jikkyo ではコメントの user_id に入れられる watch_session_client_id をセットする
'yourPostKey': watch_session_client_id,
# 「vpos を計算する基準 (vpos:0) となる時刻。(ISO8601 形式)」
## 確か本家ニコ生では番組開始時刻が vpos (相対的なコメント時刻) に入っていたはず (忘れた…)
## NX-Jikkyo でも本家ニコ生同様に番組開始時刻を ISO 8601 形式で入れている
'vposBaseTime': thread.start_at.isoformat(),
},
})
if is_sent is False:
return
# 視聴の統計情報を送信
initial_viewer_count = 0
try:
initial_viewer_count = int(await REDIS_CLIENT.hget(REDIS_KEY_VIEWER_COUNT, channel_id) or 0)
except Exception as ex:
logging.warning(
f'WatchSessionAPI [{channel_id}]: Failed to fetch viewer counter for initial statistics. Falling back to zero.',
exc_info = ex,
)
initial_comment_count = 0
try:
initial_comment_count = (await CommentCounter.get(thread_id=thread.id)).max_no
except DoesNotExist as ex:
# 稀に採番テーブルのレコードが欠損している場合は、0 にフォールバックして接続を継続する
## 定期 statistics 送信側の回復ロジック (SyncCommentCounters) で最終的に修復される
logging.warning(
f'WatchSessionAPI [{channel_id}]: CommentCounter record is missing for initial statistics. Falling back to zero.',
exc_info = ex,
)
is_sent = await SendJSONSafely(websocket, {
'type': 'statistics',
'data': {
'viewers': initial_viewer_count,
'comments': initial_comment_count,
'adPoints': 0, # NX-Jikkyo では常に 0 を返す
'giftPoints': 0, # NX-Jikkyo では常に 0 を返す
},
})
if is_sent is False:
return
initial_statistics_comment_count = initial_comment_count
# 座席維持リクエスト
## 本家ニコ生では keepSeat メッセージが一定期間の間に送られてこなかった場合に接続を切断するが、モックなので今の所何もしない
elif message_type == 'keepSeat':
pass
# pong リクエスト
## 本家ニコ生ではサーバーから ping メッセージを送ってから pong メッセージが
## 一定期間の間に送られてこなかった場合に接続を切断するが、モックなので今の所何もしない
elif message_type == 'pong':
pass
# コメント投稿リクエスト
elif message_type == 'postComment':
# 放送が終了したスレッドにはコメントを投稿できない
if thread.end_at < datetime.now(JST):
is_sent = await SendJSONSafely(websocket, {
'type': 'error',
'data': {
'message': 'NOT_ON_AIR',
},
})
if is_sent is False:
return
continue
try:
# 送られてきたリクエストから mail に相当するコメントコマンドを組み立てる
# リクエストでは直接は mail は送られてこないので、いい感じに組み立てる必要がある
comment_commands: list[str] = []
# 匿名フラグが True なら 184 を追加
if message['data']['isAnonymous'] is True:
comment_commands.append('184')
# コメント色コマンド (ex: white) があれば追加
if 'color' in message['data']:
comment_commands.append(message['data']['color'])
# コメント位置コマンド (ex: naka) があれば追加
if 'position' in message['data']:
comment_commands.append(message['data']['position'])
# コメントサイズコマンド (ex: medium) があれば追加
if 'size' in message['data']:
comment_commands.append(message['data']['size'])
# コメントフォントコマンド (ex: defont) があれば追加
if 'font' in message['data']:
comment_commands.append(message['data']['font'])
# 現在のサーバー時刻
current_time = time.time()
# 0.5 秒以内の連投チェック
## 連投とみなされた場合、レスポンス上はコメント投稿が成功したように見せかけるが、
## 実際にはサイレントにコメントを破棄する (一時 BAN 処理)
## silent_discard_count が SILENT_DISCARD_COUNT_THRESHOLD を超えた場合も同様だが、
## 接続が維持されている限り永久に BAN される点が異なる
if ((current_time - last_comment_time) < 0.5) or (silent_discard_count > SILENT_DISCARD_COUNT_THRESHOLD):
# 最後のコメント投稿時刻を更新
## コメント投稿処理の成功 or 失敗に関わらず一律で更新する
## これにより、0.5 秒以内の機械的な連投が続く場合に最初の1回以外の全コメントをサイレントに弾ける
last_comment_time = current_time
# ダミーのコメント投稿結果を返す
is_sent = await SendJSONSafely(websocket, {
'type': 'postCommentResult',
'data': {
'chat': {
'mail': ' '.join(comment_commands),
'anonymity': 1 if message['data']['isAnonymous'] else 0,
'content': message['data']['text'],
'restricted': False,
},
},
})
if is_sent is False:
return
silent_discard_count += 1
if silent_discard_count > SILENT_DISCARD_COUNT_THRESHOLD:
logging.warning(f'WatchSessionAPI [{channel_id}]: Client {watch_session_client_id}\'s comment was banned for too many consecutive comments.')
else:
logging.warning(f'WatchSessionAPI [{channel_id}]: Client {watch_session_client_id} posted a comment too quickly.')
continue
# 最後のコメント投稿時刻を更新
## コメント投稿処理の成功 or 失敗に関わらず一律で更新する
## これにより、0.5 秒以内の機械的な連投が続く場合に最初の1回以外の全コメントをサイレントに弾ける
last_comment_time = current_time
async def CreateCommentInTransaction(connection: TransactionalDBClient) -> Comment:
# 採番テーブルに記録されたコメ番をインクリメント
await connection.execute_query(
'UPDATE comment_counters SET max_no = max_no + 1 WHERE thread_id = %s',
[thread.id]
)
# インクリメント後のコメ番を取得
## 採番テーブルを使うことでコメ番の重複を防いでいる
new_no_result = await connection.execute_query_dict(
'SELECT max_no FROM comment_counters WHERE thread_id = %s',
[thread.id]
)
new_no = new_no_result[0]['max_no']
# 新しいコメントを作成
return await Comment.create(
thread_id = thread.id,
no = new_no,
vpos = message['data']['vpos'], # リクエストで与えられた vpos をそのまま入れる
mail = ' '.join(comment_commands), # コメントコマンド (mail) は空白区切りの文字列として組み立てる
user_id = watch_session_client_id, # ユーザー ID は視聴セッションのクライアント ID をそのまま入れる
premium = False, # 簡易実装なのでプレミアム会員判定は省略
anonymity = message['data']['isAnonymous'] is True,
content = message['data']['text'],
)
# コメントを DB に登録
comment = await RunTransactionWithReconnectRetry(
operation = CreateCommentInTransaction,
operation_name = f'WatchSessionAPI [{channel_id}]',
)
# スレッドごとの最新コメ番キャッシュを更新
## 投稿成功直後に反映しておくことで、statistics 送信時の DB アクセス頻度を抑える
try:
await UpdateThreadCommentCounterCache(thread.id, comment.no)
except Exception as ex:
# キャッシュ更新はベストエフォートで扱う
## ここで例外を再送出すると投稿成功レスポンスまで失敗するため、ログのみ残して継続する
logging.warning(
f'WatchSessionAPI [{channel_id}]: Failed to update thread comment counter cache.',
exc_info = ex,
)
# ニコ生 XML 互換コメント形式に変換した上で、Redis Pub/Sub でコメントを送信
## この段階ではまだ yourpost フラグを設定してはならない
## yourpost フラグはコメントセッション WebSocket 側で設定しないと、意図しないコメントに yourpost フラグが付与されてしまう
await REDIS_CLIENT.publish(
channel = f'{REDIS_CHANNEL_THREAD_COMMENTS_PREFIX}:{thread.id}',
message = json.dumps(ConvertToXMLCompatibleCommentResponse(comment), ensure_ascii=False),
)
# 実況勢いカウント用の Redis ソート済みセット型にエントリを追加
## スコア (UNIX タイムスタンプ) が現在時刻から 60 秒以内の範囲のエントリの数が実況勢いとなる