본문 바로가기
C.W.K.
Stream
Lesson 06 of 07 · published

미들웨어

~12 min · library, middleware, rate-limit

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

연결 시점의 미들웨어

connect 처리기는 인증, 버전 검사, 지역 차단, 속도 제한 등록을 하는 미들웨어 자리야. 유용한 페이로드를 담아 ConnectionRefusedError(code, message) 를 일으키면 Socket.IO 가 코드와 문장을 모두 클라이언트의 connect_error 이벤트에 드러내.

이벤트별 속도 제한

속도 제한 데코레이터를 만들어 채팅 전송이나 파일 업로드처럼 필요한 이벤트에만 적용하고 읽기 전용 이벤트는 건너뛰어. sid 를 키로 삼아 연결별 최근 시각을 작은 deque 에 저장하면 충분해.

Code

연결 시 인증 미들웨어·python
@sio.event
async def connect(sid, environ, auth):
    token = (auth or {}).get('token')
    user = decode_jwt(token) if token else None
    if not user:
        raise socketio.exceptions.ConnectionRefusedError(
            'unauthorized',
            'token missing or invalid',
        )
    if user.get('disabled'):
        raise socketio.exceptions.ConnectionRefusedError(
            'forbidden',
            'account disabled',
        )
    await sio.save_session(sid, {'user': user})
이벤트별 속도 제한 데코레이터·python
from collections import defaultdict, deque
import time, functools

windows = defaultdict(deque)  # sid -> deque of timestamps

def rate_limit(per_second=20):
    def deco(fn):
        @functools.wraps(fn)
        async def wrapper(sid, *args, **kwargs):
            now = time.time()
            w = windows[sid]
            while w and now - w[0] > 1.0:
                w.popleft()
            if len(w) >= per_second:
                await sio.emit('error',
                    {'code': 'rate_limited', 'message': 'slow down'},
                    to=sid)
                return
            w.append(now)
            return await fn(sid, *args, **kwargs)
        return wrapper
    return deco

@sio.on('chat:message')
@rate_limit(per_second=20)
async def chat(sid, data):
    # ...
    pass

External links

Exercise

인증 미들웨어와 채팅의 초당 메시지 5개 제한을 추가해. 잘못된 토큰으로 연결해 connect_error 를 확인하고, 올바른 토큰으로 반복문에서 메시지 100개를 보내 초당 처음 5개만 성공하고 나머지는 오류 이벤트를 받는지 확인해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.