File size: 1,187 Bytes
bdc2878
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Classify upstream HTTP responses into proxy feedback categories."""

from .models import ProxyFeedback, ProxyFeedbackKind


def classify_status_code(status_code: int) -> ProxyFeedbackKind:
    if status_code == 200:
        return ProxyFeedbackKind.SUCCESS
    if status_code == 401:
        return ProxyFeedbackKind.UNAUTHORIZED
    if status_code == 403:
        return ProxyFeedbackKind.CHALLENGE
    if status_code == 429:
        return ProxyFeedbackKind.RATE_LIMITED
    if status_code >= 500:
        return ProxyFeedbackKind.UPSTREAM_5XX
    return ProxyFeedbackKind.FORBIDDEN


def build_feedback(
    status_code: int,
    *,
    is_cloudflare: bool = False,
    reason: str = "",
    retry_after_ms: int | None = None,
) -> ProxyFeedback:
    """Build a ``ProxyFeedback`` from an HTTP response status code."""
    kind = classify_status_code(status_code)
    if is_cloudflare and status_code == 403:
        kind = ProxyFeedbackKind.CHALLENGE
    return ProxyFeedback(
        kind           = kind,
        status_code    = status_code,
        reason         = reason,
        retry_after_ms = retry_after_ms,
    )


__all__ = ["classify_status_code", "build_feedback"]