{"id":124718,"date":"2026-11-19T11:40:50","date_gmt":"2026-11-19T03:40:50","guid":{"rendered":"https:\/\/www.wsisp.com\/helps\/124718.html"},"modified":"2026-11-19T11:40:50","modified_gmt":"2026-11-19T03:40:50","slug":"http-%e7%8a%b6%e6%80%81%e7%a0%81%ef%bc%9a%e5%ae%a2%e6%88%b7%e7%ab%af%e4%b8%8e%e6%9c%8d%e5%8a%a1%e5%99%a8%e7%9a%84%e9%80%9a%e4%bf%a1%e8%af%ad%e8%a8%80-%e7%ac%ac%e4%b8%83%e9%83%a8-3","status":"publish","type":"post","link":"https:\/\/www.wsisp.com\/helps\/124718.html","title":{"rendered":"HTTP \u72b6\u6001\u7801\uff1a\u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668\u7684\u901a\u4fe1\u8bed\u8a00\u2014\u2014\u7b2c\u4e03\u90e8\u5206\uff1a\u9ad8\u7ea7\u4e3b\u9898\u4e0e\u672a\u6765\u5c55\u671b\uff08\u4e00\uff09"},"content":{"rendered":"<p>        \/* MD \/ \u5bcc\u6587\u672c\u4e2d\u7684 .toc\uff08\u542b\u535a\u5ba2\u56ed\u642c\u5bb6\u7b49\u5d4c\u5957\u7ed3\u6784\uff09\uff1b.toc-box \u5728\u4fa7\u680f\uff0c\u4e0d\u53d7\u5f71\u54cd *\/<br \/>\n        #content_views .toc,<br \/>\n        \/* \u7f16\u8f91\u5668\u5e38\u5728\u76ee\u5f55\u524d\u540e\u63d2\u5165\u7a7a p\uff08:empty \u4ecd\u5360 20px\uff09\uff0c\u4e00\u5e76\u53bb\u6389\u907f\u514d\u9876\u7a7a\u9699 *\/<br \/>\n        #content_views.markdown_views &gt; p:empty:has(+ .toc),<br \/>\n        #content_views.markdown_views &gt; .toc + p:empty,<br \/>\n        \/* \u5bcc\u6587\u672c\u65e7\u7248\u76ee\u5f55\u6807\u8bb0 *\/<br \/>\n        #content_views.htmledit_views #main-toc,<br \/>\n        #content_views.htmledit_views #hr-toc,<br \/>\n        #content_views.htmledit_views p[id*=\\&#8221;-toc\\&#8221;] {<br \/>\n          display: none !important;<br \/>\n        }<br \/>\n        \/* \u76ee\u5f55\u53bb\u6389\u540e\uff0c\u7d27\u8ddf\u7684\u9996\u4e2a\u6807\u9898\u4e0d\u518d\u591a\u51fa\u4e00\u5757\u4e0a\u8fb9\u8ddd *\/<br \/>\n        #content_views.markdown_views &gt; .toc + h1,<br \/>\n        #content_views.markdown_views &gt; .toc + h2,<br \/>\n        #content_views.markdown_views &gt; .toc + h3,<br \/>\n        #content_views.markdown_views &gt; .toc + h4,<br \/>\n        #content_views.markdown_views &gt; .toc + p:empty + h1,<br \/>\n        #content_views.markdown_views &gt; .toc + p:empty + h2,<br \/>\n        #content_views.markdown_views &gt; .toc + p:empty + h3,<br \/>\n        #content_views.markdown_views &gt; .toc + p:empty + h4 {<br \/>\n          margin-top: 0 !important;<br \/>\n        }<\/p>\n<h3>\u7b2c35\u7ae0&#xff1a;HTTP\/2\u548cHTTP\/3\u5bf9\u72b6\u6001\u7801\u7684\u5f71\u54cd<\/h3>\n<h4>35.1 HTTP\/2\u534f\u8bae\u7684\u6838\u5fc3\u7279\u6027<\/h4>\n<h5>35.1.1 \u4e8c\u8fdb\u5236\u5206\u5e27\u5c42<\/h5>\n<p>HTTP\/2\u5f15\u5165\u4e86\u4e8c\u8fdb\u5236\u5206\u5e27\u5c42&#xff0c;\u5f7b\u5e95\u6539\u53d8\u4e86HTTP\u534f\u8bae\u7684\u4f20\u8f93\u65b9\u5f0f\u3002\u4e0eHTTP\/1.x\u7684\u6587\u672c\u683c\u5f0f\u4e0d\u540c&#xff0c;HTTP\/2\u5c06\u6240\u6709\u6d88\u606f\u5206\u89e3\u4e3a\u66f4\u5c0f\u7684\u5e27&#xff0c;\u6bcf\u4e2a\u5e27\u90fd\u6709\u7279\u5b9a\u7684\u7c7b\u578b\u548c\u7528\u9014&#xff1a;<\/p>\n<p>text<\/p>\n<p>&#043;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;&#043;<br \/>\n|                 HTTP\/2 \u5e27\u7ed3\u6784                 |<br \/>\n&#043;&#8212;&#8212;&#8212;&#8212;&#8212;-&#043;&#8212;&#8212;&#8212;&#8212;&#8212;-&#043;&#8212;&#8212;&#8212;&#8212;-&#043;<br \/>\n|  \u957f\u5ea6(24\u4f4d)    |   \u7c7b\u578b(8\u4f4d)    | \u6807\u5fd7(8\u4f4d)   |<br \/>\n&#043;&#8212;&#8212;&#8212;&#8212;&#8212;-&#043;&#8212;&#8212;&#8212;&#8212;&#8212;-&#043;&#8212;&#8212;&#8212;&#8212;-&#043;<br \/>\n|                   \u6d41\u6807\u8bc6\u7b26(31\u4f4d)               |<br \/>\n&#043;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#043;<br \/>\n|                   \u5e27\u8f7d\u8377(\u53ef\u53d8\u957f\u5ea6)              |<br \/>\n&#043;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#043;<\/p>\n<p>\u5e27\u7c7b\u578b\u5305\u62ec&#xff1a;<\/p>\n<ul>\n<li>\n<p>HEADERS\u5e27&#xff1a;\u643a\u5e26HTTP\u5934\u90e8\u4fe1\u606f<\/p>\n<\/li>\n<li>\n<p>DATA\u5e27&#xff1a;\u643a\u5e26\u8bf7\u6c42\/\u54cd\u5e94\u4f53<\/p>\n<\/li>\n<li>\n<p>PRIORITY\u5e27&#xff1a;\u6307\u5b9a\u6d41\u7684\u4f18\u5148\u7ea7<\/p>\n<\/li>\n<li>\n<p>RST_STREAM\u5e27&#xff1a;\u7acb\u5373\u7ec8\u6b62\u6d41&#xff08;\u7c7b\u4f3cTCP\u7684RST&#xff09;<\/p>\n<\/li>\n<li>\n<p>SETTINGS\u5e27&#xff1a;\u914d\u7f6e\u8fde\u63a5\u53c2\u6570<\/p>\n<\/li>\n<li>\n<p>PUSH_PROMISE\u5e27&#xff1a;\u670d\u52a1\u5668\u63a8\u9001\u8d44\u6e90<\/p>\n<\/li>\n<li>\n<p>GOAWAY\u5e27&#xff1a;\u4f18\u96c5\u7ec8\u6b62\u8fde\u63a5<\/p>\n<\/li>\n<\/ul>\n<h5>35.1.2 \u591a\u8def\u590d\u7528\u4e0e\u6d41\u63a7\u5236<\/h5>\n<p>HTTP\/2\u901a\u8fc7\u6d41(Stream)\u7684\u6982\u5ff5\u5b9e\u73b0\u4e86\u771f\u6b63\u7684\u591a\u8def\u590d\u7528&#xff1a;<\/p>\n<p>javascript<\/p>\n<p>\/\/ HTTP\/2\u4e2d\u591a\u4e2a\u8bf7\u6c42\/\u54cd\u5e94\u5728\u5355\u4e2a\u8fde\u63a5\u4e0a\u5e76\u884c\u4f20\u8f93<br \/>\n&#043;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#043;<br \/>\n| \u8fde\u63a5 (Connection)                              |<br \/>\n|  &#043;&#8212;&#8212;&#8212;&#8212;&#043;  &#043;&#8212;&#8212;&#8212;&#8212;&#043;  &#043;&#8212;&#8212;&#8212;&#8212;&#043;|<br \/>\n|  |   \u6d411      |  |   \u6d412      |  |   \u6d413      ||<br \/>\n|  | ID: 1      |  | ID: 3      |  | ID: 5      ||<br \/>\n|  | \u72b6\u6001\u7801:200 |  | \u72b6\u6001\u7801:404 |  | \u72b6\u6001\u7801:500 ||<br \/>\n|  &#043;&#8212;&#8212;&#8212;&#8212;&#043;  &#043;&#8212;&#8212;&#8212;&#8212;&#043;  &#043;&#8212;&#8212;&#8212;&#8212;&#043;|<br \/>\n&#043;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#043;<\/p>\n<p>\u6d41\u72b6\u6001\u673a\u66f4\u52a0\u590d\u6742&#xff1a;<\/p>\n<h5>35.1.3 \u670d\u52a1\u5668\u63a8\u9001<\/h5>\n<p>HTTP\/2\u7684\u670d\u52a1\u5668\u63a8\u9001\u529f\u80fd\u5141\u8bb8\u670d\u52a1\u5668\u4e3b\u52a8\u5411\u5ba2\u6237\u7aef\u53d1\u9001\u8d44\u6e90&#xff1a;<\/p>\n<p>http<\/p>\n<p># \u670d\u52a1\u5668\u63a8\u9001\u793a\u4f8b<br \/>\n\u5ba2\u6237\u7aef\u8bf7\u6c42: GET \/index.html<br \/>\n\u670d\u52a1\u5668\u54cd\u5e94:<br \/>\n1. 200 OK &#043; index.html\u5185\u5bb9<br \/>\n2. PUSH_PROMISE\u5e27: \u544a\u77e5\u5c06\u63a8\u9001style.css<br \/>\n3. \u5728\u6d41ID:X\u4e0a\u53d1\u9001style.css (HEADERS&#043;DATA\u5e27)<\/p>\n<h4>35.2 HTTP\/2\u5bf9\u72b6\u6001\u7801\u5904\u7406\u7684\u5f71\u54cd<\/h4>\n<h5>35.2.1 \u72b6\u6001\u7801\u7684\u4f20\u8f93\u65b9\u5f0f\u53d8\u5316<\/h5>\n<p>\u5728HTTP\/2\u4e2d&#xff0c;\u72b6\u6001\u7801\u4e0d\u518d\u4ee5\u6587\u672c\u5f62\u5f0f\u51fa\u73b0\u5728\u54cd\u5e94\u884c&#xff0c;\u800c\u662f\u4f5c\u4e3aHEADERS\u5e27\u7684\u7279\u6b8a\u5934\u90e8\u5b57\u6bb5&#xff1a;<\/p>\n<p>http<\/p>\n<p># HTTP\/1.1\u54cd\u5e94\u884c<br \/>\nHTTP\/1.1 200 OK<\/p>\n<p># HTTP\/2\u4f2a\u5934\u90e8\u5b57\u6bb5<br \/>\n:status &#061; 200<\/p>\n<p>\u4f2a\u5934\u90e8\u5b57\u6bb5\u5305\u62ec&#xff1a;<\/p>\n<ul>\n<li>\n<p>:method\u00a0&#8211; \u8bf7\u6c42\u65b9\u6cd5<\/p>\n<\/li>\n<li>\n<p>:scheme\u00a0&#8211; \u534f\u8bae\u65b9\u6848<\/p>\n<\/li>\n<li>\n<p>:authority\u00a0&#8211; \u6743\u5a01\u90e8\u5206(\u66ff\u4ee3Host)<\/p>\n<\/li>\n<li>\n<p>:path\u00a0&#8211; \u8bf7\u6c42\u8def\u5f84<\/p>\n<\/li>\n<li>\n<p>:status\u00a0&#8211; \u54cd\u5e94\u72b6\u6001\u7801<\/p>\n<\/li>\n<\/ul>\n<h5>35.2.2 \u9519\u8bef\u5904\u7406\u7684\u65b0\u6a21\u5f0f<\/h5>\n<p>HTTP\/2\u5f15\u5165\u4e86\u65b0\u7684\u9519\u8bef\u5904\u7406\u673a\u5236&#xff1a;<\/p>\n<li>\n<p>RST_STREAM\u5e27&#xff1a;\u5141\u8bb8\u7acb\u5373\u7ec8\u6b62\u5355\u4e2a\u6d41\u800c\u4e0d\u5f71\u54cd\u6574\u4e2a\u8fde\u63a5<\/p>\n<p>python<\/p>\n<p># \u670d\u52a1\u5668\u9047\u5230\u9519\u8bef\u65f6\u53d1\u9001RST_STREAM<br \/>\ndef handle_request_error(stream_id, error_code):<br \/>\n    # \u53d1\u9001RST_STREAM\u5e27\u7ec8\u6b62\u7279\u5b9a\u6d41<br \/>\n    send_rst_stream(stream_id, error_code)<br \/>\n    # \u8fde\u63a5\u4e0a\u7684\u5176\u4ed6\u6d41\u7ee7\u7eed\u6b63\u5e38\u5904\u7406<\/p>\n<p># \u9519\u8bef\u4ee3\u7801\u5b9a\u4e49<br \/>\nERROR_CODES &#061; {<br \/>\n    0x0: &#039;NO_ERROR&#039;,<br \/>\n    0x1: &#039;PROTOCOL_ERROR&#039;,<br \/>\n    0x2: &#039;INTERNAL_ERROR&#039;,<br \/>\n    0x3: &#039;FLOW_CONTROL_ERROR&#039;,<br \/>\n    0x4: &#039;SETTINGS_TIMEOUT&#039;,<br \/>\n    0x5: &#039;STREAM_CLOSED&#039;,<br \/>\n    0x6: &#039;FRAME_SIZE_ERROR&#039;,<br \/>\n    0x7: &#039;REFUSED_STREAM&#039;,<br \/>\n    0x8: &#039;CANCEL&#039;,<br \/>\n    0x9: &#039;COMPRESSION_ERROR&#039;,<br \/>\n    0xA: &#039;CONNECT_ERROR&#039;,<br \/>\n    0xB: &#039;ENHANCE_YOUR_CALM&#039;,<br \/>\n    0xC: &#039;INADEQUATE_SECURITY&#039;,<br \/>\n    0xD: &#039;HTTP_1_1_REQUIRED&#039;<br \/>\n}\n<\/li>\n<li>\n<p>GOAWAY\u5e27&#xff1a;\u4f18\u96c5\u8fde\u63a5\u7ec8\u6b62<\/p>\n<p>http<\/p>\n<p># GOAWAY\u5e27\u7ed3\u6784<br \/>\n\u6700\u540e\u5904\u7406\u7684\u6d41ID: 0x7FFFFFFF (\u6700\u592731\u4f4d\u503c)<br \/>\n\u9519\u8bef\u4ee3\u7801: PROTOCOL_ERROR (0x1)<br \/>\n\u9644\u52a0\u8c03\u8bd5\u6570\u636e: (\u53ef\u9009)\n<\/li>\n<h5>35.2.3 \u72b6\u6001\u7801\u5728\u5934\u90e8\u538b\u7f29\u4e2d\u7684\u4f18\u5316<\/h5>\n<p>HTTP\/2\u4f7f\u7528HPACK\u7b97\u6cd5\u538b\u7f29\u5934\u90e8&#xff0c;\u72b6\u6001\u7801\u4f5c\u4e3a\u9ad8\u9891\u51fa\u73b0\u7684\u503c\u88ab\u7279\u6b8a\u5904\u7406&#xff1a;<\/p>\n<p>text<\/p>\n<p>\u9759\u6001\u8868\u7d22\u5f15:<br \/>\n8  :status: 200<br \/>\n20 :status: 204<br \/>\n26 :status: 206<br \/>\n42 :status: 301<br \/>\n43 :status: 302<br \/>\n44 :status: 303<br \/>\n45 :status: 307<br \/>\n46 :status: 308<br \/>\n48 :status: 400<br \/>\n49 :status: 401<br \/>\n50 :status: 403<br \/>\n51 :status: 404<br \/>\n52 :status: 405<br \/>\n53 :status: 406<br \/>\n54 :status: 407<br \/>\n55 :status: 408<br \/>\n56 :status: 409<br \/>\n57 :status: 410<br \/>\n58 :status: 411<br \/>\n59 :status: 412<br \/>\n60 :status: 413<br \/>\n61 :status: 414<br \/>\n62 :status: 415<br \/>\n63 :status: 416<br \/>\n64 :status: 417<br \/>\n65 :status: 500<br \/>\n66 :status: 501<br \/>\n67 :status: 502<br \/>\n68 :status: 503<br \/>\n69 :status: 504<br \/>\n70 :status: 505<\/p>\n<p>\u5e38\u89c1\u72b6\u6001\u7801\u53ea\u97001\u5b57\u8282\u7d22\u5f15&#xff0c;\u5927\u5e45\u51cf\u5c11\u4f20\u8f93\u5f00\u9500\u3002<\/p>\n<h4>35.3 HTTP\/3\u7684\u9769\u65b0\u6027\u53d8\u5316<\/h4>\n<h5>35.3.1 \u57fa\u4e8eQUIC\u7684\u4f20\u8f93\u5c42<\/h5>\n<p>HTTP\/3\u6700\u5927\u7684\u53d8\u5316\u662f\u5c06\u4f20\u8f93\u5c42\u4eceTCP\u6539\u4e3aQUIC&#xff08;\u57fa\u4e8eUDP&#xff09;&#xff1a;<\/p>\n<p>QUIC\u7684\u6838\u5fc3\u4f18\u52bf&#xff1a;<\/p>\n<li>\n<p>\u96f6RTT\u8fde\u63a5\u5efa\u7acb&#xff1a;\u7f13\u5b58\u670d\u52a1\u5668\u914d\u7f6e\u53ef\u51cf\u5c11\u63e1\u624b\u65f6\u95f4<\/p>\n<\/li>\n<li>\n<p>\u6539\u8fdb\u7684\u62e5\u585e\u63a7\u5236&#xff1a;\u53ef\u63d2\u62d4\u7b97\u6cd5&#xff0c;\u66f4\u597d\u7684\u79fb\u52a8\u7f51\u7edc\u652f\u6301<\/p>\n<\/li>\n<li>\n<p>\u65e0\u961f\u5934\u963b\u585e&#xff1a;\u6bcf\u4e2a\u6d41\u72ec\u7acb&#xff0c;\u4e22\u5305\u53ea\u5f71\u54cd\u5355\u4e2a\u6d41<\/p>\n<\/li>\n<li>\n<p>\u8fde\u63a5\u8fc1\u79fb&#xff1a;\u7f51\u7edc\u5207\u6362\u65f6\u4fdd\u6301\u8fde\u63a5<\/p>\n<\/li>\n<h5>35.3.2 HTTP\/3\u4e2d\u7684\u72b6\u6001\u7801\u4f20\u8f93<\/h5>\n<p>HTTP\/3\u4fdd\u6301\u4e0eHTTP\/2\u76f8\u540c\u7684\u8bed\u4e49&#xff0c;\u4f46\u5e27\u683c\u5f0f\u548c\u4f20\u8f93\u673a\u5236\u4e0d\u540c&#xff1a;<\/p>\n<p>text<\/p>\n<p>HTTP\/3\u5e27\u683c\u5f0f&#xff1a;<br \/>\n&#043;&#8212;&#8212;&#8212;&#8212;&#8212;-&#043;&#8212;&#8212;&#8212;&#8212;&#8212;-&#043;&#8212;&#8212;&#8212;&#8212;-&#043;<br \/>\n|  \u7c7b\u578b(\u53d8\u957f)    |   \u957f\u5ea6(\u53d8\u957f)   |   \u8f7d\u8377      |<br \/>\n&#043;&#8212;&#8212;&#8212;&#8212;&#8212;-&#043;&#8212;&#8212;&#8212;&#8212;&#8212;-&#043;&#8212;&#8212;&#8212;&#8212;-&#043;<\/p>\n<p>HEADERS\u5e27\u5305\u542bQPACK\u538b\u7f29\u7684\u5934\u90e8\u5b57\u6bb5<br \/>\n:status\u4f2a\u5934\u90e8\u5b57\u6bb5\u7ee7\u7eed\u4f7f\u7528<\/p>\n<h5>35.3.3 QUIC\u7279\u6709\u7684\u9519\u8bef\u5904\u7406<\/h5>\n<p>QUIC\u5f15\u5165\u4e86\u81ea\u5df1\u7684\u9519\u8bef\u4ee3\u7801\u4f53\u7cfb&#xff1a;<\/p>\n<p>rust<\/p>\n<p>\/\/ QUIC\u9519\u8bef\u4ee3\u7801\u793a\u4f8b<br \/>\nenum QuicErrorCode {<br \/>\n    \/\/ \u4f20\u8f93\u9519\u8bef<br \/>\n    NO_ERROR &#061; 0x0,<br \/>\n    INTERNAL_ERROR &#061; 0x1,<br \/>\n    CONNECTION_REFUSED &#061; 0x2,<br \/>\n    FLOW_CONTROL_ERROR &#061; 0x3,<\/p>\n<p>    \/\/ \u6d41\u9519\u8bef<br \/>\n    STREAM_STATE_ERROR &#061; 0x5,<br \/>\n    FINAL_SIZE_ERROR &#061; 0x6,<br \/>\n    FRAME_ENCODING_ERROR &#061; 0x7,<\/p>\n<p>    \/\/ \u4f20\u8f93\u53c2\u6570\u9519\u8bef<br \/>\n    TRANSPORT_PARAMETER_ERROR &#061; 0x8,<\/p>\n<p>    \/\/ \u7248\u672c\u534f\u5546\u9519\u8bef<br \/>\n    VERSION_NEGOTIATION_ERROR &#061; 0x9,<\/p>\n<p>    \/\/ \u52a0\u5bc6\u9519\u8bef<br \/>\n    CRYPTO_BUFFER_EXCEEDED &#061; 0xD,<br \/>\n    KEY_UPDATE_ERROR &#061; 0xE,<br \/>\n    AEAD_LIMIT_REACHED &#061; 0xF,<br \/>\n}<\/p>\n<h4>35.4 \u5b9e\u9645\u5e94\u7528\u4e2d\u7684\u53d8\u5316\u4e0e\u6311\u6218<\/h4>\n<h5>35.4.1 \u76d1\u63a7\u548c\u65e5\u5fd7\u7cfb\u7edf\u7684\u8c03\u6574<\/h5>\n<p>HTTP\/2\/3\u7684\u591a\u8def\u590d\u7528\u7279\u6027\u7ed9\u76d1\u63a7\u5e26\u6765\u6311\u6218&#xff1a;<\/p>\n<p>python<\/p>\n<p># \u4f20\u7edf\u65e5\u5fd7 vs HTTP\/2\u65e5\u5fd7<br \/>\nclass HTTP1LogEntry:<br \/>\n    &#034;&#034;&#034;HTTP\/1.1\u65e5\u5fd7\u6761\u76ee&#034;&#034;&#034;<br \/>\n    def __init__(self):<br \/>\n        self.client_ip: str<br \/>\n        self.timestamp: datetime<br \/>\n        self.method: str<br \/>\n        self.path: str<br \/>\n        self.status_code: int  # \u5355\u4e2a\u72b6\u6001\u7801<br \/>\n        self.bytes_sent: int<br \/>\n        self.duration: float<\/p>\n<p>class HTTP2LogEntry:<br \/>\n    &#034;&#034;&#034;HTTP\/2\u65e5\u5fd7\u6761\u76ee &#8211; \u9700\u8981\u8ddf\u8e2a\u591a\u4e2a\u6d41&#034;&#034;&#034;<br \/>\n    def __init__(self):<br \/>\n        self.client_ip: str<br \/>\n        self.connection_id: str  # \u8fde\u63a5\u6807\u8bc6<br \/>\n        self.streams: List[StreamLog]  # \u591a\u4e2a\u6d41<\/p>\n<p>class StreamLog:<br \/>\n    &#034;&#034;&#034;\u5355\u4e2a\u6d41\u7684\u65e5\u5fd7&#034;&#034;&#034;<br \/>\n    def __init__(self):<br \/>\n        self.stream_id: int<br \/>\n        self.start_time: datetime<br \/>\n        self.end_time: datetime<br \/>\n        self.method: str<br \/>\n        self.path: str<br \/>\n        self.status_code: int<br \/>\n        self.bytes_sent: int<br \/>\n        self.priority: int<br \/>\n        self.dependencies: List[int]  # \u4f9d\u8d56\u7684\u6d41<\/p>\n<h5>35.4.2 \u4e2d\u95f4\u4ef6\u548c\u4ee3\u7406\u7684\u517c\u5bb9\u6027<\/h5>\n<p>\u4ee3\u7406\u670d\u52a1\u5668\u9700\u8981\u540c\u65f6\u5904\u7406\u4e0d\u540cHTTP\u7248\u672c&#xff1a;<\/p>\n<p>go<\/p>\n<p>\/\/ \u652f\u6301\u591a\u7248\u672cHTTP\u7684\u4ee3\u7406\u793a\u4f8b<br \/>\ntype HTTPProxy struct {<br \/>\n    \/\/ \u914d\u7f6e<br \/>\n    config ProxyConfig<\/p>\n<p>    \/\/ \u5904\u7406\u5668\u6620\u5c04<br \/>\n    handlers map[string]RequestHandler<\/p>\n<p>    \/\/ \u7edf\u8ba1\u4fe1\u606f<br \/>\n    metrics *ProxyMetrics<br \/>\n}<\/p>\n<p>func (p *HTTPProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {<br \/>\n    \/\/ \u68c0\u6d4bHTTP\u7248\u672c<br \/>\n    version :&#061; detectHTTPVersion(r)<\/p>\n<p>    switch version {<br \/>\n    case &#034;HTTP\/1.1&#034;:<br \/>\n        p.handleHTTP11(w, r)<br \/>\n    case &#034;HTTP\/2&#034;:<br \/>\n        p.handleHTTP2(w, r)<br \/>\n    case &#034;HTTP\/3&#034;:<br \/>\n        p.handleHTTP3(w, r)<br \/>\n    default:<br \/>\n        http.Error(w, &#034;Unsupported HTTP version&#034;,<br \/>\n                   http.StatusHTTPVersionNotSupported)<br \/>\n    }<br \/>\n}<\/p>\n<p>func detectHTTPVersion(r *http.Request) string {<br \/>\n    \/\/ \u901a\u8fc7\u591a\u79cd\u65b9\u5f0f\u68c0\u6d4bHTTP\u7248\u672c<br \/>\n    if r.ProtoMajor &#061;&#061; 3 {<br \/>\n        return &#034;HTTP\/3&#034;<br \/>\n    } else if r.ProtoMajor &#061;&#061; 2 {<br \/>\n        return &#034;HTTP\/2&#034;<br \/>\n    } else if r.TLS !&#061; nil &amp;&amp; r.TLS.NegotiatedProtocol &#061;&#061; &#034;h2&#034; {<br \/>\n        return &#034;HTTP\/2&#034;<br \/>\n    }<br \/>\n    return &#034;HTTP\/1.1&#034;<br \/>\n}<\/p>\n<h5>35.4.3 \u72b6\u6001\u7801\u7edf\u8ba1\u7684\u53d8\u5316<\/h5>\n<p>HTTP\/2\/3\u6539\u53d8\u4e86\u72b6\u6001\u7801\u7684\u5206\u5e03\u6a21\u5f0f&#xff1a;<\/p>\n<p>sql<\/p>\n<p>&#8212; HTTP\u7248\u672c\u5bf9\u72b6\u6001\u7801\u5206\u5e03\u7684\u5f71\u54cd\u5206\u6790<br \/>\nSELECT<br \/>\n    http_version,<br \/>\n    status_code,<br \/>\n    COUNT(*) as count,<br \/>\n    ROUND(COUNT(*) * 100.0 \/ SUM(COUNT(*)) OVER(PARTITION BY http_version), 2) as percentage,<br \/>\n    AVG(response_time_ms) as avg_response_time,<br \/>\n    PERCENTILE_CONT(0.95) WITHIN GROUP (ORDER BY response_time_ms) as p95_response_time<br \/>\nFROM http_requests<br \/>\nWHERE date &gt;&#061; NOW() &#8211; INTERVAL &#039;7 days&#039;<br \/>\nGROUP BY http_version, status_code<br \/>\nORDER BY http_version, count DESC;<\/p>\n<p>&#8212; \u9884\u671f\u53d1\u73b0&#xff1a;<br \/>\n&#8212; 1. HTTP\/2\u4e2d4xx\u9519\u8bef\u53ef\u80fd\u589e\u52a0&#xff08;\u66f4\u4e25\u683c\u7684\u534f\u8bae\u9a8c\u8bc1&#xff09;<br \/>\n&#8212; 2. HTTP\/3\u4e2d5xx\u9519\u8bef\u53ef\u80fd\u51cf\u5c11&#xff08;\u66f4\u597d\u7684\u8fde\u63a5\u7a33\u5b9a\u6027&#xff09;<br \/>\n&#8212; 3. 206 Partial Content\u4f7f\u7528\u589e\u52a0&#xff08;\u66f4\u597d\u7684\u6d41\u5a92\u4f53\u652f\u6301&#xff09;<\/p>\n<h4>35.5 \u6700\u4f73\u5b9e\u8df5\u4e0e\u8fc1\u79fb\u7b56\u7565<\/h4>\n<h5>35.5.1 \u6e10\u8fdb\u5f0f\u8fc1\u79fb\u7b56\u7565<\/h5>\n<p>yaml<\/p>\n<p># \u6e10\u8fdb\u5f0fHTTP\u7248\u672c\u5347\u7ea7\u7b56\u7565<br \/>\nphases:<br \/>\n  phase_1_preparation:<br \/>\n    description: &#034;\u57fa\u7840\u8bbe\u65bd\u51c6\u5907&#034;<br \/>\n    actions:<br \/>\n      &#8211; \u66f4\u65b0\u8d1f\u8f7d\u5747\u8861\u5668\u652f\u6301HTTP\/2<br \/>\n      &#8211; \u914d\u7f6eTLS 1.2&#043; (HTTP\/2\u8981\u6c42)<br \/>\n      &#8211; \u90e8\u7f72HTTP\/2\u517c\u5bb9\u7684Web\u670d\u52a1\u5668<br \/>\n    metrics:<br \/>\n      &#8211; tls_1_2_coverage: &#034;&gt;99%&#034;<br \/>\n      &#8211; http2_support_score: &#034;&gt;90&#034;<\/p>\n<p>  phase_2_dual_protocol:<br \/>\n    description: &#034;\u53cc\u534f\u8bae\u8fd0\u884c&#034;<br \/>\n    actions:<br \/>\n      &#8211; \u540c\u65f6\u652f\u6301HTTP\/1.1\u548cHTTP\/2<br \/>\n      &#8211; \u76d1\u63a7\u5404\u534f\u8bae\u6027\u80fd\u6307\u6807<br \/>\n      &#8211; \u4f18\u5316HTTP\/2\u7279\u5b9a\u914d\u7f6e<br \/>\n    duration: &#034;4-8 weeks&#034;<\/p>\n<p>  phase_3_http3_experimental:<br \/>\n    description: &#034;HTTP\/3\u5b9e\u9a8c\u6027\u90e8\u7f72&#034;<br \/>\n    actions:<br \/>\n      &#8211; \u542f\u7528QUIC\u652f\u6301<br \/>\n      &#8211; \u9762\u5411\u90e8\u5206\u7528\u6237\u5b9e\u9a8c<br \/>\n      &#8211; \u6536\u96c6\u6027\u80fd\u6570\u636e<br \/>\n    rollback_plan: &#034;\u7981\u7528QUIC&#xff0c;\u56de\u9000\u5230HTTP\/2&#034;<\/p>\n<p>  phase_4_optimization:<br \/>\n    description: &#034;\u57fa\u4e8e\u6570\u636e\u7684\u4f18\u5316&#034;<br \/>\n    actions:<br \/>\n      &#8211; \u5206\u6790\u5404HTTP\u7248\u672c\u6027\u80fd<br \/>\n      &#8211; \u8c03\u6574\u534f\u8bae\u53c2\u6570<br \/>\n      &#8211; \u5b9e\u73b0\u667a\u80fd\u534f\u8bae\u9009\u62e9<\/p>\n<h5>35.5.2 \u534f\u8bae\u9009\u62e9\u7b56\u7565<\/h5>\n<p>javascript<\/p>\n<p>\/\/ \u667a\u80fd\u534f\u8bae\u9009\u62e9\u7b97\u6cd5<br \/>\nclass ProtocolSelector {<br \/>\n    constructor(options) {<br \/>\n        this.options &#061; options;<br \/>\n        this.metrics &#061; new ProtocolMetrics();<br \/>\n    }<\/p>\n<p>    selectProtocol(clientInfo, serverCapabilities) {<br \/>\n        const factors &#061; this.evaluateFactors(clientInfo);<\/p>\n<p>        \/\/ \u6253\u5206\u7b97\u6cd5<br \/>\n        const scores &#061; {<br \/>\n            &#039;http\/1.1&#039;: this.scoreHTTP11(factors),<br \/>\n            &#039;http\/2&#039;: this.scoreHTTP2(factors),<br \/>\n            &#039;http\/3&#039;: this.scoreHTTP3(factors)<br \/>\n        };<\/p>\n<p>        \/\/ \u9009\u62e9\u6700\u9ad8\u5206\u534f\u8bae<br \/>\n        let selected &#061; &#039;http\/1.1&#039;;<br \/>\n        let maxScore &#061; -1;<\/p>\n<p>        for (const [protocol, score] of Object.entries(scores)) {<br \/>\n            if (score &gt; maxScore &amp;&amp;<br \/>\n                serverCapabilities.includes(protocol)) {<br \/>\n                maxScore &#061; score;<br \/>\n                selected &#061; protocol;<br \/>\n            }<br \/>\n        }<\/p>\n<p>        return selected;<br \/>\n    }<\/p>\n<p>    evaluateFactors(clientInfo) {<br \/>\n        return {<br \/>\n            \/\/ \u7f51\u7edc\u8d28\u91cf<br \/>\n            rtt: clientInfo.rtt,<br \/>\n            packetLoss: clientInfo.packetLoss,<br \/>\n            bandwidth: clientInfo.bandwidth,<\/p>\n<p>            \/\/ \u8bbe\u5907\u80fd\u529b<br \/>\n            supportsHTTP2: clientInfo.supportsHTTP2,<br \/>\n            supportsHTTP3: clientInfo.supportsHTTP3,<\/p>\n<p>            \/\/ \u4f7f\u7528\u6a21\u5f0f<br \/>\n            isMobile: clientInfo.isMobile,<br \/>\n            concurrentRequests: clientInfo.typicalConcurrency,<\/p>\n<p>            \/\/ \u5386\u53f2\u8868\u73b0<br \/>\n            historicalPerformance: this.metrics.getHistoricalPerformance(<br \/>\n                clientInfo.userAgent, clientInfo.networkType<br \/>\n            )<br \/>\n        };<br \/>\n    }<\/p>\n<p>    scoreHTTP11(factors) {<br \/>\n        \/\/ HTTP\/1.1\u5728\u4ee5\u4e0b\u60c5\u51b5\u8868\u73b0\u597d&#xff1a;<br \/>\n        \/\/ 1. \u9ad8\u5ef6\u8fdf\u7f51\u7edc&#xff08;\u907f\u514d\u961f\u5934\u963b\u585e\u5f71\u54cd\u4e0d\u5927&#xff09;<br \/>\n        \/\/ 2. \u65e7\u5ba2\u6237\u7aef<br \/>\n        \/\/ 3. \u5c11\u91cf\u5e76\u53d1\u8bf7\u6c42<br \/>\n        let score &#061; 50; \/\/ \u57fa\u7840\u5206<\/p>\n<p>        if (!factors.supportsHTTP2 &amp;&amp; !factors.supportsHTTP3) {<br \/>\n            score &#043;&#061; 30; \/\/ \u4ec5\u652f\u6301HTTP\/1.1<br \/>\n        }<\/p>\n<p>        if (factors.concurrentRequests &lt; 3) {<br \/>\n            score &#043;&#061; 10; \/\/ \u4f4e\u5e76\u53d1\u65f6HTTP\/1.1\u8db3\u591f<br \/>\n        }<\/p>\n<p>        if (factors.packetLoss &gt; 0.1) {<br \/>\n            score -&#061; 20; \/\/ \u9ad8\u4e22\u5305\u7387\u4e0d\u5229<br \/>\n        }<\/p>\n<p>        return score;<br \/>\n    }<\/p>\n<p>    scoreHTTP2(factors) {<br \/>\n        \/\/ HTTP\/2\u5728\u4ee5\u4e0b\u60c5\u51b5\u8868\u73b0\u597d&#xff1a;<br \/>\n        \/\/ 1. \u9ad8\u5e76\u53d1\u8bf7\u6c42<br \/>\n        \/\/ 2. \u9700\u8981\u670d\u52a1\u5668\u63a8\u9001<br \/>\n        \/\/ 3. \u7a33\u5b9a\u7f51\u7edc\u73af\u5883<br \/>\n        let score &#061; 70; \/\/ \u57fa\u7840\u5206<\/p>\n<p>        if (factors.concurrentRequests &gt; 6) {<br \/>\n            score &#043;&#061; 20; \/\/ \u9ad8\u5e76\u53d1\u4f18\u52bf\u660e\u663e<br \/>\n        }<\/p>\n<p>        if (factors.rtt &lt; 100 &amp;&amp; factors.packetLoss &lt; 0.05) {<br \/>\n            score &#043;&#061; 15; \/\/ \u7a33\u5b9a\u7f51\u7edc<br \/>\n        }<\/p>\n<p>        if (factors.isMobile &amp;&amp; factors.bandwidth &lt; 5) {<br \/>\n            score &#043;&#061; 10; \/\/ \u79fb\u52a8\u7f51\u7edc\u5934\u90e8\u538b\u7f29\u4f18\u52bf<br \/>\n        }<\/p>\n<p>        return score;<br \/>\n    }<\/p>\n<p>    scoreHTTP3(factors) {<br \/>\n        \/\/ HTTP\/3\u5728\u4ee5\u4e0b\u60c5\u51b5\u8868\u73b0\u597d&#xff1a;<br \/>\n        \/\/ 1. \u9ad8\u4e22\u5305\u7387\u7f51\u7edc<br \/>\n        \/\/ 2. \u9891\u7e41\u7f51\u7edc\u5207\u6362<br \/>\n        \/\/ 3. \u9700\u89810-RTT\u8fde\u63a5<br \/>\n        let score &#061; 60; \/\/ \u57fa\u7840\u5206<\/p>\n<p>        if (factors.packetLoss &gt; 0.05) {<br \/>\n            score &#043;&#061; 25; \/\/ \u6297\u4e22\u5305\u80fd\u529b\u5f3a<br \/>\n        }<\/p>\n<p>        if (factors.isMobile) {<br \/>\n            score &#043;&#061; 15; \/\/ \u79fb\u52a8\u7f51\u7edc\u4f18\u52bf<br \/>\n        }<\/p>\n<p>        if (factors.rtt &gt; 200) {<br \/>\n            score &#043;&#061; 10; \/\/ \u9ad8\u5ef6\u8fdf\u7f51\u7edc<br \/>\n        }<\/p>\n<p>        \/\/ \u8003\u8651\u6210\u719f\u5ea6\u8c03\u6574<br \/>\n        score -&#061; 10; \/\/ \u76f8\u5bf9\u8f83\u65b0&#xff0c;\u5de5\u5177\u94fe\u4e0d\u5b8c\u5584<\/p>\n<p>        return score;<br \/>\n    }<br \/>\n}<\/p>\n<h5>35.5.3 \u9519\u8bef\u5904\u7406\u7684\u7edf\u4e00\u62bd\u8c61\u5c42<\/h5>\n<p>java<\/p>\n<p>\/\/ \u8de8HTTP\u7248\u672c\u7684\u7edf\u4e00\u9519\u8bef\u5904\u7406\u62bd\u8c61<br \/>\npublic abstract class HTTPErrorHandler {<\/p>\n<p>    \/\/ \u7edf\u4e00\u7684\u72b6\u6001\u7801\u6620\u5c04<br \/>\n    protected static final Map&lt;Integer, String&gt; STATUS_MESSAGES &#061; Map.of(<br \/>\n        200, &#034;OK&#034;,<br \/>\n        404, &#034;Not Found&#034;,<br \/>\n        500, &#034;Internal Server Error&#034;,<br \/>\n        \/\/ &#8230; \u5176\u4ed6\u72b6\u6001\u7801<br \/>\n    );<\/p>\n<p>    \/\/ \u534f\u8bae\u7279\u5b9a\u7684\u9519\u8bef\u8f6c\u6362<br \/>\n    public abstract HTTPError translateProtocolError(<br \/>\n        ProtocolSpecificError protocolError);<\/p>\n<p>    \/\/ \u751f\u6210\u7528\u6237\u53cb\u597d\u7684\u9519\u8bef\u54cd\u5e94<br \/>\n    public abstract ErrorResponse generateErrorResponse(<br \/>\n        HTTPError error,<br \/>\n        RequestContext context);<\/p>\n<p>    \/\/ \u65e5\u5fd7\u8bb0\u5f55<br \/>\n    public abstract void logError(HTTPError error,<br \/>\n                                  RequestContext context);<br \/>\n}<\/p>\n<p>\/\/ HTTP\/2\u9519\u8bef\u5904\u7406\u5668\u5b9e\u73b0<br \/>\npublic class HTTP2ErrorHandler extends HTTPErrorHandler {<\/p>\n<p>    &#064;Override<br \/>\n    public HTTPError translateProtocolError(<br \/>\n            ProtocolSpecificError protocolError) {<\/p>\n<p>        if (protocolError instanceof RSTStreamError) {<br \/>\n            RSTStreamError rstError &#061; (RSTStreamError) protocolError;<\/p>\n<p>            \/\/ \u5c06RST_STREAM\u9519\u8bef\u4ee3\u7801\u6620\u5c04\u5230HTTP\u72b6\u6001\u7801<br \/>\n            switch (rstError.getErrorCode()) {<br \/>\n                case REFUSED_STREAM:<br \/>\n                    return new HTTPError(503, &#034;Service Temporarily Unavailable&#034;);<br \/>\n                case INTERNAL_ERROR:<br \/>\n                    return new HTTPError(500, &#034;Internal Server Error&#034;);<br \/>\n                case PROTOCOL_ERROR:<br \/>\n                    return new HTTPError(400, &#034;Bad Request&#034;);<br \/>\n                default:<br \/>\n                    return new HTTPError(500, &#034;Protocol Error&#034;);<br \/>\n            }<br \/>\n        }<\/p>\n<p>        return super.translateProtocolError(protocolError);<br \/>\n    }<br \/>\n}<\/p>\n<p>\/\/ HTTP\/3\u9519\u8bef\u5904\u7406\u5668\u5b9e\u73b0<br \/>\npublic class HTTP3ErrorHandler extends HTTPErrorHandler {<\/p>\n<p>    &#064;Override<br \/>\n    public HTTPError translateProtocolError(<br \/>\n            ProtocolSpecificError protocolError) {<\/p>\n<p>        if (protocolError instanceof QUICError) {<br \/>\n            QUICError quicError &#061; (QUICError) protocolError;<\/p>\n<p>            \/\/ QUIC\u9519\u8bef\u6620\u5c04<br \/>\n            switch (quicError.getErrorCode()) {<br \/>\n                case CONNECTION_REFUSED:<br \/>\n                    return new HTTPError(503, &#034;Connection Refused&#034;);<br \/>\n                case CRYPTO_BUFFER_EXCEEDED:<br \/>\n                    return new HTTPError(431, &#034;Request Header Fields Too Large&#034;);<br \/>\n                default:<br \/>\n                    return new HTTPError(500, &#034;Transport Error&#034;);<br \/>\n            }<br \/>\n        }<\/p>\n<p>        return super.translateProtocolError(protocolError);<br \/>\n    }<br \/>\n}<\/p>\n<h4>35.6 \u6027\u80fd\u4f18\u5316\u7b56\u7565<\/h4>\n<h5>35.6.1 HTTP\/2\u7279\u5b9a\u4f18\u5316<\/h5>\n<p>nginx<\/p>\n<p># Nginx HTTP\/2\u4f18\u5316\u914d\u7f6e<br \/>\nhttp {<br \/>\n    # \u542f\u7528HTTP\/2<br \/>\n    listen 443 ssl http2;<\/p>\n<p>    # HTTP\/2\u4f18\u5316\u53c2\u6570<br \/>\n    http2_max_field_size 16k;      # \u6700\u5927\u5934\u90e8\u5b57\u6bb5\u5927\u5c0f<br \/>\n    http2_max_header_size 64k;     # \u6700\u5927\u5934\u90e8\u603b\u5927\u5c0f<br \/>\n    http2_max_concurrent_streams 128; # \u6700\u5927\u5e76\u53d1\u6d41\u6570<br \/>\n    http2_max_requests 1000;       # \u5355\u4e2a\u8fde\u63a5\u6700\u5927\u8bf7\u6c42\u6570<br \/>\n    http2_body_preread_size 64k;   # \u8bf7\u6c42\u4f53\u9884\u8bfb\u5927\u5c0f<\/p>\n<p>    # \u8fde\u63a5\u8d85\u65f6\u8bbe\u7f6e<br \/>\n    http2_idle_timeout 3m;         # \u7a7a\u95f2\u8d85\u65f6<br \/>\n    http2_recv_timeout 30s;        # \u63a5\u6536\u8d85\u65f6<\/p>\n<p>    # \u6d41\u91cf\u63a7\u5236<br \/>\n    http2_chunk_size 8k;           # DATA\u5e27\u5927\u5c0f<br \/>\n    http2_max_concurrent_pushes 10; # \u6700\u5927\u5e76\u53d1\u63a8\u9001\u6570<\/p>\n<p>    # \u670d\u52a1\u5668\u63a8\u9001\u914d\u7f6e<br \/>\n    location &#061; \/index.html {<br \/>\n        http2_push \/style.css;     # \u63a8\u9001CSS<br \/>\n        http2_push \/app.js;        # \u63a8\u9001JS<br \/>\n        http2_push_preload on;     # \u542f\u7528\u9884\u52a0\u8f7d<br \/>\n    }<br \/>\n}<\/p>\n<h5>35.6.2 HTTP\/3\/QUIC\u4f18\u5316<\/h5>\n<p>bash<\/p>\n<p># QUIC\u6027\u80fd\u8c03\u4f18\u53c2\u6570<br \/>\n# \u7f16\u8bd1\u652f\u6301HTTP\/3\u7684Nginx<br \/>\n.\/configure \\\\<br \/>\n    &#8211;with-http_v3_module \\\\<br \/>\n    &#8211;with-stream_quic_module \\\\<br \/>\n    &#8211;with-openssl&#061;..\/openssl \\\\<br \/>\n    &#8211;with-cc-opt&#061;&#034;-I..\/openssl\/include&#034; \\\\<br \/>\n    &#8211;with-ld-opt&#061;&#034;-L..\/openssl\/lib&#034;<\/p>\n<p># QUIC\u5185\u6838\u53c2\u6570\u4f18\u5316<br \/>\n# \u589e\u52a0UDP\u7f13\u51b2\u533a\u5927\u5c0f<br \/>\nsysctl -w net.core.rmem_max&#061;2500000<br \/>\nsysctl -w net.core.wmem_max&#061;2500000<br \/>\nsysctl -w net.ipv4.udp_mem&#061;&#034;4096 87380 2500000&#034;<\/p>\n<p># \u542f\u7528GSO(Generic Segmentation Offload)<br \/>\nethtool -K eth0 gso on<br \/>\nethtool -K eth0 tso on<br \/>\nethtool -K eth0 gro on<\/p>\n<p># \u8c03\u6574UDP\u8fde\u63a5\u8ddf\u8e2a<br \/>\nsysctl -w net.netfilter.nf_conntrack_udp_timeout&#061;30<br \/>\nsysctl -w net.netfilter.nf_conntrack_udp_timeout_stream&#061;60<\/p>\n<h4>35.7 \u76d1\u63a7\u4e0e\u8c03\u8bd5<\/h4>\n<h5>35.7.1 \u534f\u8bae\u7ea7\u522b\u7684\u76d1\u63a7\u6307\u6807<\/h5>\n<p>prometheus<\/p>\n<p># HTTP\/2\u7279\u5b9a\u6307\u6807<br \/>\n# Prometheus\u6307\u6807\u5b9a\u4e49<br \/>\nhttp2_connections_total{protocol&#061;&#034;h2&#034;, status&#061;&#034;active&#034;}<br \/>\nhttp2_streams_total{stream_type&#061;&#034;request&#034;}<br \/>\nhttp2_streams_active<br \/>\nhttp2_resets_total{error_code&#061;&#034;NO_ERROR&#034;}<br \/>\nhttp2_settings_total{setting&#061;&#034;HEADER_TABLE_SIZE&#034;}<br \/>\nhttp2_goaway_total{last_stream_id&#061;&#034;*&#034;, error_code&#061;&#034;*&#034;}<\/p>\n<p># QUIC\/HTTP\/3\u6307\u6807<br \/>\nquic_connections_total{version&#061;&#034;draft-29&#034;}<br \/>\nquic_handshake_duration_seconds<br \/>\nquic_packets_lost_total<br \/>\nquic_connection_migration_total<br \/>\nhttp3_streams_active<\/p>\n<h5>35.7.2 \u8c03\u8bd5\u5de5\u5177\u548c\u6280\u5de7<\/h5>\n<p>bash<\/p>\n<p># \u4f7f\u7528curl\u6d4b\u8bd5\u4e0d\u540cHTTP\u7248\u672c<br \/>\n# \u6d4b\u8bd5HTTP\/2<br \/>\ncurl &#8211;http2 -v https:\/\/example.com<br \/>\ncurl &#8211;http2-prior-knowledge -v http:\/\/example.com<\/p>\n<p># \u6d4b\u8bd5HTTP\/3 (\u9700\u8981\u652f\u6301QUIC\u7684curl)<br \/>\ncurl &#8211;http3 -v https:\/\/example.com<\/p>\n<p># \u4f7f\u7528nghttp2\u8fdb\u884cHTTP\/2\u8c03\u8bd5<br \/>\nnghttp -v https:\/\/example.com<br \/>\nnghttp -v &#8211;no-tls http:\/\/example.com:80<\/p>\n<p># Wireshark\u8fc7\u6ee4\u8868\u8fbe\u5f0f<br \/>\n# HTTP\/2\u6d41\u91cf<br \/>\nhttp2<br \/>\nhttp2.stream.id &#061;&#061; 1<br \/>\nhttp2.headers.status &#061;&#061; 200<\/p>\n<p># QUIC\u6d41\u91cf<br \/>\nquic<br \/>\nquic.version &#061;&#061; &#034;draft-29&#034;<br \/>\nquic.long.packet_type &#061;&#061; &#034;initial&#034;<\/p>\n<p># Chrome\u5f00\u53d1\u8005\u5de5\u5177<br \/>\n# network\u9762\u677f\u67e5\u770b\u534f\u8bae\u7248\u672c<br \/>\n# \u542f\u7528HTTP\/2\u65e5\u5fd7<br \/>\nchrome:\/\/net-internals\/#http2<br \/>\nchrome:\/\/net-internals\/#quic<\/p>\n<h4>35.8 \u603b\u7ed3\u4e0e\u5c55\u671b<\/h4>\n<p>HTTP\/2\u548cHTTP\/3\u901a\u8fc7\u5f15\u5165\u4e8c\u8fdb\u5236\u5206\u5e27\u3001\u591a\u8def\u590d\u7528\u3001\u5934\u90e8\u538b\u7f29\u3001\u670d\u52a1\u5668\u63a8\u9001\u7b49\u7279\u6027&#xff0c;\u663e\u8457\u63d0\u5347\u4e86Web\u6027\u80fd\u3002\u5bf9\u72b6\u6001\u7801\u5904\u7406\u7684\u4e3b\u8981\u5f71\u54cd\u5305\u62ec&#xff1a;<\/p>\n<li>\n<p>\u72b6\u6001\u7801\u4f20\u8f93\u6548\u7387\u63d0\u5347&#xff1a;\u901a\u8fc7HPACK\/QPACK\u538b\u7f29&#xff0c;\u9ad8\u9891\u72b6\u6001\u7801\u53ea\u97001\u5b57\u8282<\/p>\n<\/li>\n<li>\n<p>\u66f4\u7ec6\u7c92\u5ea6\u7684\u9519\u8bef\u5904\u7406&#xff1a;RST_STREAM\u5141\u8bb8\u7ec8\u6b62\u5355\u4e2a\u6d41\u800c\u4e0d\u5f71\u54cd\u8fde\u63a5<\/p>\n<\/li>\n<li>\n<p>\u6539\u8fdb\u7684\u8fde\u63a5\u7ba1\u7406&#xff1a;QUIC\u51cf\u5c11\u961f\u5934\u963b\u585e&#xff0c;\u63d0\u4f9b\u66f4\u597d\u7684\u79fb\u52a8\u4f53\u9a8c<\/p>\n<\/li>\n<li>\n<p>\u590d\u6742\u7684\u76d1\u63a7\u9700\u6c42&#xff1a;\u591a\u8def\u590d\u7528\u9700\u8981\u66f4\u7ec6\u81f4\u7684\u6d41\u7ea7\u522b\u76d1\u63a7<\/p>\n<\/li>\n<p>\u672a\u6765\u8d8b\u52bf&#xff1a;<\/p>\n<ul>\n<li>\n<p>HTTP\/3\u9010\u6e10\u666e\u53ca&#xff0c;\u7279\u522b\u662f\u5728\u79fb\u52a8\u548c\u4e0d\u53ef\u9760\u7f51\u7edc\u73af\u5883<\/p>\n<\/li>\n<li>\n<p>\u667a\u80fd\u534f\u8bae\u9009\u62e9\u6210\u4e3a\u6807\u51c6\u529f\u80fd<\/p>\n<\/li>\n<li>\n<p>\u8fb9\u7f18\u8ba1\u7b97\u63a8\u52a8HTTP\u534f\u8bae\u4f18\u5316<\/p>\n<\/li>\n<li>\n<p>\u5b89\u5168\u6027\u6301\u7eed\u589e\u5f3a&#xff08;TLS 1.3\u6210\u4e3a\u6807\u914d&#xff09;<\/p>\n<\/li>\n<\/ul>\n<p>\u968f\u7740\u534f\u8bae\u6f14\u8fdb&#xff0c;\u72b6\u6001\u7801\u867d\u7136\u8bed\u4e49\u4fdd\u6301\u4e0d\u53d8&#xff0c;\u4f46\u5176\u4f20\u8f93\u3001\u5904\u7406\u548c\u76d1\u63a7\u65b9\u5f0f\u6b63\u5728\u53d1\u751f\u6df1\u523b\u53d8\u5316&#xff0c;\u5f00\u53d1\u8005\u9700\u8981\u9002\u5e94\u8fd9\u4e9b\u53d8\u5316\u4ee5\u6784\u5efa\u9ad8\u6027\u80fd\u3001\u53ef\u9760\u7684Web\u670d\u52a1\u3002<\/p>\n<hr \/>\n<h3>\u7b2c36\u7ae0&#xff1a;\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u4e0e\u6269\u5c55\u72b6\u6001\u7801<\/h3>\n<h4>36.1 \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u7684\u9700\u6c42\u4e0e\u573a\u666f<\/h4>\n<h5>36.1.1 \u4e1a\u52a1\u7279\u5b9a\u72b6\u6001\u9700\u6c42<\/h5>\n<p>\u968f\u7740\u5fae\u670d\u52a1\u67b6\u6784\u548cAPI\u7ecf\u6d4e\u7684\u5174\u8d77&#xff0c;\u6807\u51c6HTTP\u72b6\u6001\u7801\u5df2\u65e0\u6cd5\u6ee1\u8db3\u6240\u6709\u4e1a\u52a1\u573a\u666f\u7684\u9700\u6c42&#xff1a;<\/p>\n<p>python<\/p>\n<p># \u7535\u5546\u7cfb\u7edf\u7279\u6709\u7684\u72b6\u6001\u573a\u666f<br \/>\nclass ECommerceStatusCodes:<br \/>\n    &#034;&#034;&#034;\u7535\u5546\u4e1a\u52a1\u81ea\u5b9a\u4e49\u72b6\u6001\u7801&#034;&#034;&#034;<\/p>\n<p>    # \u5e93\u5b58\u76f8\u5173 (\u6269\u5c554xx)<br \/>\n    OUT_OF_STOCK &#061; 460          # \u5546\u54c1\u7f3a\u8d27<br \/>\n    INSUFFICIENT_INVENTORY &#061; 461 # \u5e93\u5b58\u4e0d\u8db3<br \/>\n    PRICE_CHANGED &#061; 462         # \u4ef7\u683c\u5df2\u53d8\u66f4<br \/>\n    PRODUCT_DISCONTINUED &#061; 463  # \u5546\u54c1\u5df2\u4e0b\u67b6<\/p>\n<p>    # \u8ba2\u5355\u76f8\u5173 (\u6269\u5c552xx)<br \/>\n    ORDER_PARTIALLY_FULFILLED &#061; 210  # \u8ba2\u5355\u90e8\u5206\u5b8c\u6210<br \/>\n    PAYMENT_PENDING &#061; 211            # \u652f\u4ed8\u5904\u7406\u4e2d<br \/>\n    SHIPPING_DELAYED &#061; 212           # \u53d1\u8d27\u5ef6\u8fdf<\/p>\n<p>    # \u4fc3\u9500\u76f8\u5173<br \/>\n    COUPON_EXPIRED &#061; 480             # \u4f18\u60e0\u5238\u8fc7\u671f<br \/>\n    PROMOTION_LIMIT_EXCEEDED &#061; 481   # \u4fc3\u9500\u9650\u5236\u8d85\u9650<br \/>\n    LOYALTY_POINTS_INSUFFICIENT &#061; 482 # \u79ef\u5206\u4e0d\u8db3<\/p>\n<h5>36.1.2 API\u7f51\u5173\u4e0e\u5fae\u670d\u52a1\u901a\u4fe1<\/h5>\n<p>\u5728\u5fae\u670d\u52a1\u67b6\u6784\u4e2d&#xff0c;\u9700\u8981\u66f4\u4e30\u5bcc\u7684\u72b6\u6001\u4fe1\u606f\u6765\u4f20\u9012\u670d\u52a1\u95f4\u7684\u590d\u6742\u72b6\u6001&#xff1a;<\/p>\n<p>json<\/p>\n<p>{<br \/>\n  &#034;status&#034;: 570,<br \/>\n  &#034;code&#034;: &#034;CIRCUIT_BREAKER_OPEN&#034;,<br \/>\n  &#034;message&#034;: &#034;\u5546\u54c1\u670d\u52a1\u7194\u65ad\u5668\u5df2\u5f00\u542f&#034;,<br \/>\n  &#034;details&#034;: {<br \/>\n    &#034;service&#034;: &#034;product-service&#034;,<br \/>\n    &#034;failure_rate&#034;: &#034;85%&#034;,<br \/>\n    &#034;last_failure&#034;: &#034;2023-10-01T10:30:00Z&#034;,<br \/>\n    &#034;estimated_recovery&#034;: &#034;2023-10-01T10:35:00Z&#034;<br \/>\n  },<br \/>\n  &#034;retry_after&#034;: 300,<br \/>\n  &#034;fallback_available&#034;: true,<br \/>\n  &#034;alternative_endpoints&#034;: [<br \/>\n    &#034;https:\/\/product-fallback.example.com&#034;<br \/>\n  ]<br \/>\n}<\/p>\n<h5>36.1.3 \u5b9e\u65f6\u901a\u4fe1\u4e0eWebSocket<\/h5>\n<p>WebSocket\u548c\u5b9e\u65f6API\u9700\u8981\u7279\u6b8a\u7684\u72b6\u6001\u6307\u793a&#xff1a;<\/p>\n<p>javascript<\/p>\n<p>\/\/ WebSocket\u8fde\u63a5\u72b6\u6001\u6269\u5c55<br \/>\nconst WebSocketStatusCodes &#061; {<br \/>\n    \/\/ \u8fde\u63a5\u5efa\u7acb\u9636\u6bb5<br \/>\n    1001: &#034;WEBSOCKET_HANDSHAKE_FAILED&#034;,<br \/>\n    1002: &#034;WEBSOCKET_PROTOCOL_MISMATCH&#034;,<br \/>\n    1003: &#034;WEBSOCKET_UNSUPPORTED_DATA_FORMAT&#034;,<\/p>\n<p>    \/\/ \u8fde\u63a5\u751f\u547d\u5468\u671f<br \/>\n    1010: &#034;WEBSOCKET_CONNECTION_LIMIT_EXCEEDED&#034;,<br \/>\n    1011: &#034;WEBSOCKET_SERVER_ERROR&#034;,<br \/>\n    1012: &#034;WEBSOCKET_SERVICE_RESTARTING&#034;,<br \/>\n    1013: &#034;WEBSOCKET_TRY_AGAIN_LATER&#034;,<\/p>\n<p>    \/\/ \u4e1a\u52a1\u72b6\u6001<br \/>\n    1100: &#034;WEBSOCKET_SESSION_EXPIRED&#034;,<br \/>\n    1101: &#034;WEBSOCKET_RATE_LIMITED&#034;,<br \/>\n    1102: &#034;WEBSOCKET_INVALID_MESSAGE_FORMAT&#034;<br \/>\n};<\/p>\n<h4>36.2 \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u7684\u8bbe\u8ba1\u539f\u5219<\/h4>\n<h5>36.2.1 \u517c\u5bb9\u6027\u539f\u5219<\/h5>\n<p>\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u5fc5\u987b\u4e0e\u73b0\u6709HTTP\u72b6\u6001\u7801\u4f53\u7cfb\u517c\u5bb9&#xff1a;<\/p>\n<p>typescript<\/p>\n<p>interface CustomStatusCode {<br \/>\n    \/\/ \u5fc5\u987b\u9075\u5b88HTTP\u72b6\u6001\u7801\u8303\u56f4\u89c4\u5219<br \/>\n    readonly value: number;<\/p>\n<p>    \/\/ \u72b6\u6001\u7801\u5206\u7c7b<br \/>\n    readonly category: &#039;1xx&#039; | &#039;2xx&#039; | &#039;3xx&#039; | &#039;4xx&#039; | &#039;5xx&#039;;<\/p>\n<p>    \/\/ \u8bed\u4e49\u5b9a\u4e49<br \/>\n    readonly description: string;<br \/>\n    readonly specification: string;<\/p>\n<p>    \/\/ \u517c\u5bb9\u6027\u6807\u8bb0<br \/>\n    readonly isExperimental?: boolean;<br \/>\n    readonly isDeprecated?: boolean;<br \/>\n    readonly sinceVersion?: string;<\/p>\n<p>    \/\/ \u6807\u51c6\u6269\u5c55\u70b9<br \/>\n    static readonly EXTENSION_RANGES &#061; {<br \/>\n        &#039;1xx&#039;: [100, 199],      \/\/ \u4fe1\u606f\u54cd\u5e94<br \/>\n        &#039;2xx&#039;: [200, 299],      \/\/ \u6210\u529f\u54cd\u5e94<br \/>\n        &#039;3xx&#039;: [300, 399],      \/\/ \u91cd\u5b9a\u5411<br \/>\n        &#039;4xx&#039;: [400, 499],      \/\/ \u5ba2\u6237\u7aef\u9519\u8bef<br \/>\n        &#039;5xx&#039;: [500, 599],      \/\/ \u670d\u52a1\u5668\u9519\u8bef<\/p>\n<p>        \/\/ IANA\u6ce8\u518c\u8303\u56f4<br \/>\n        &#039;IANA_REGISTERED&#039;: [100, 599],<\/p>\n<p>        \/\/ \u81ea\u5b9a\u4e49\u6269\u5c55\u8303\u56f4&#xff08;\u5efa\u8bae&#xff09;<br \/>\n        &#039;CUSTOM_EXPERIMENTAL&#039;: [420, 430],  \/\/ \u5b9e\u9a8c\u6027<br \/>\n        &#039;CUSTOM_BUSINESS&#039;: [450, 499],      \/\/ \u4e1a\u52a1\u7279\u5b9a<br \/>\n        &#039;CUSTOM_SYSTEM&#039;: [520, 599]         \/\/ \u7cfb\u7edf\u6269\u5c55<br \/>\n    };<\/p>\n<p>    \/\/ \u9a8c\u8bc1\u65b9\u6cd5<br \/>\n    static isValidCustomCode(code: number): boolean {<br \/>\n        const ranges &#061; this.EXTENSION_RANGES;<br \/>\n        return (<br \/>\n            (code &gt;&#061; ranges.CUSTOM_EXPERIMENTAL[0] &amp;&amp;<br \/>\n             code &lt;&#061; ranges.CUSTOM_EXPERIMENTAL[1]) ||<br \/>\n            (code &gt;&#061; ranges.CUSTOM_BUSINESS[0] &amp;&amp;<br \/>\n             code &lt;&#061; ranges.CUSTOM_BUSINESS[1]) ||<br \/>\n            (code &gt;&#061; ranges.CUSTOM_SYSTEM[0] &amp;&amp;<br \/>\n             code &lt;&#061; ranges.CUSTOM_SYSTEM[1])<br \/>\n        );<br \/>\n    }<br \/>\n}<\/p>\n<h5>36.2.2 \u8bed\u4e49\u6e05\u6670\u539f\u5219<\/h5>\n<p>\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u5fc5\u987b\u6709\u660e\u786e\u7684\u8bed\u4e49\u5b9a\u4e49&#xff1a;<\/p>\n<p>yaml<\/p>\n<p># \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u8bed\u4e49\u5b9a\u4e49\u89c4\u8303<br \/>\ncode: 460<br \/>\ncategory: 4xx<br \/>\nsummary: &#034;Out of Stock&#034;<br \/>\ndescription: &gt;<br \/>\n  \u8bf7\u6c42\u7684\u5546\u54c1\u5f53\u524d\u7f3a\u8d27&#xff0c;\u4f46\u5c06\u6765\u53ef\u80fd\u4f1a\u8865\u8d27\u3002<br \/>\n  \u4e0e410 Gone\u4e0d\u540c&#xff0c;460\u8868\u793a\u4e34\u65f6\u6027\u7f3a\u8d27\u3002<\/p>\n<p>specification:<br \/>\n  rfc: &#034;RFC-XXXX&#034;  # \u5982\u679c\u63d0\u4ea4\u4e3aRFC<br \/>\n  draft: &#034;draft-custom-http-status-01&#034;<\/p>\n<p>semantics:<br \/>\n  client_action: &#034;retry_later&#034;<br \/>\n  cacheability: &#034;non_cacheable&#034;<br \/>\n  safe_method: true  # \u5bf9\u5b89\u5168\u65b9\u6cd5\u53ef\u91cd\u8bd5<\/p>\n<p>headers:<br \/>\n  required:<br \/>\n    &#8211; Retry-After<br \/>\n  optional:<br \/>\n    &#8211; X-Stock-Estimate<br \/>\n    &#8211; X-Alternative-Products<\/p>\n<p>body:<br \/>\n  required_fields:<br \/>\n    &#8211; code<br \/>\n    &#8211; message<br \/>\n    &#8211; product_id<br \/>\n  optional_fields:<br \/>\n    &#8211; estimated_restock_date<br \/>\n    &#8211; backorder_available<\/p>\n<p>examples:<br \/>\n  response: |<br \/>\n    HTTP\/1.1 460 Out of Stock<br \/>\n    Retry-After: 3600<br \/>\n    Content-Type: application\/json<\/p>\n<p>    {<br \/>\n      &#034;code&#034;: 460,<br \/>\n      &#034;message&#034;: &#034;Product XYZ is temporarily out of stock&#034;,<br \/>\n      &#034;product_id&#034;: &#034;12345&#034;,<br \/>\n      &#034;estimated_restock_date&#034;: &#034;2023-12-01&#034;,<br \/>\n      &#034;backorder_available&#034;: true<br \/>\n    }<\/p>\n<h5>36.2.3 \u6e10\u8fdb\u5f0f\u91c7\u7528\u7b56\u7565<\/h5>\n<h4>36.3 \u5b9e\u73b0\u81ea\u5b9a\u4e49\u72b6\u6001\u7801<\/h4>\n<h5>36.3.1 \u670d\u52a1\u5668\u7aef\u5b9e\u73b0<\/h5>\n<p>java<\/p>\n<p>\/\/ Spring Boot\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u5b9e\u73b0<br \/>\n&#064;Configuration<br \/>\npublic class CustomStatusCodeConfig {<\/p>\n<p>    \/\/ \u5b9a\u4e49\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u679a\u4e3e<br \/>\n    public enum CustomHttpStatus {<\/p>\n<p>        \/\/ \u4e1a\u52a1\u7279\u5b9a\u72b6\u6001\u7801<br \/>\n        OUT_OF_STOCK(460, &#034;Out of Stock&#034;),<br \/>\n        INSUFFICIENT_INVENTORY(461, &#034;Insufficient Inventory&#034;),<br \/>\n        PAYMENT_PROCESSING(210, &#034;Payment Processing&#034;),<\/p>\n<p>        \/\/ \u7cfb\u7edf\u6269\u5c55\u72b6\u6001\u7801<br \/>\n        CIRCUIT_BREAKER_OPEN(520, &#034;Circuit Breaker Open&#034;),<br \/>\n        SERVICE_DEGRADED(521, &#034;Service Degraded&#034;),<br \/>\n        MAINTENANCE_MODE(503, &#034;Service Unavailable&#034;); \/\/ \u91cd\u7528503\u4f46\u4e0d\u540c\u8bed\u4e49<\/p>\n<p>        private final int value;<br \/>\n        private final String reasonPhrase;<\/p>\n<p>        CustomHttpStatus(int value, String reasonPhrase) {<br \/>\n            this.value &#061; value;<br \/>\n            this.reasonPhrase &#061; reasonPhrase;<br \/>\n        }<\/p>\n<p>        public int value() {<br \/>\n            return this.value;<br \/>\n        }<\/p>\n<p>        public String getReasonPhrase() {<br \/>\n            return this.reasonPhrase;<br \/>\n        }<\/p>\n<p>        \/\/ \u8f6c\u6362\u4e3aHttpStatus<br \/>\n        public HttpStatus toHttpStatus() {<br \/>\n            return HttpStatus.valueOf(this.value);<br \/>\n        }<br \/>\n    }<\/p>\n<p>    \/\/ \u81ea\u5b9a\u4e49\u5f02\u5e38\u5904\u7406\u5668<br \/>\n    &#064;ControllerAdvice<br \/>\n    public class CustomExceptionHandler {<\/p>\n<p>        &#064;ExceptionHandler(OutOfStockException.class)<br \/>\n        public ResponseEntity&lt;ErrorResponse&gt; handleOutOfStock(<br \/>\n                OutOfStockException ex) {<\/p>\n<p>            CustomHttpStatus status &#061; CustomHttpStatus.OUT_OF_STOCK;<\/p>\n<p>            ErrorResponse error &#061; ErrorResponse.builder()<br \/>\n                .status(status.value())<br \/>\n                .code(&#034;OUT_OF_STOCK&#034;)<br \/>\n                .message(ex.getMessage())<br \/>\n                .details(ex.getDetails())<br \/>\n                .timestamp(Instant.now())<br \/>\n                .path(ex.getRequestPath())<br \/>\n                .build();<\/p>\n<p>            HttpHeaders headers &#061; new HttpHeaders();<br \/>\n            headers.set(&#034;Retry-After&#034;,<br \/>\n                       String.valueOf(ex.getEstimatedRestockSeconds()));<\/p>\n<p>            return new ResponseEntity&lt;&gt;(error, headers, status.value());<br \/>\n        }<\/p>\n<p>        &#064;ExceptionHandler(CircuitBreakerOpenException.class)<br \/>\n        public ResponseEntity&lt;ErrorResponse&gt; handleCircuitBreaker(<br \/>\n                CircuitBreakerOpenException ex) {<\/p>\n<p>            CustomHttpStatus status &#061; CustomHttpStatus.CIRCUIT_BREAKER_OPEN;<\/p>\n<p>            ErrorResponse error &#061; ErrorResponse.builder()<br \/>\n                .status(status.value())<br \/>\n                .code(&#034;CIRCUIT_BREAKER_OPEN&#034;)<br \/>\n                .message(&#034;Service temporarily unavailable due to high failure rate&#034;)<br \/>\n                .details(Map.of(<br \/>\n                    &#034;service&#034;, ex.getServiceName(),<br \/>\n                    &#034;failure_rate&#034;, ex.getFailureRate(),<br \/>\n                    &#034;open_since&#034;, ex.getOpenSince(),<br \/>\n                    &#034;estimated_recovery&#034;, ex.getEstimatedRecovery()<br \/>\n                ))<br \/>\n                .retryAfter(ex.getRetryAfterSeconds())<br \/>\n                .build();<\/p>\n<p>            HttpHeaders headers &#061; new HttpHeaders();<br \/>\n            headers.set(&#034;Retry-After&#034;,<br \/>\n                       String.valueOf(ex.getRetryAfterSeconds()));<br \/>\n            headers.set(&#034;X-Circuit-Breaker-State&#034;, &#034;OPEN&#034;);<\/p>\n<p>            return new ResponseEntity&lt;&gt;(error, headers, status.value());<br \/>\n        }<br \/>\n    }<br \/>\n}<\/p>\n<p>\/\/ \u81ea\u5b9a\u4e49HttpStatus\u6269\u5c55<br \/>\npublic class ExtendedHttpStatus {<\/p>\n<p>    private static final Map&lt;Integer, String&gt; CUSTOM_STATUS_MAP &#061;<br \/>\n        new ConcurrentHashMap&lt;&gt;();<\/p>\n<p>    static {<br \/>\n        \/\/ \u6ce8\u518c\u81ea\u5b9a\u4e49\u72b6\u6001\u7801<br \/>\n        register(460, &#034;Out of Stock&#034;);<br \/>\n        register(461, &#034;Insufficient Inventory&#034;);<br \/>\n        register(520, &#034;Circuit Breaker Open&#034;);<br \/>\n        register(521, &#034;Service Degraded&#034;);<br \/>\n    }<\/p>\n<p>    public static void register(int code, String reasonPhrase) {<br \/>\n        if (code &lt; 100 || code &gt; 599) {<br \/>\n            throw new IllegalArgumentException(<br \/>\n                &#034;Status code must be between 100 and 599&#034;);<br \/>\n        }<\/p>\n<p>        \/\/ \u907f\u514d\u8986\u76d6\u6807\u51c6\u72b6\u6001\u7801<br \/>\n        if (HttpStatus.resolve(code) !&#061; null) {<br \/>\n            throw new IllegalArgumentException(<br \/>\n                &#034;Cannot override standard HTTP status code: &#034; &#043; code);<br \/>\n        }<\/p>\n<p>        CUSTOM_STATUS_MAP.put(code, reasonPhrase);<br \/>\n    }<\/p>\n<p>    public static Optional&lt;String&gt; getReasonPhrase(int code) {<br \/>\n        \/\/ \u5148\u68c0\u67e5\u6807\u51c6\u72b6\u6001\u7801<br \/>\n        HttpStatus standardStatus &#061; HttpStatus.resolve(code);<br \/>\n        if (standardStatus !&#061; null) {<br \/>\n            return Optional.of(standardStatus.getReasonPhrase());<br \/>\n        }<\/p>\n<p>        \/\/ \u68c0\u67e5\u81ea\u5b9a\u4e49\u72b6\u6001\u7801<br \/>\n        return Optional.ofNullable(CUSTOM_STATUS_MAP.get(code));<br \/>\n    }<\/p>\n<p>    public static boolean isCustomCode(int code) {<br \/>\n        return CUSTOM_STATUS_MAP.containsKey(code);<br \/>\n    }<br \/>\n}<\/p>\n<h5>36.3.2 \u5ba2\u6237\u7aef\u5904\u7406<\/h5>\n<p>typescript<\/p>\n<p>\/\/ \u5ba2\u6237\u7aef\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u5904\u7406<br \/>\nclass CustomStatusCodeHandler {<\/p>\n<p>    private static readonly CUSTOM_CODES &#061; {<br \/>\n        460: {<br \/>\n            name: &#039;OUT_OF_STOCK&#039;,<br \/>\n            description: &#039;\u5546\u54c1\u7f3a\u8d27&#039;,<br \/>\n            retryable: true,<br \/>\n            defaultRetryAfter: 3600,<br \/>\n            handler: &#039;handleOutOfStock&#039;<br \/>\n        },<br \/>\n        461: {<br \/>\n            name: &#039;INSUFFICIENT_INVENTORY&#039;,<br \/>\n            description: &#039;\u5e93\u5b58\u4e0d\u8db3&#039;,<br \/>\n            retryable: false,<br \/>\n            handler: &#039;handleInsufficientInventory&#039;<br \/>\n        },<br \/>\n        520: {<br \/>\n            name: &#039;CIRCUIT_BREAKER_OPEN&#039;,<br \/>\n            description: &#039;\u670d\u52a1\u7194\u65ad&#039;,<br \/>\n            retryable: true,<br \/>\n            fallback: true,<br \/>\n            handler: &#039;handleCircuitBreaker&#039;<br \/>\n        }<br \/>\n    };<\/p>\n<p>    static async handleResponse(response: Response): Promise&lt;any&gt; {<br \/>\n        const status &#061; response.status;<\/p>\n<p>        \/\/ \u68c0\u67e5\u662f\u5426\u81ea\u5b9a\u4e49\u72b6\u6001\u7801<br \/>\n        if (this.isCustomStatusCode(status)) {<br \/>\n            return await this.handleCustomCode(status, response);<br \/>\n        }<\/p>\n<p>        \/\/ \u6807\u51c6\u72b6\u6001\u7801\u5904\u7406<br \/>\n        return await this.handleStandardCode(status, response);<br \/>\n    }<\/p>\n<p>    private static isCustomStatusCode(status: number): boolean {<br \/>\n        return status in this.CUSTOM_CODES;<br \/>\n    }<\/p>\n<p>    private static async handleCustomCode(<br \/>\n        status: number,<br \/>\n        response: Response<br \/>\n    ): Promise&lt;any&gt; {<br \/>\n        const codeInfo &#061; this.CUSTOM_CODES[status];<br \/>\n        const data &#061; await response.json().catch(() &#061;&gt; ({}));<\/p>\n<p>        \/\/ \u8c03\u7528\u5bf9\u5e94\u7684\u5904\u7406\u5668<br \/>\n        const handler &#061; this[codeInfo.handler];<br \/>\n        if (typeof handler &#061;&#061;&#061; &#039;function&#039;) {<br \/>\n            return handler.call(this, response, data);<br \/>\n        }<\/p>\n<p>        \/\/ \u9ed8\u8ba4\u5904\u7406<br \/>\n        throw new CustomHttpError(<br \/>\n            status,<br \/>\n            codeInfo.name,<br \/>\n            data.message || codeInfo.description,<br \/>\n            data<br \/>\n        );<br \/>\n    }<\/p>\n<p>    private static async handleOutOfStock(<br \/>\n        response: Response,<br \/>\n        data: any<br \/>\n    ): Promise&lt;any&gt; {<br \/>\n        const retryAfter &#061; response.headers.get(&#039;Retry-After&#039;) ||<br \/>\n                          this.CUSTOM_CODES[460].defaultRetryAfter;<\/p>\n<p>        \/\/ \u663e\u793a\u7528\u6237\u53cb\u597d\u7684\u6d88\u606f<br \/>\n        const message &#061; data.message || &#039;\u5546\u54c1\u6682\u65f6\u7f3a\u8d27&#039;;<br \/>\n        const estimatedDate &#061; data.estimated_restock_date;<\/p>\n<p>        \/\/ \u63d0\u4f9b\u91cd\u8bd5\u673a\u5236<br \/>\n        return {<br \/>\n            success: false,<br \/>\n            code: 460,<br \/>\n            message,<br \/>\n            retryAfter: parseInt(retryAfter, 10),<br \/>\n            estimatedRestock: estimatedDate,<br \/>\n            canBackorder: data.backorder_available || false,<br \/>\n            alternatives: data.alternative_products || [],<\/p>\n<p>            \/\/ \u91cd\u8bd5\u51fd\u6570<br \/>\n            retry: async () &#061;&gt; {<br \/>\n                await new Promise(resolve &#061;&gt;<br \/>\n                    setTimeout(resolve, retryAfter * 1000));<br \/>\n                return fetch(response.url, {<br \/>\n                    method: &#039;GET&#039;,<br \/>\n                    headers: response.headers<br \/>\n                });<br \/>\n            }<br \/>\n        };<br \/>\n    }<\/p>\n<p>    private static async handleCircuitBreaker(<br \/>\n        response: Response,<br \/>\n        data: any<br \/>\n    ): Promise&lt;any&gt; {<br \/>\n        const retryAfter &#061; response.headers.get(&#039;Retry-After&#039;) || 30;<br \/>\n        const service &#061; data.details?.service || &#039;unknown&#039;;<\/p>\n<p>        \/\/ \u8bb0\u5f55\u7194\u65ad\u4e8b\u4ef6<br \/>\n        console.warn(&#096;Circuit breaker open for ${service}&#096;, data);<\/p>\n<p>        \/\/ \u68c0\u67e5\u662f\u5426\u6709\u964d\u7ea7\u670d\u52a1<br \/>\n        if (data.alternative_endpoints?.length &gt; 0) {<br \/>\n            return await this.fallbackToAlternative(<br \/>\n                data.alternative_endpoints,<br \/>\n                response<br \/>\n            );<br \/>\n        }<\/p>\n<p>        return {<br \/>\n            success: false,<br \/>\n            code: 520,<br \/>\n            message: &#039;\u670d\u52a1\u6682\u65f6\u4e0d\u53ef\u7528&#xff0c;\u8bf7\u7a0d\u540e\u91cd\u8bd5&#039;,<br \/>\n            retryAfter: parseInt(retryAfter, 10),<br \/>\n            service,<br \/>\n            failureRate: data.details?.failure_rate,<\/p>\n<p>            retry: async () &#061;&gt; {<br \/>\n                await new Promise(resolve &#061;&gt;<br \/>\n                    setTimeout(resolve, retryAfter * 1000));<br \/>\n                return fetch(response.url, {<br \/>\n                    method: &#039;GET&#039;,<br \/>\n                    headers: response.headers<br \/>\n                });<br \/>\n            }<br \/>\n        };<br \/>\n    }<\/p>\n<p>    private static async fallbackToAlternative(<br \/>\n        endpoints: string[],<br \/>\n        originalResponse: Response<br \/>\n    ): Promise&lt;any&gt; {<br \/>\n        for (const endpoint of endpoints) {<br \/>\n            try {<br \/>\n                const response &#061; await fetch(endpoint, {<br \/>\n                    method: &#039;GET&#039;,<br \/>\n                    headers: originalResponse.headers<br \/>\n                });<\/p>\n<p>                if (response.ok) {<br \/>\n                    console.log(&#096;Fallback to ${endpoint} succeeded&#096;);<br \/>\n                    return await response.json();<br \/>\n                }<br \/>\n            } catch (error) {<br \/>\n                console.warn(&#096;Fallback to ${endpoint} failed:&#096;, error);<br \/>\n                continue;<br \/>\n            }<br \/>\n        }<\/p>\n<p>        throw new Error(&#039;All fallback endpoints failed&#039;);<br \/>\n    }<br \/>\n}<\/p>\n<p>\/\/ \u4f7f\u7528\u793a\u4f8b<br \/>\nasync function purchaseProduct(productId: string) {<br \/>\n    try {<br \/>\n        const response &#061; await fetch(&#096;\/api\/products\/${productId}\/purchase&#096;, {<br \/>\n            method: &#039;POST&#039;,<br \/>\n            headers: {<br \/>\n                &#039;Content-Type&#039;: &#039;application\/json&#039;<br \/>\n            }<br \/>\n        });<\/p>\n<p>        return await CustomStatusCodeHandler.handleResponse(response);<\/p>\n<p>    } catch (error) {<br \/>\n        if (error instanceof CustomHttpError) {<br \/>\n            \/\/ \u5904\u7406\u81ea\u5b9a\u4e49\u9519\u8bef<br \/>\n            switch (error.code) {<br \/>\n                case 460:<br \/>\n                    \/\/ \u663e\u793a\u7f3a\u8d27\u754c\u9762<br \/>\n                    showOutOfStockUI(error.details);<br \/>\n                    break;<br \/>\n                case 520:<br \/>\n                    \/\/ \u663e\u793a\u670d\u52a1\u964d\u7ea7\u63d0\u793a<br \/>\n                    showServiceDegradedUI(error.details);<br \/>\n                    break;<br \/>\n            }<br \/>\n        }<br \/>\n        throw error;<br \/>\n    }<br \/>\n}<\/p>\n<h4>36.4 \u6269\u5c55\u72b6\u6001\u7801\u7684\u6807\u51c6\u5316<\/h4>\n<h5>36.4.1 IANA\u6ce8\u518c\u6d41\u7a0b<\/h5>\n<p>markdown<\/p>\n<p># \u81ea\u5b9a\u4e49HTTP\u72b6\u6001\u7801RFC\u63d0\u6848\u6a21\u677f<\/p>\n<p>Title: An HTTP Status Code for Indicating Temporary Out of Stock<br \/>\nStatus: Proposed Standard<br \/>\nAuthor: A. Merchant, B. Developer<br \/>\nDate: October 2023<\/p>\n<p>1. Introduction<br \/>\n   1.1. Motivation and Use Cases<br \/>\n   1.2. Requirements<\/p>\n<p>2. The 460 Out of Stock Status Code<br \/>\n   2.1. Semantics<br \/>\n   2.2. Example Usage<br \/>\n   2.3. Client Handling Requirements<\/p>\n<p>3. Security Considerations<br \/>\n   3.1. Information Disclosure<br \/>\n   3.2. Denial of Service<\/p>\n<p>4. IANA Considerations<br \/>\n   4.1. HTTP Status Code Registry Update<\/p>\n<p>5. References<br \/>\n   5.1. Normative References<br \/>\n   5.2. Informative References<\/p>\n<p>Appendix A. Implementation Examples<br \/>\nAppendix B. Change History<\/p>\n<h5>36.4.2 \u884c\u4e1a\u6807\u51c6\u7ec4\u7ec7<\/h5>\n<p>yaml<\/p>\n<p># OpenAPI\u6269\u5c55\u72b6\u6001\u7801\u5b9a\u4e49<br \/>\nopenapi: 3.1.0<br \/>\ninfo:<br \/>\n  title: E-Commerce API<br \/>\n  version: 1.0.0<br \/>\n  description: API with custom status codes<\/p>\n<p>paths:<br \/>\n  \/products\/{id}\/purchase:<br \/>\n    post:<br \/>\n      summary: Purchase a product<br \/>\n      responses:<br \/>\n        &#039;200&#039;:<br \/>\n          description: Purchase successful<br \/>\n        &#039;460&#039;:<br \/>\n          $ref: &#039;#\/components\/responses\/OutOfStock&#039;<br \/>\n        &#039;461&#039;:<br \/>\n          $ref: &#039;#\/components\/responses\/InsufficientInventory&#039;<br \/>\n        &#039;520&#039;:<br \/>\n          $ref: &#039;#\/components\/responses\/CircuitBreakerOpen&#039;<\/p>\n<p>components:<br \/>\n  responses:<br \/>\n    OutOfStock:<br \/>\n      description: Product is temporarily out of stock<br \/>\n      headers:<br \/>\n        Retry-After:<br \/>\n          schema:<br \/>\n            type: integer<br \/>\n          description: Seconds to wait before retrying<br \/>\n      content:<br \/>\n        application\/json:<br \/>\n          schema:<br \/>\n            $ref: &#039;#\/components\/schemas\/OutOfStockError&#039;<\/p>\n<p>    CircuitBreakerOpen:<br \/>\n      description: Service temporarily unavailable due to circuit breaker<br \/>\n      headers:<br \/>\n        Retry-After:<br \/>\n          schema:<br \/>\n            type: integer<br \/>\n        X-Circuit-Breaker-State:<br \/>\n          schema:<br \/>\n            type: string<br \/>\n            enum: [OPEN, HALF_OPEN, CLOSED]<br \/>\n      content:<br \/>\n        application\/json:<br \/>\n          schema:<br \/>\n            $ref: &#039;#\/components\/schemas\/CircuitBreakerError&#039;<\/p>\n<p>  schemas:<br \/>\n    OutOfStockError:<br \/>\n      type: object<br \/>\n      required:<br \/>\n        &#8211; code<br \/>\n        &#8211; message<br \/>\n        &#8211; product_id<br \/>\n      properties:<br \/>\n        code:<br \/>\n          type: integer<br \/>\n          example: 460<br \/>\n        message:<br \/>\n          type: string<br \/>\n        product_id:<br \/>\n          type: string<br \/>\n        estimated_restock_date:<br \/>\n          type: string<br \/>\n          format: date-time<br \/>\n        backorder_available:<br \/>\n          type: boolean<br \/>\n        alternative_products:<br \/>\n          type: array<br \/>\n          items:<br \/>\n            type: string<\/p>\n<h4>36.5 \u76d1\u63a7\u4e0e\u5206\u6790<\/h4>\n<h5>36.5.1 \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u7684\u76d1\u63a7<\/h5>\n<p>python<\/p>\n<p># \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u76d1\u63a7\u7cfb\u7edf<br \/>\nfrom dataclasses import dataclass<br \/>\nfrom datetime import datetime<br \/>\nfrom typing import Dict, List, Optional<br \/>\nfrom enum import Enum<\/p>\n<p>class StatusCodeCategory(Enum):<br \/>\n    STANDARD_1XX &#061; &#034;standard_1xx&#034;<br \/>\n    STANDARD_2XX &#061; &#034;standard_2xx&#034;<br \/>\n    STANDARD_3XX &#061; &#034;standard_3xx&#034;<br \/>\n    STANDARD_4XX &#061; &#034;standard_4xx&#034;<br \/>\n    STANDARD_5XX &#061; &#034;standard_5xx&#034;<br \/>\n    CUSTOM_BUSINESS &#061; &#034;custom_business&#034;<br \/>\n    CUSTOM_SYSTEM &#061; &#034;custom_system&#034;<br \/>\n    CUSTOM_EXPERIMENTAL &#061; &#034;custom_experimental&#034;<\/p>\n<p>&#064;dataclass<br \/>\nclass StatusCodeDefinition:<br \/>\n    code: int<br \/>\n    name: str<br \/>\n    category: StatusCodeCategory<br \/>\n    description: str<br \/>\n    introduced_at: datetime<br \/>\n    deprecated_at: Optional[datetime] &#061; None<br \/>\n    removed_at: Optional[datetime] &#061; None<\/p>\n<p>    # \u4e1a\u52a1\u6307\u6807<br \/>\n    expected_rate: Optional[float] &#061; None  # \u9884\u671f\u51fa\u73b0\u9891\u7387<br \/>\n    alert_threshold: Optional[float] &#061; None  # \u544a\u8b66\u9608\u503c<br \/>\n    sla_impact: bool &#061; False  # \u662f\u5426\u5f71\u54cdSLA<\/p>\n<p>class StatusCodeMonitor:<br \/>\n    def __init__(self):<br \/>\n        self.definitions: Dict[int, StatusCodeDefinition] &#061; {}<br \/>\n        self.metrics &#061; StatusCodeMetrics()<\/p>\n<p>    def register_code(self, definition: StatusCodeDefinition):<br \/>\n        &#034;&#034;&#034;\u6ce8\u518c\u81ea\u5b9a\u4e49\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        if definition.code in self.definitions:<br \/>\n            raise ValueError(f&#034;Status code {definition.code} already registered&#034;)<\/p>\n<p>        # \u9a8c\u8bc1\u72b6\u6001\u7801\u8303\u56f4<br \/>\n        if not self._validate_code_range(definition.code, definition.category):<br \/>\n            raise ValueError(f&#034;Invalid code range for category {definition.category}&#034;)<\/p>\n<p>        self.definitions[definition.code] &#061; definition<br \/>\n        self.metrics.initialize_code(definition.code)<\/p>\n<p>    def record_request(self,<br \/>\n                      status_code: int,<br \/>\n                      endpoint: str,<br \/>\n                      response_time: float,<br \/>\n                      timestamp: datetime):<br \/>\n        &#034;&#034;&#034;\u8bb0\u5f55\u8bf7\u6c42\u6307\u6807&#034;&#034;&#034;<br \/>\n        # \u6807\u51c6\u5316\u72b6\u6001\u7801\u5206\u7c7b<br \/>\n        category &#061; self._categorize_code(status_code)<\/p>\n<p>        # \u8bb0\u5f55\u57fa\u672c\u6307\u6807<br \/>\n        self.metrics.record_request(<br \/>\n            status_code&#061;status_code,<br \/>\n            category&#061;category,<br \/>\n            endpoint&#061;endpoint,<br \/>\n            response_time&#061;response_time,<br \/>\n            timestamp&#061;timestamp<br \/>\n        )<\/p>\n<p>        # \u68c0\u67e5\u662f\u5426\u9700\u8981\u544a\u8b66<br \/>\n        self._check_alert_conditions(status_code, endpoint)<\/p>\n<p>    def _categorize_code(self, code: int) -&gt; StatusCodeCategory:<br \/>\n        &#034;&#034;&#034;\u5c06\u72b6\u6001\u7801\u5206\u7c7b&#034;&#034;&#034;<br \/>\n        if code in self.definitions:<br \/>\n            return self.definitions[code].category<\/p>\n<p>        # \u6807\u51c6\u72b6\u6001\u7801\u5206\u7c7b<br \/>\n        if 100 &lt;&#061; code &lt;&#061; 199:<br \/>\n            return StatusCodeCategory.STANDARD_1XX<br \/>\n        elif 200 &lt;&#061; code &lt;&#061; 299:<br \/>\n            return StatusCodeCategory.STANDARD_2XX<br \/>\n        elif 300 &lt;&#061; code &lt;&#061; 399:<br \/>\n            return StatusCodeCategory.STANDARD_3XX<br \/>\n        elif 400 &lt;&#061; code &lt;&#061; 499:<br \/>\n            return StatusCodeCategory.STANDARD_4XX<br \/>\n        elif 500 &lt;&#061; code &lt;&#061; 599:<br \/>\n            return StatusCodeCategory.STANDARD_5XX<br \/>\n        else:<br \/>\n            return StatusCodeCategory.CUSTOM_EXPERIMENTAL<\/p>\n<p>    def _check_alert_conditions(self, code: int, endpoint: str):<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u544a\u8b66\u6761\u4ef6&#034;&#034;&#034;<br \/>\n        if code not in self.definitions:<br \/>\n            return<\/p>\n<p>        definition &#061; self.definitions[code]<\/p>\n<p>        # \u68c0\u67e5\u662f\u5426\u8d85\u8fc7\u9884\u671f\u9891\u7387<br \/>\n        current_rate &#061; self.metrics.get_rate_last_hour(code, endpoint)<br \/>\n        if (definition.expected_rate is not None and<br \/>\n            current_rate &gt; definition.expected_rate * 1.5):  # \u8d85\u8fc750%<\/p>\n<p>            self._trigger_alert(<br \/>\n                f&#034;High frequency of {code} {definition.name} &#034;<br \/>\n                f&#034;on {endpoint}: {current_rate:.2%}&#034;<br \/>\n            )<\/p>\n<p>        # \u68c0\u67e5\u662f\u5426\u5f71\u54cdSLA<br \/>\n        if definition.sla_impact:<br \/>\n            sla_violations &#061; self.metrics.get_sla_violations_last_hour(endpoint)<br \/>\n            if sla_violations &gt; 10:  # \u9608\u503c<br \/>\n                self._trigger_alert(<br \/>\n                    f&#034;SLA impacted by {code} on {endpoint}: &#034;<br \/>\n                    f&#034;{sla_violations} violations&#034;<br \/>\n                )<\/p>\n<p>    def generate_report(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u72b6\u6001\u7801\u5206\u6790\u62a5\u544a&#034;&#034;&#034;<br \/>\n        report &#061; {<br \/>\n            &#034;timestamp&#034;: datetime.now(),<br \/>\n            &#034;summary&#034;: {},<br \/>\n            &#034;custom_codes&#034;: [],<br \/>\n            &#034;anomalies&#034;: [],<br \/>\n            &#034;recommendations&#034;: []<br \/>\n        }<\/p>\n<p>        # \u7edf\u8ba1\u81ea\u5b9a\u4e49\u72b6\u6001\u7801<br \/>\n        for code, definition in self.definitions.items():<br \/>\n            stats &#061; self.metrics.get_code_stats(code)<br \/>\n            code_report &#061; {<br \/>\n                &#034;code&#034;: code,<br \/>\n                &#034;name&#034;: definition.name,<br \/>\n                &#034;category&#034;: definition.category.value,<br \/>\n                &#034;total_requests&#034;: stats[&#034;total&#034;],<br \/>\n                &#034;rate_last_hour&#034;: stats[&#034;rate_last_hour&#034;],<br \/>\n                &#034;avg_response_time&#034;: stats[&#034;avg_response_time&#034;],<br \/>\n                &#034;endpoints&#034;: stats[&#034;endpoints&#034;]<br \/>\n            }<\/p>\n<p>            report[&#034;custom_codes&#034;].append(code_report)<\/p>\n<p>            # \u8bc6\u522b\u5f02\u5e38\u6a21\u5f0f<br \/>\n            if self._is_anomalous(code, stats):<br \/>\n                report[&#034;anomalies&#034;].append({<br \/>\n                    &#034;code&#034;: code,<br \/>\n                    &#034;issue&#034;: &#034;Unusual pattern detected&#034;,<br \/>\n                    &#034;metrics&#034;: stats<br \/>\n                })<\/p>\n<p>        return report<\/p>\n<p>    def _is_anomalous(self, code: int, stats: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u5f02\u5e38\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        # \u57fa\u4e8e\u5386\u53f2\u6570\u636e\u68c0\u6d4b\u5f02\u5e38<br \/>\n        # \u8fd9\u91cc\u53ef\u4ee5\u4f7f\u7528\u66f4\u590d\u6742\u7684\u5f02\u5e38\u68c0\u6d4b\u7b97\u6cd5<br \/>\n        historical_avg &#061; self.metrics.get_historical_average(code)<\/p>\n<p>        if historical_avg is None:<br \/>\n            return False<\/p>\n<p>        current_rate &#061; stats[&#034;rate_last_hour&#034;]<br \/>\n        if abs(current_rate &#8211; historical_avg) \/ historical_avg &gt; 0.3:  # 30%\u53d8\u5316<br \/>\n            return True<\/p>\n<p>        return False<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nmonitor &#061; StatusCodeMonitor()<\/p>\n<p># \u6ce8\u518c\u81ea\u5b9a\u4e49\u72b6\u6001\u7801<br \/>\nmonitor.register_code(StatusCodeDefinition(<br \/>\n    code&#061;460,<br \/>\n    name&#061;&#034;OUT_OF_STOCK&#034;,<br \/>\n    category&#061;StatusCodeCategory.CUSTOM_BUSINESS,<br \/>\n    description&#061;&#034;Product temporarily out of stock&#034;,<br \/>\n    introduced_at&#061;datetime(2023, 1, 1),<br \/>\n    expected_rate&#061;0.01,  # \u9884\u671f1%<br \/>\n    alert_threshold&#061;0.05,  # \u8d85\u8fc75%\u544a\u8b66<br \/>\n    sla_impact&#061;True<br \/>\n))<\/p>\n<p># \u76d1\u63a7\u8bf7\u6c42<br \/>\nmonitor.record_request(<br \/>\n    status_code&#061;460,<br \/>\n    endpoint&#061;&#034;\/api\/products\/123\/purchase&#034;,<br \/>\n    response_time&#061;150.5,<br \/>\n    timestamp&#061;datetime.now()<br \/>\n)<\/p>\n<p># \u751f\u6210\u62a5\u544a<br \/>\nreport &#061; monitor.generate_report()<\/p>\n<h5>36.5.2 \u53ef\u89c6\u5316\u4eea\u8868\u677f<\/h5>\n<p>javascript<\/p>\n<p>\/\/ \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u76d1\u63a7\u4eea\u8868\u677f<br \/>\nimport React, { useState, useEffect } from &#039;react&#039;;<br \/>\nimport {<br \/>\n  LineChart, BarChart, PieChart,<br \/>\n  Line, Bar, Pie, Cell,<br \/>\n  XAxis, YAxis, CartesianGrid,<br \/>\n  Tooltip, Legend, ResponsiveContainer<br \/>\n} from &#039;recharts&#039;;<\/p>\n<p>const StatusCodeDashboard &#061; () &#061;&gt; {<br \/>\n  const [timeRange, setTimeRange] &#061; useState(&#039;24h&#039;);<br \/>\n  const [data, setData] &#061; useState({});<br \/>\n  const [alerts, setAlerts] &#061; useState([]);<\/p>\n<p>  useEffect(() &#061;&gt; {<br \/>\n    fetchData();<br \/>\n    const interval &#061; setInterval(fetchData, 30000); \/\/ 30\u79d2\u66f4\u65b0<br \/>\n    return () &#061;&gt; clearInterval(interval);<br \/>\n  }, [timeRange]);<\/p>\n<p>  const fetchData &#061; async () &#061;&gt; {<br \/>\n    const response &#061; await fetch(&#096;\/api\/metrics\/status-codes?range&#061;${timeRange}&#096;);<br \/>\n    const result &#061; await response.json();<br \/>\n    setData(result);<\/p>\n<p>    \/\/ \u68c0\u67e5\u544a\u8b66<br \/>\n    if (result.alerts &amp;&amp; result.alerts.length &gt; 0) {<br \/>\n      setAlerts(result.alerts);<br \/>\n    }<br \/>\n  };<\/p>\n<p>  \/\/ \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u989c\u8272\u6620\u5c04<br \/>\n  const CUSTOM_CODE_COLORS &#061; {<br \/>\n    460: &#039;#ff6b6b&#039;, \/\/ \u7ea2\u8272 &#8211; \u7f3a\u8d27<br \/>\n    461: &#039;#ffa726&#039;, \/\/ \u6a59\u8272 &#8211; \u5e93\u5b58\u4e0d\u8db3<br \/>\n    520: &#039;#5c6bc0&#039;, \/\/ \u84dd\u8272 &#8211; \u7194\u65ad\u5668<br \/>\n    521: &#039;#26a69a&#039;, \/\/ \u9752\u8272 &#8211; \u670d\u52a1\u964d\u7ea7<br \/>\n    210: &#039;#66bb6a&#039;, \/\/ \u7eff\u8272 &#8211; \u5904\u7406\u4e2d<br \/>\n    211: &#039;#42a5f5&#039;, \/\/ \u6d45\u84dd &#8211; \u652f\u4ed8\u4e2d<br \/>\n  };<\/p>\n<p>  const getColorForCode &#061; (code) &#061;&gt; {<br \/>\n    return CUSTOM_CODE_COLORS[code] || &#039;#8884d8&#039;; \/\/ \u9ed8\u8ba4\u989c\u8272<br \/>\n  };<\/p>\n<p>  return (<br \/>\n    &lt;div className&#061;&#034;status-code-dashboard&#034;&gt;<br \/>\n      {\/* \u544a\u8b66\u9762\u677f *\/}<br \/>\n      {alerts.length &gt; 0 &amp;&amp; (<br \/>\n        &lt;div className&#061;&#034;alerts-panel&#034;&gt;<br \/>\n          &lt;h3&gt;\u26a0\ufe0f Status Code Alerts&lt;\/h3&gt;<br \/>\n          {alerts.map((alert, index) &#061;&gt; (<br \/>\n            &lt;div key&#061;{index} className&#061;&#034;alert-item&#034;&gt;<br \/>\n              &lt;strong&gt;{alert.code}: {alert.name}&lt;\/strong&gt;<br \/>\n              &lt;p&gt;{alert.message}&lt;\/p&gt;<br \/>\n              &lt;small&gt;{new Date(alert.timestamp).toLocaleString()}&lt;\/small&gt;<br \/>\n            &lt;\/div&gt;<br \/>\n          ))}<br \/>\n        &lt;\/div&gt;<br \/>\n      )}<\/p>\n<p>      {\/* \u72b6\u6001\u7801\u5206\u5e03 *\/}<br \/>\n      &lt;div className&#061;&#034;chart-container&#034;&gt;<br \/>\n        &lt;h3&gt;Status Code Distribution&lt;\/h3&gt;<br \/>\n        &lt;ResponsiveContainer width&#061;&#034;100%&#034; height&#061;{300}&gt;<br \/>\n          &lt;BarChart data&#061;{data.distribution}&gt;<br \/>\n            &lt;CartesianGrid strokeDasharray&#061;&#034;3 3&#034; \/&gt;<br \/>\n            &lt;XAxis dataKey&#061;&#034;code&#034; \/&gt;<br \/>\n            &lt;YAxis \/&gt;<br \/>\n            &lt;Tooltip<br \/>\n              formatter&#061;{(value, name, props) &#061;&gt; [<br \/>\n                value,<br \/>\n                &#096;${props.payload.name} (${props.payload.code})&#096;<br \/>\n              ]}<br \/>\n            \/&gt;<br \/>\n            &lt;Legend \/&gt;<br \/>\n            &lt;Bar dataKey&#061;&#034;count&#034; name&#061;&#034;Requests&#034;&gt;<br \/>\n              {data.distribution?.map((entry, index) &#061;&gt; (<br \/>\n                &lt;Cell<br \/>\n                  key&#061;{&#096;cell-${index}&#096;}<br \/>\n                  fill&#061;{getColorForCode(entry.code)}<br \/>\n                \/&gt;<br \/>\n              ))}<br \/>\n            &lt;\/Bar&gt;<br \/>\n          &lt;\/BarChart&gt;<br \/>\n        &lt;\/ResponsiveContainer&gt;<br \/>\n      &lt;\/div&gt;<\/p>\n<p>      {\/* \u8d8b\u52bf\u5206\u6790 *\/}<br \/>\n      &lt;div className&#061;&#034;chart-container&#034;&gt;<br \/>\n        &lt;h3&gt;Custom Status Code Trends&lt;\/h3&gt;<br \/>\n        &lt;ResponsiveContainer width&#061;&#034;100%&#034; height&#061;{300}&gt;<br \/>\n          &lt;LineChart data&#061;{data.trends}&gt;<br \/>\n            &lt;CartesianGrid strokeDasharray&#061;&#034;3 3&#034; \/&gt;<br \/>\n            &lt;XAxis dataKey&#061;&#034;timestamp&#034; \/&gt;<br \/>\n            &lt;YAxis \/&gt;<br \/>\n            &lt;Tooltip \/&gt;<br \/>\n            &lt;Legend \/&gt;<br \/>\n            {Object.keys(CUSTOM_CODE_COLORS).map(code &#061;&gt; (<br \/>\n              &lt;Line<br \/>\n                key&#061;{code}<br \/>\n                type&#061;&#034;monotone&#034;<br \/>\n                dataKey&#061;{&#096;code_${code}&#096;}<br \/>\n                name&#061;{&#096;${code}&#096;}<br \/>\n                stroke&#061;{CUSTOM_CODE_COLORS[code]}<br \/>\n                strokeWidth&#061;{2}<br \/>\n                dot&#061;{false}<br \/>\n              \/&gt;<br \/>\n            ))}<br \/>\n          &lt;\/LineChart&gt;<br \/>\n        &lt;\/ResponsiveContainer&gt;<br \/>\n      &lt;\/div&gt;<\/p>\n<p>      {\/* \u7aef\u70b9\u5206\u6790 *\/}<br \/>\n      &lt;div className&#061;&#034;endpoint-analysis&#034;&gt;<br \/>\n        &lt;h3&gt;Endpoint-Specific Status Codes&lt;\/h3&gt;<br \/>\n        &lt;table&gt;<br \/>\n          &lt;thead&gt;<br \/>\n            &lt;tr&gt;<br \/>\n              &lt;th&gt;Endpoint&lt;\/th&gt;<br \/>\n              &lt;th&gt;Total Requests&lt;\/th&gt;<br \/>\n              &lt;th&gt;Success Rate&lt;\/th&gt;<br \/>\n              &lt;th&gt;Custom Codes&lt;\/th&gt;<br \/>\n              &lt;th&gt;Avg Response Time&lt;\/th&gt;<br \/>\n            &lt;\/tr&gt;<br \/>\n          &lt;\/thead&gt;<br \/>\n          &lt;tbody&gt;<br \/>\n            {data.endpoints?.map(endpoint &#061;&gt; (<br \/>\n              &lt;tr key&#061;{endpoint.path}&gt;<br \/>\n                &lt;td&gt;{endpoint.path}&lt;\/td&gt;<br \/>\n                &lt;td&gt;{endpoint.total_requests}&lt;\/td&gt;<br \/>\n                &lt;td&gt;<br \/>\n                  &lt;div className&#061;&#034;success-rate-bar&#034;&gt;<br \/>\n                    &lt;div<br \/>\n                      className&#061;&#034;success-rate-fill&#034;<br \/>\n                      style&#061;{{ width: &#096;${endpoint.success_rate * 100}%&#096; }}<br \/>\n                    \/&gt;<br \/>\n                    &lt;span&gt;{(endpoint.success_rate * 100).toFixed(1)}%&lt;\/span&gt;<br \/>\n                  &lt;\/div&gt;<br \/>\n                &lt;\/td&gt;<br \/>\n                &lt;td&gt;<br \/>\n                  {endpoint.custom_codes?.map(code &#061;&gt; (<br \/>\n                    &lt;span<br \/>\n                      key&#061;{code.code}<br \/>\n                      className&#061;&#034;code-badge&#034;<br \/>\n                      style&#061;{{ backgroundColor: getColorForCode(code.code) }}<br \/>\n                    &gt;<br \/>\n                      {code.code}: {code.count}<br \/>\n                    &lt;\/span&gt;<br \/>\n                  ))}<br \/>\n                &lt;\/td&gt;<br \/>\n                &lt;td&gt;{endpoint.avg_response_time.toFixed(0)}ms&lt;\/td&gt;<br \/>\n              &lt;\/tr&gt;<br \/>\n            ))}<br \/>\n          &lt;\/tbody&gt;<br \/>\n        &lt;\/table&gt;<br \/>\n      &lt;\/div&gt;<br \/>\n    &lt;\/div&gt;<br \/>\n  );<br \/>\n};<\/p>\n<h4>36.6 \u6700\u4f73\u5b9e\u8df5\u4e0e\u5efa\u8bae<\/h4>\n<h5>36.6.1 \u4f7f\u7528\u6307\u5357<\/h5>\n<p>markdown<\/p>\n<p># \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u4f7f\u7528\u6307\u5357<\/p>\n<p>## \u4f55\u65f6\u4f7f\u7528\u81ea\u5b9a\u4e49\u72b6\u6001\u7801&#xff1f;<\/p>\n<p>### \u63a8\u8350\u4f7f\u7528\u573a\u666f&#xff1a;<br \/>\n1. **\u4e1a\u52a1\u7279\u5b9a\u72b6\u6001** &#8211; \u6807\u51c6\u72b6\u6001\u7801\u65e0\u6cd5\u51c6\u786e\u63cf\u8ff0\u7684\u4e1a\u52a1\u72b6\u6001<br \/>\n2. **\u5fae\u670d\u52a1\u901a\u4fe1** &#8211; \u670d\u52a1\u95f4\u9700\u8981\u4f20\u9012\u590d\u6742\u72b6\u6001\u4fe1\u606f<br \/>\n3. **\u5b9e\u65f6API** &#8211; WebSocket\u3001SSE\u7b49\u5b9e\u65f6\u901a\u4fe1\u573a\u666f<br \/>\n4. **API\u7248\u672c\u6f14\u8fdb** &#8211; \u5411\u540e\u517c\u5bb9\u7684API\u53d8\u66f4<\/p>\n<p>### \u907f\u514d\u4f7f\u7528\u573a\u666f&#xff1a;<br \/>\n1. **\u53ef\u91cd\u7528\u6807\u51c6\u72b6\u6001\u7801\u65f6** &#8211; \u4f18\u5148\u4f7f\u7528\u6807\u51c6\u72b6\u6001\u7801<br \/>\n2. **\u516c\u5f00API\u65e9\u671f\u7248\u672c** &#8211; \u907f\u514d\u8fc7\u65e9\u9501\u5b9a\u8bbe\u8ba1<br \/>\n3. **\u4e34\u65f6\u6027\u9700\u6c42** &#8211; \u4f7f\u7528\u6269\u5c55\u5934\u90e8\u4ee3\u66ff<\/p>\n<p>## \u8bbe\u8ba1\u539f\u5219<\/p>\n<p>### \u8bed\u4e49\u6e05\u6670<br \/>\n&#8211; \u6bcf\u4e2a\u72b6\u6001\u7801\u5fc5\u987b\u6709\u660e\u786e\u7684\u6587\u6863<br \/>\n&#8211; \u907f\u514d\u6a21\u7cca\u6216\u591a\u4e49\u7684\u8bed\u4e49<br \/>\n&#8211; \u63d0\u4f9b\u5904\u7406\u6307\u5357\u548c\u793a\u4f8b<\/p>\n<p>### \u8303\u56f4\u5408\u7406<br \/>\n&#8211; 4xx\u8303\u56f4&#xff1a;\u5ba2\u6237\u7aef\u9519\u8bef\u6216\u4e1a\u52a1\u9650\u5236<br \/>\n&#8211; 5xx\u8303\u56f4&#xff1a;\u670d\u52a1\u5668\u9519\u8bef\u6216\u7cfb\u7edf\u72b6\u6001<br \/>\n&#8211; \u907f\u514d\u4f7f\u7528\u672a\u5206\u914d\u4f46\u53ef\u80fd\u6807\u51c6\u5316\u7684\u4ee3\u7801<\/p>\n<p>### \u5411\u540e\u517c\u5bb9<br \/>\n&#8211; \u65b0\u589e\u72b6\u6001\u7801\u4e0d\u5e94\u7834\u574f\u73b0\u6709\u5ba2\u6237\u7aef<br \/>\n&#8211; \u63d0\u4f9b\u964d\u7ea7\u5904\u7406\u65b9\u6848<br \/>\n&#8211; \u8003\u8651\u7248\u672c\u8fc7\u6e21\u7b56\u7565<\/p>\n<p>## \u5b9e\u73b0\u5efa\u8bae<\/p>\n<p>### \u670d\u52a1\u5668\u7aef&#xff1a;<br \/>\n&#096;&#096;&#096;python<br \/>\n# 1. \u7edf\u4e00\u5b9a\u4e49\u7ba1\u7406<br \/>\nCUSTOM_STATUS_CODES &#061; {<br \/>\n    460: (&#034;Out of Stock&#034;, &#034;Product temporarily unavailable&#034;),<br \/>\n    461: (&#034;Insufficient Inventory&#034;, &#034;Requested quantity not available&#034;),<br \/>\n    # &#8230;<br \/>\n}<\/p>\n<p># 2. \u63d0\u4f9b\u8be6\u7ec6\u7684\u9519\u8bef\u54cd\u5e94<br \/>\n{<br \/>\n    &#034;error&#034;: {<br \/>\n        &#034;code&#034;: 460,<br \/>\n        &#034;message&#034;: &#034;Product XYZ is out of stock&#034;,<br \/>\n        &#034;details&#034;: {<br \/>\n            &#034;product_id&#034;: &#034;123&#034;,<br \/>\n            &#034;available_quantity&#034;: 0,<br \/>\n            &#034;estimated_restock&#034;: &#034;2023-12-01&#034;<br \/>\n        },<br \/>\n        &#034;documentation_url&#034;: &#034;https:\/\/api.example.com\/docs\/errors\/460&#034;,<br \/>\n        &#034;retry_after&#034;: 3600<br \/>\n    }<br \/>\n}<\/p>\n<p># 3. \u76d1\u63a7\u548c\u544a\u8b66<br \/>\n&#8211; \u8ddf\u8e2a\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u9891\u7387<br \/>\n&#8211; \u8bbe\u7f6e\u5408\u7406\u7684\u9608\u503c<br \/>\n&#8211; \u96c6\u6210\u5230\u73b0\u6709\u76d1\u63a7\u7cfb\u7edf<\/p>\n<h4>\u5ba2\u6237\u7aef&#xff1a;<\/h4>\n<p>javascript<\/p>\n<p>\/\/ 1. \u4f18\u96c5\u5904\u7406\u672a\u77e5\u72b6\u6001\u7801<br \/>\nfunction handleResponse(response) {<br \/>\n    if (response.status &gt;&#061; 400 &amp;&amp; response.status &lt;&#061; 599) {<br \/>\n        if (!isStandardStatusCode(response.status)) {<br \/>\n            \/\/ \u5904\u7406\u81ea\u5b9a\u4e49\u72b6\u6001\u7801<br \/>\n            return handleCustomStatusCode(response);<br \/>\n        }<br \/>\n    }<br \/>\n    \/\/ \u5904\u7406\u6807\u51c6\u72b6\u6001\u7801<br \/>\n}<\/p>\n<p>\/\/ 2. \u63d0\u4f9b\u7528\u6237\u53cb\u597d\u7684\u6d88\u606f<br \/>\nconst ERROR_MESSAGES &#061; {<br \/>\n    460: &#034;This item is currently out of stock. We expect more on {date}.&#034;,<br \/>\n    461: &#034;Only {quantity} items available. Please adjust your quantity.&#034;,<br \/>\n    \/\/ &#8230;<br \/>\n};<\/p>\n<p>\/\/ 3. \u5b9e\u73b0\u91cd\u8bd5\u903b\u8f91<br \/>\nasync function retryWithBackoff(requestFn, maxRetries &#061; 3) {<br \/>\n    for (let i &#061; 0; i &lt; maxRetries; i&#043;&#043;) {<br \/>\n        try {<br \/>\n            return await requestFn();<br \/>\n        } catch (error) {<br \/>\n            if (error.status &#061;&#061;&#061; 460 &amp;&amp; error.retry_after) {<br \/>\n                await sleep(error.retry_after * 1000);<br \/>\n                continue;<br \/>\n            }<br \/>\n            throw error;<br \/>\n        }<br \/>\n    }<br \/>\n}<\/p>\n<h3>\u7248\u672c\u7ba1\u7406<\/h3>\n<h4>\u751f\u547d\u5468\u671f\u9636\u6bb5&#xff1a;<\/h4>\n<li>\n<p>Experimental\u00a0(\u5b9e\u9a8c\u9636\u6bb5) &#8211; 420-429\u8303\u56f4<\/p>\n<\/li>\n<li>\n<p>Stable\u00a0(\u7a33\u5b9a\u9636\u6bb5) &#8211; 450-499, 520-599\u8303\u56f4<\/p>\n<\/li>\n<li>\n<p>Deprecated\u00a0(\u5e9f\u5f03\u9636\u6bb5) &#8211; \u6dfb\u52a0\u5f03\u7528\u8b66\u544a<\/p>\n<\/li>\n<li>\n<p>Removed\u00a0(\u79fb\u9664\u9636\u6bb5) &#8211; \u5b8c\u5168\u79fb\u9664\u652f\u6301<\/p>\n<\/li>\n<h4>\u53d8\u66f4\u7b56\u7565&#xff1a;<\/h4>\n<ul>\n<li>\n<p>\u65b0\u589e&#xff1a;\u901a\u8fc7API\u7248\u672c\u5f15\u5165<\/p>\n<\/li>\n<li>\n<p>\u4fee\u6539&#xff1a;\u4fdd\u6301\u8bed\u4e49\u4e0d\u53d8&#xff0c;\u53ea\u66f4\u65b0\u6587\u6863<\/p>\n<\/li>\n<li>\n<p>\u5f03\u7528&#xff1a;\u63d0\u524d\u901a\u77e5&#xff0c;\u63d0\u4f9b\u66ff\u4ee3\u65b9\u6848<\/p>\n<\/li>\n<li>\n<p>\u79fb\u9664&#xff1a;\u591a\u7248\u672c\u8fc7\u6e21\u540e\u79fb\u9664<\/p>\n<\/li>\n<\/ul>\n<p>text<\/p>\n<p>#### 36.6.2 \u5b89\u5168\u6027\u8003\u8651<br \/>\n&#096;&#096;&#096;python<br \/>\n# \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u7684\u5b89\u5168\u5ba1\u8ba1<br \/>\nfrom typing import Dict, List, Set<br \/>\nfrom dataclasses import dataclass<br \/>\nfrom datetime import datetime<\/p>\n<p>&#064;dataclass<br \/>\nclass SecurityAuditRule:<br \/>\n    &#034;&#034;&#034;\u5b89\u5168\u5ba1\u8ba1\u89c4\u5219&#034;&#034;&#034;<br \/>\n    rule_id: str<br \/>\n    description: str<br \/>\n    severity: str  # LOW, MEDIUM, HIGH, CRITICAL<br \/>\n    check_function: callable<\/p>\n<p>    def check(self, status_code: int, context: Dict) -&gt; bool:<br \/>\n        return self.check_function(status_code, context)<\/p>\n<p>class StatusCodeSecurityAuditor:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u5b89\u5168\u5ba1\u8ba1\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.rules: List[SecurityAuditRule] &#061; []<br \/>\n        self._initialize_rules()<\/p>\n<p>    def _initialize_rules(self):<br \/>\n        &#034;&#034;&#034;\u521d\u59cb\u5316\u5ba1\u8ba1\u89c4\u5219&#034;&#034;&#034;<br \/>\n        self.rules &#061; [<br \/>\n            SecurityAuditRule(<br \/>\n                rule_id&#061;&#034;INFO_LEAK_001&#034;,<br \/>\n                description&#061;&#034;Custom status code leaks sensitive information&#034;,<br \/>\n                severity&#061;&#034;HIGH&#034;,<br \/>\n                check_function&#061;self._check_information_leak<br \/>\n            ),<br \/>\n            SecurityAuditRule(<br \/>\n                rule_id&#061;&#034;ENUM_ATTACK_001&#034;,<br \/>\n                description&#061;&#034;Custom status code enables enumeration attacks&#034;,<br \/>\n                severity&#061;&#034;MEDIUM&#034;,<br \/>\n                check_function&#061;self._check_enumeration_risk<br \/>\n            ),<br \/>\n            SecurityAuditRule(<br \/>\n                rule_id&#061;&#034;DOS_VECTOR_001&#034;,<br \/>\n                description&#061;&#034;Custom status code creates DoS vector&#034;,<br \/>\n                severity&#061;&#034;CRITICAL&#034;,<br \/>\n                check_function&#061;self._check_dos_vector<br \/>\n            ),<br \/>\n            SecurityAuditRule(<br \/>\n                rule_id&#061;&#034;AUTH_BYPASS_001&#034;,<br \/>\n                description&#061;&#034;Custom status code could bypass authentication&#034;,<br \/>\n                severity&#061;&#034;CRITICAL&#034;,<br \/>\n                check_function&#061;self._check_auth_bypass<br \/>\n            )<br \/>\n        ]<\/p>\n<p>    def audit_status_code(self,<br \/>\n                         status_code: int,<br \/>\n                         definition: Dict,<br \/>\n                         usage_patterns: Dict) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u5ba1\u8ba1\u5355\u4e2a\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        findings &#061; []<br \/>\n        context &#061; {<br \/>\n            &#039;definition&#039;: definition,<br \/>\n            &#039;usage_patterns&#039;: usage_patterns<br \/>\n        }<\/p>\n<p>        for rule in self.rules:<br \/>\n            if rule.check(status_code, context):<br \/>\n                findings.append({<br \/>\n                    &#039;rule_id&#039;: rule.rule_id,<br \/>\n                    &#039;description&#039;: rule.description,<br \/>\n                    &#039;severity&#039;: rule.severity,<br \/>\n                    &#039;status_code&#039;: status_code,<br \/>\n                    &#039;timestamp&#039;: datetime.now()<br \/>\n                })<\/p>\n<p>        return findings<\/p>\n<p>    def _check_information_leak(self, status_code: int, context: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u4fe1\u606f\u6cc4\u9732\u98ce\u9669&#034;&#034;&#034;<br \/>\n        definition &#061; context[&#039;definition&#039;]<\/p>\n<p>        # \u68c0\u67e5\u662f\u5426\u66b4\u9732\u654f\u611f\u4fe1\u606f<br \/>\n        sensitive_patterns &#061; [<br \/>\n            &#039;password&#039;, &#039;secret&#039;, &#039;key&#039;, &#039;token&#039;,<br \/>\n            &#039;internal&#039;, &#039;admin&#039;, &#039;debug&#039;, &#039;stack&#039;<br \/>\n        ]<\/p>\n<p>        description &#061; definition.get(&#039;description&#039;, &#039;&#039;).lower()<br \/>\n        for pattern in sensitive_patterns:<br \/>\n            if pattern in description:<br \/>\n                return True<\/p>\n<p>        # \u68c0\u67e5\u54cd\u5e94\u5185\u5bb9<br \/>\n        example_response &#061; definition.get(&#039;example_response&#039;, &#039;&#039;)<br \/>\n        if any(pattern in str(example_response).lower()<br \/>\n               for pattern in sensitive_patterns):<br \/>\n            return True<\/p>\n<p>        return False<\/p>\n<p>    def _check_enumeration_risk(self, status_code: int, context: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u679a\u4e3e\u653b\u51fb\u98ce\u9669&#034;&#034;&#034;<br \/>\n        # \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u53ef\u80fd\u6cc4\u9732\u8d44\u6e90\u5b58\u5728\u6027<br \/>\n        if 400 &lt;&#061; status_code &lt;&#061; 499:<br \/>\n            # 4xx\u72b6\u6001\u7801\u53ef\u80fd\u7528\u4e8e\u63a2\u6d4b\u8d44\u6e90<br \/>\n            patterns &#061; context[&#039;usage_patterns&#039;]<\/p>\n<p>            # \u68c0\u67e5\u662f\u5426\u5b58\u5728\u4e0d\u540c\u7684\u54cd\u5e94\u6a21\u5f0f<br \/>\n            if patterns.get(&#039;varied_responses&#039;, False):<br \/>\n                # \u540c\u4e00\u8d44\u6e90\u4e0d\u540c\u72b6\u6001\u53ef\u80fd\u6cc4\u9732\u4fe1\u606f<br \/>\n                return True<\/p>\n<p>        return False<\/p>\n<p>    def _check_dos_vector(self, status_code: int, context: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5DoS\u653b\u51fb\u5411\u91cf&#034;&#034;&#034;<br \/>\n        definition &#061; context[&#039;definition&#039;]<\/p>\n<p>        # \u68c0\u67e5\u662f\u5426\u53ef\u80fd\u5bfc\u81f4\u8d44\u6e90\u8017\u5c3d<br \/>\n        if definition.get(&#039;expensive_operation&#039;, False):<br \/>\n            # \u72b6\u6001\u7801\u5173\u8054\u9ad8\u6210\u672c\u64cd\u4f5c<br \/>\n            return True<\/p>\n<p>        # \u68c0\u67e5\u662f\u5426\u53ef\u80fd\u89e6\u53d1\u5faa\u73af\u6216\u94fe\u5f0f\u53cd\u5e94<br \/>\n        if definition.get(&#039;triggers_cascading&#039;, False):<br \/>\n            # \u53ef\u80fd\u89e6\u53d1\u7ea7\u8054\u8bf7\u6c42<br \/>\n            return True<\/p>\n<p>        return False<\/p>\n<p>    def _check_auth_bypass(self, status_code: int, context: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u8ba4\u8bc1\u7ed5\u8fc7\u98ce\u9669&#034;&#034;&#034;<br \/>\n        definition &#061; context[&#039;definition&#039;]<\/p>\n<p>        # \u68c0\u67e5\u662f\u5426\u53ef\u80fd\u7ed5\u8fc7\u8ba4\u8bc1<br \/>\n        if definition.get(&#039;bypasses_auth&#039;, False):<br \/>\n            return True<\/p>\n<p>        # \u68c0\u67e5\u662f\u5426\u5728\u8ba4\u8bc1\u524d\u8fd4\u56de<br \/>\n        patterns &#061; context[&#039;usage_patterns&#039;]<br \/>\n        if patterns.get(&#039;pre_auth&#039;, False):<br \/>\n            # \u5728\u8ba4\u8bc1\u524d\u8fd4\u56de\u72b6\u6001\u7801\u53ef\u80fd\u6cc4\u9732\u4fe1\u606f<br \/>\n            return True<\/p>\n<p>        return False<\/p>\n<p>    def generate_security_report(self,<br \/>\n                                status_codes: Dict[int, Dict]) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u5b89\u5168\u5ba1\u8ba1\u62a5\u544a&#034;&#034;&#034;<br \/>\n        report &#061; {<br \/>\n            &#039;audit_date&#039;: datetime.now(),<br \/>\n            &#039;summary&#039;: {<br \/>\n                &#039;total_codes&#039;: len(status_codes),<br \/>\n                &#039;high_risk&#039;: 0,<br \/>\n                &#039;medium_risk&#039;: 0,<br \/>\n                &#039;low_risk&#039;: 0<br \/>\n            },<br \/>\n            &#039;findings&#039;: [],<br \/>\n            &#039;recommendations&#039;: []<br \/>\n        }<\/p>\n<p>        for code, definition in status_codes.items():<br \/>\n            findings &#061; self.audit_status_code(<br \/>\n                code,<br \/>\n                definition,<br \/>\n                self._get_usage_patterns(code)<br \/>\n            )<\/p>\n<p>            if findings:<br \/>\n                report[&#039;findings&#039;].extend(findings)<\/p>\n<p>                # \u66f4\u65b0\u7edf\u8ba1<br \/>\n                for finding in findings:<br \/>\n                    severity &#061; finding[&#039;severity&#039;]<br \/>\n                    if severity &#061;&#061; &#039;HIGH&#039; or severity &#061;&#061; &#039;CRITICAL&#039;:<br \/>\n                        report[&#039;summary&#039;][&#039;high_risk&#039;] &#043;&#061; 1<br \/>\n                    elif severity &#061;&#061; &#039;MEDIUM&#039;:<br \/>\n                        report[&#039;summary&#039;][&#039;medium_risk&#039;] &#043;&#061; 1<br \/>\n                    else:<br \/>\n                        report[&#039;summary&#039;][&#039;low_risk&#039;] &#043;&#061; 1<\/p>\n<p>        # \u751f\u6210\u5efa\u8bae<br \/>\n        report[&#039;recommendations&#039;] &#061; self._generate_recommendations(report)<\/p>\n<p>        return report<\/p>\n<p>    def _get_usage_patterns(self, status_code: int) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u72b6\u6001\u7801\u4f7f\u7528\u6a21\u5f0f&#xff08;\u6a21\u62df&#xff09;&#034;&#034;&#034;<br \/>\n        # \u5b9e\u9645\u5e94\u4ece\u76d1\u63a7\u6570\u636e\u83b7\u53d6<br \/>\n        return {<br \/>\n            &#039;request_count&#039;: 1000,<br \/>\n            &#039;error_rate&#039;: 0.05,<br \/>\n            &#039;varied_responses&#039;: False,<br \/>\n            &#039;pre_auth&#039;: False,<br \/>\n            &#039;sensitive_endpoints&#039;: []<br \/>\n        }<\/p>\n<p>    def _generate_recommendations(self, report: Dict) -&gt; List[str]:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u5b89\u5168\u5efa\u8bae&#034;&#034;&#034;<br \/>\n        recommendations &#061; []<\/p>\n<p>        high_risk &#061; report[&#039;summary&#039;][&#039;high_risk&#039;]<br \/>\n        if high_risk &gt; 0:<br \/>\n            recommendations.append(<br \/>\n                f&#034;\u53d1\u73b0{high_risk}\u4e2a\u9ad8\u98ce\u9669\u72b6\u6001\u7801&#xff0c;\u5efa\u8bae\u7acb\u5373\u4fee\u590d&#034;<br \/>\n            )<\/p>\n<p>        for finding in report[&#039;findings&#039;]:<br \/>\n            if finding[&#039;severity&#039;] &#061;&#061; &#039;CRITICAL&#039;:<br \/>\n                recommendations.append(<br \/>\n                    f&#034;\u72b6\u6001\u7801{finding[&#039;status_code&#039;]}\u5b58\u5728\u4e25\u91cd\u5b89\u5168\u98ce\u9669&#xff1a;&#034;<br \/>\n                    f&#034;{finding[&#039;description&#039;]}&#034;<br \/>\n                )<\/p>\n<p>        return recommendations<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nauditor &#061; StatusCodeSecurityAuditor()<\/p>\n<p># \u5ba1\u8ba1\u81ea\u5b9a\u4e49\u72b6\u6001\u7801<br \/>\ncustom_codes &#061; {<br \/>\n    460: {<br \/>\n        &#039;name&#039;: &#039;OUT_OF_STOCK&#039;,<br \/>\n        &#039;description&#039;: &#039;Product temporarily out of stock&#039;,<br \/>\n        &#039;example_response&#039;: {<br \/>\n            &#039;error&#039;: &#039;Product XYZ out of stock&#039;,<br \/>\n            &#039;estimated_restock&#039;: &#039;2023-12-01&#039;,<br \/>\n            &#039;internal_product_id&#039;: &#039;INT-12345&#039;  # \u53ef\u80fd\u6cc4\u9732\u5185\u90e8\u4fe1\u606f<br \/>\n        },<br \/>\n        &#039;expensive_operation&#039;: False,<br \/>\n        &#039;bypasses_auth&#039;: False<br \/>\n    },<br \/>\n    999: {  # \u793a\u4f8b\u4e2d\u7684\u4e0d\u5b89\u5168\u72b6\u6001\u7801<br \/>\n        &#039;name&#039;: &#039;DEBUG_INFO&#039;,<br \/>\n        &#039;description&#039;: &#039;Debug information including internal state&#039;,<br \/>\n        &#039;example_response&#039;: {<br \/>\n            &#039;debug&#039;: {<br \/>\n                &#039;database_queries&#039;: [&#8230;],<br \/>\n                &#039;internal_state&#039;: {&#8230;},<br \/>\n                &#039;secrets&#039;: &#039;REDACTED&#039;<br \/>\n            }<br \/>\n        },<br \/>\n        &#039;expensive_operation&#039;: True,<br \/>\n        &#039;bypasses_auth&#039;: True<br \/>\n    }<br \/>\n}<\/p>\n<p>report &#061; auditor.generate_security_report(custom_codes)<br \/>\nprint(f&#034;\u5b89\u5168\u5ba1\u8ba1\u7ed3\u679c&#xff1a;\u9ad8\u98ce\u9669{report[&#039;summary&#039;][&#039;high_risk&#039;]}\u4e2a&#034;)<br \/>\nfor finding in report[&#039;findings&#039;]:<br \/>\n    print(f&#034;  [{finding[&#039;severity&#039;]}] {finding[&#039;status_code&#039;]}: &#034;<br \/>\n          f&#034;{finding[&#039;description&#039;]}&#034;)<\/p>\n<h4>36.7 \u672a\u6765\u53d1\u5c55\u8d8b\u52bf<\/h4>\n<h5>36.7.1 \u884c\u4e1a\u6807\u51c6\u5316\u8d8b\u52bf<\/h5>\n<p>yaml<\/p>\n<p># \u672a\u6765\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u6807\u51c6\u5316\u7684\u53ef\u80fd\u65b9\u5411<\/p>\n<p>emerging_standards:<br \/>\n  # 1. \u884c\u4e1a\u7279\u5b9a\u72b6\u6001\u7801\u6807\u51c6<br \/>\n  ecommerce:<br \/>\n    &#8211; code: 460<br \/>\n      name: OUT_OF_STOCK<br \/>\n      standard: &#034;E-Commerce API Standard v1.0&#034;<\/p>\n<p>    &#8211; code: 461<br \/>\n      name: PRICE_CHANGED<br \/>\n      standard: &#034;E-Commerce API Standard v1.0&#034;<\/p>\n<p>  finance:<br \/>\n    &#8211; code: 470<br \/>\n      name: INSUFFICIENT_FUNDS<br \/>\n      standard: &#034;Open Banking API v3.1&#034;<\/p>\n<p>    &#8211; code: 471<br \/>\n      name: TRANSACTION_LIMIT_EXCEEDED<br \/>\n      standard: &#034;Open Banking API v3.1&#034;<\/p>\n<p>  # 2. \u6280\u672f\u67b6\u6784\u72b6\u6001\u7801<br \/>\n  microservices:<br \/>\n    &#8211; code: 520<br \/>\n      name: CIRCUIT_BREAKER_OPEN<br \/>\n      standard: &#034;Microservices Resilience Pattern v2&#034;<\/p>\n<p>    &#8211; code: 521<br \/>\n      name: BULKHEAD_FULL<br \/>\n      standard: &#034;Microservices Resilience Pattern v2&#034;<\/p>\n<p>  # 3. \u5b9e\u65f6\u901a\u4fe1\u72b6\u6001\u7801<br \/>\n  websocket:<br \/>\n    &#8211; code: 1008<br \/>\n      name: POLICY_VIOLATION<br \/>\n      standard: &#034;RFC 6455&#034;<\/p>\n<p>    &#8211; code: 1013<br \/>\n      name: TRY_AGAIN_LATER<br \/>\n      standard: &#034;RFC 6455 Extension&#034;<\/p>\n<p>adoption_timeline:<br \/>\n  2023:<br \/>\n    &#8211; &#034;Experimental custom codes in major APIs&#034;<br \/>\n    &#8211; &#034;Industry-specific code registries emerge&#034;<\/p>\n<p>  2024:<br \/>\n    &#8211; &#034;IANA registration of popular custom codes&#034;<br \/>\n    &#8211; &#034;Widespread adoption in microservices&#034;<\/p>\n<p>  2025:<br \/>\n    &#8211; &#034;Standardization of resilience patterns&#034;<br \/>\n    &#8211; &#034;Cross-industry code harmonization&#034;<\/p>\n<p>  2026:<br \/>\n    &#8211; &#034;Automated code negotiation&#034;<br \/>\n    &#8211; &#034;AI-driven status code optimization&#034;<\/p>\n<h5>36.7.2 \u6280\u672f\u6f14\u8fdb\u9884\u6d4b<\/h5>\n<p>python<\/p>\n<p># \u672a\u6765\u72b6\u6001\u7801\u5904\u7406\u7cfb\u7edf\u7684\u53ef\u80fd\u67b6\u6784<br \/>\nfrom typing import Dict, List, Optional, Protocol<br \/>\nfrom dataclasses import dataclass<br \/>\nimport asyncio<\/p>\n<p>class IntelligentStatusCodeSystem:<br \/>\n    &#034;&#034;&#034;<br \/>\n    \u667a\u80fd\u72b6\u6001\u7801\u5904\u7406\u7cfb\u7edf<br \/>\n    \u9884\u6d4b\u672a\u6765\u7684\u53d1\u5c55\u65b9\u5411<br \/>\n    &#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.code_registry &#061; DynamicCodeRegistry()<br \/>\n        self.negotiation_engine &#061; CodeNegotiationEngine()<br \/>\n        self.learning_engine &#061; MachineLearningEngine()<\/p>\n<p>    async def handle_request(self, request: Request) -&gt; Response:<br \/>\n        &#034;&#034;&#034;\u667a\u80fd\u5904\u7406\u8bf7\u6c42&#xff0c;\u52a8\u6001\u9009\u62e9\u72b6\u6001\u7801&#034;&#034;&#034;<\/p>\n<p>        # 1. \u5206\u6790\u8bf7\u6c42\u4e0a\u4e0b\u6587<br \/>\n        context &#061; await self.analyze_context(request)<\/p>\n<p>        # 2. \u534f\u5546\u6700\u4f73\u72b6\u6001\u7801<br \/>\n        preferred_codes &#061; await self.negotiation_engine.negotiate(<br \/>\n            request,<br \/>\n            context<br \/>\n        )<\/p>\n<p>        # 3. \u52a8\u6001\u751f\u6210\u6216\u9009\u62e9\u72b6\u6001\u7801<br \/>\n        if self.should_generate_dynamic_code(context):<br \/>\n            status_code &#061; await self.generate_dynamic_code(context)<br \/>\n        else:<br \/>\n            status_code &#061; await self.select_best_code(<br \/>\n                preferred_codes,<br \/>\n                context<br \/>\n            )<\/p>\n<p>        # 4. \u5b66\u4e60\u5e76\u4f18\u5316<br \/>\n        await self.learning_engine.record_decision(<br \/>\n            request, status_code, context<br \/>\n        )<\/p>\n<p>        return await self.build_response(status_code, context)<\/p>\n<p>    async def generate_dynamic_code(self, context: Dict) -&gt; int:<br \/>\n        &#034;&#034;&#034;\u52a8\u6001\u751f\u6210\u72b6\u6001\u7801&#xff08;\u672a\u6765\u53ef\u80fd\u7279\u6027&#xff09;&#034;&#034;&#034;<br \/>\n        # \u57fa\u4e8e\u4e0a\u4e0b\u6587\u54c8\u5e0c\u751f\u6210\u552f\u4e00\u72b6\u6001\u7801<br \/>\n        context_hash &#061; hash(str(context))<\/p>\n<p>        # \u4f7f\u7528\u6269\u5c55\u8303\u56f4&#xff08;\u5982 600-999&#xff09;<br \/>\n        dynamic_code &#061; 600 &#043; (context_hash % 400)<\/p>\n<p>        # \u6ce8\u518c\u4e34\u65f6\u72b6\u6001\u7801<br \/>\n        await self.code_registry.register_temporary(<br \/>\n            code&#061;dynamic_code,<br \/>\n            context&#061;context,<br \/>\n            ttl_seconds&#061;3600  # 1\u5c0f\u65f6\u6709\u6548\u671f<br \/>\n        )<\/p>\n<p>        return dynamic_code<\/p>\n<p>    async def select_best_code(self,<br \/>\n                              options: List[int],<br \/>\n                              context: Dict) -&gt; int:<br \/>\n        &#034;&#034;&#034;\u9009\u62e9\u6700\u4f73\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        scores &#061; []<\/p>\n<p>        for code in options:<br \/>\n            # \u8003\u8651\u591a\u4e2a\u56e0\u7d20<br \/>\n            score &#061; await self.score_code(code, context)<br \/>\n            scores.append((code, score))<\/p>\n<p>        # \u9009\u62e9\u6700\u9ad8\u5206<br \/>\n        scores.sort(key&#061;lambda x: x[1], reverse&#061;True)<br \/>\n        return scores[0][0]<\/p>\n<p>    async def score_code(self, code: int, context: Dict) -&gt; float:<br \/>\n        &#034;&#034;&#034;\u4e3a\u72b6\u6001\u7801\u8bc4\u5206&#034;&#034;&#034;<br \/>\n        score &#061; 0.0<\/p>\n<p>        # 1. \u5ba2\u6237\u7aef\u517c\u5bb9\u6027&#xff08;30%&#xff09;<br \/>\n        client_compatibility &#061; await self.check_client_compatibility(<br \/>\n            code, context[&#039;user_agent&#039;]<br \/>\n        )<br \/>\n        score &#043;&#061; client_compatibility * 0.3<\/p>\n<p>        # 2. \u8bed\u4e49\u51c6\u786e\u6027&#xff08;40%&#xff09;<br \/>\n        semantic_accuracy &#061; await self.evaluate_semantic_accuracy(<br \/>\n            code, context<br \/>\n        )<br \/>\n        score &#043;&#061; semantic_accuracy * 0.4<\/p>\n<p>        # 3. \u6027\u80fd\u5f71\u54cd&#xff08;20%&#xff09;<br \/>\n        performance_impact &#061; await self.estimate_performance_impact(code)<br \/>\n        score &#043;&#061; performance_impact * 0.2<\/p>\n<p>        # 4. \u76d1\u63a7\u4ef7\u503c&#xff08;10%&#xff09;<br \/>\n        monitoring_value &#061; await self.assess_monitoring_value(code)<br \/>\n        score &#043;&#061; monitoring_value * 0.1<\/p>\n<p>        return score<\/p>\n<p>    def predict_future_trends(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u9884\u6d4b\u672a\u6765\u53d1\u5c55\u8d8b\u52bf&#034;&#034;&#034;<br \/>\n        return {<br \/>\n            &#034;dynamic_codes&#034;: {<br \/>\n                &#034;probability&#034;: 0.8,<br \/>\n                &#034;timeline&#034;: &#034;2025-2026&#034;,<br \/>\n                &#034;description&#034;: &#034;\u4e0a\u4e0b\u6587\u76f8\u5173\u7684\u52a8\u6001\u72b6\u6001\u7801\u751f\u6210&#034;<br \/>\n            },<br \/>\n            &#034;ai_optimized_codes&#034;: {<br \/>\n                &#034;probability&#034;: 0.9,<br \/>\n                &#034;timeline&#034;: &#034;2024-2025&#034;,<br \/>\n                &#034;description&#034;: &#034;\u57fa\u4e8e\u673a\u5668\u5b66\u4e60\u7684\u72b6\u6001\u7801\u4f18\u5316&#034;<br \/>\n            },<br \/>\n            &#034;cross_protocol_codes&#034;: {<br \/>\n                &#034;probability&#034;: 0.7,<br \/>\n                &#034;timeline&#034;: &#034;2025&#043;&#034;,<br \/>\n                &#034;description&#034;: &#034;\u8de8HTTP\/gRPC\/WebSocket\u7684\u7edf\u4e00\u72b6\u6001\u7801&#034;<br \/>\n            },<br \/>\n            &#034;quantum_resistant_codes&#034;: {<br \/>\n                &#034;probability&#034;: 0.6,<br \/>\n                &#034;timeline&#034;: &#034;2026&#043;&#034;,<br \/>\n                &#034;description&#034;: &#034;\u6297\u91cf\u5b50\u8ba1\u7b97\u7684\u5b89\u5168\u72b6\u6001\u7801&#034;<br \/>\n            }<br \/>\n        }<\/p>\n<p># \u672a\u6765\u53ef\u80fd\u7684\u4ee3\u7801\u534f\u5546\u534f\u8bae<br \/>\n&#064;dataclass<br \/>\nclass CodeNegotiation:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u534f\u5546\u534f\u8bae&#xff08;\u6982\u5ff5&#xff09;&#034;&#034;&#034;<br \/>\n    protocol_version: str &#061; &#034;1.0&#034;<br \/>\n    supported_codes: List[int]<br \/>\n    preferred_ranges: List[tuple]<br \/>\n    client_capabilities: Dict<br \/>\n    server_capabilities: Dict<\/p>\n<p>    async def negotiate(self) -&gt; NegotiationResult:<br \/>\n        &#034;&#034;&#034;\u534f\u5546\u53cc\u65b9\u90fd\u652f\u6301\u7684\u6700\u4f73\u72b6\u6001\u7801\u96c6&#034;&#034;&#034;<br \/>\n        # \u5bfb\u627e\u4ea4\u96c6<br \/>\n        common_codes &#061; set(self.supported_codes) &amp; \\\\<br \/>\n                      set(self.server_capabilities.get(&#039;supported_codes&#039;, []))<\/p>\n<p>        # \u6839\u636e\u4f18\u5148\u7ea7\u6392\u5e8f<br \/>\n        prioritized &#061; self.prioritize_codes(common_codes)<\/p>\n<p>        return NegotiationResult(<br \/>\n            agreed_codes&#061;prioritized,<br \/>\n            fallback_codes&#061;self.determine_fallbacks(),<br \/>\n            metadata&#061;self.generate_metadata()<br \/>\n        )<\/p>\n<h4>36.8 \u603b\u7ed3<\/h4>\n<p>\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u548c\u6269\u5c55\u72b6\u6001\u7801\u662f\u73b0\u4ee3Web API\u53d1\u5c55\u7684\u91cd\u8981\u65b9\u5411&#xff0c;\u5b83\u4eec\u63d0\u4f9b\u4e86&#xff1a;<\/p>\n<li>\n<p>\u66f4\u7cbe\u786e\u7684\u8bed\u4e49\u8868\u8fbe&#xff1a;\u80fd\u591f\u51c6\u786e\u63cf\u8ff0\u4e1a\u52a1\u7279\u5b9a\u72b6\u6001<\/p>\n<\/li>\n<li>\n<p>\u66f4\u597d\u7684\u9519\u8bef\u5904\u7406&#xff1a;\u63d0\u4f9b\u4e30\u5bcc\u7684\u4e0a\u4e0b\u6587\u4fe1\u606f<\/p>\n<\/li>\n<li>\n<p>\u589e\u5f3a\u7684\u53ef\u89c2\u6d4b\u6027&#xff1a;\u4fbf\u4e8e\u76d1\u63a7\u548c\u95ee\u9898\u8bca\u65ad<\/p>\n<\/li>\n<li>\n<p>\u7075\u6d3b\u7684\u6269\u5c55\u673a\u5236&#xff1a;\u652f\u6301\u4e1a\u52a1\u548c\u6280\u672f\u6f14\u8fdb<\/p>\n<\/li>\n<p>\u5173\u952e\u6210\u529f\u56e0\u7d20&#xff1a;<\/p>\n<ul>\n<li>\n<p>\u6e05\u6670\u7684\u8bed\u4e49\u5b9a\u4e49\u548c\u6587\u6863<\/p>\n<\/li>\n<li>\n<p>\u5ba2\u6237\u7aef\u548c\u670d\u52a1\u5668\u7aef\u7684\u826f\u597d\u652f\u6301<\/p>\n<\/li>\n<li>\n<p>\u5b8c\u5584\u7684\u76d1\u63a7\u548c\u544a\u8b66\u673a\u5236<\/p>\n<\/li>\n<li>\n<p>\u6e10\u8fdb\u5f0f\u7684\u91c7\u7528\u7b56\u7565<\/p>\n<\/li>\n<li>\n<p>\u5b89\u5168\u6027\u8003\u8651\u548c\u5ba1\u8ba1<\/p>\n<\/li>\n<\/ul>\n<p>\u672a\u6765\u5c55\u671b&#xff1a;<\/p>\n<ul>\n<li>\n<p>\u884c\u4e1a\u6807\u51c6\u5316\u7a0b\u5ea6\u63d0\u9ad8<\/p>\n<\/li>\n<li>\n<p>\u667a\u80fd\u5316\u548c\u52a8\u6001\u5316\u8d8b\u52bf<\/p>\n<\/li>\n<li>\n<p>\u8de8\u534f\u8bae\u7684\u7edf\u4e00\u72b6\u6001\u8868\u793a<\/p>\n<\/li>\n<li>\n<p>\u66f4\u597d\u7684\u5f00\u53d1\u5de5\u5177\u652f\u6301<\/p>\n<\/li>\n<\/ul>\n<p>\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u7684\u6b63\u786e\u4f7f\u7528\u53ef\u4ee5\u663e\u8457\u63d0\u5347API\u7684\u53ef\u7528\u6027\u3001\u53ef\u7ef4\u62a4\u6027\u548c\u7528\u6237\u4f53\u9a8c&#xff0c;\u4f46\u9700\u8981\u8c28\u614e\u8bbe\u8ba1\u548c\u7ba1\u7406&#xff0c;\u907f\u514d\u8fc7\u5ea6\u590d\u6742\u5316\u548c\u788e\u7247\u5316\u3002<\/p>\n<hr \/>\n<h3>\u7b2c37\u7ae0&#xff1a;\u72b6\u6001\u7801\u7684\u5b89\u5168\u8003\u91cf<\/h3>\n<h4>37.1 \u72b6\u6001\u7801\u7684\u4fe1\u606f\u6cc4\u9732\u98ce\u9669<\/h4>\n<h5>37.1.1 \u6307\u7eb9\u8bc6\u522b\u4e0e\u7cfb\u7edf\u63a2\u6d4b<\/h5>\n<p>\u653b\u51fb\u8005\u53ef\u4ee5\u5229\u7528\u72b6\u6001\u7801\u5dee\u5f02\u8fdb\u884c\u7cfb\u7edf\u6307\u7eb9\u8bc6\u522b&#xff1a;<\/p>\n<p>python<\/p>\n<p># \u72b6\u6001\u7801\u6307\u7eb9\u8bc6\u522b\u653b\u51fb\u793a\u4f8b<br \/>\nimport requests<br \/>\nfrom typing import Dict, List<\/p>\n<p>class StatusCodeFingerprinter:<br \/>\n    &#034;&#034;&#034;\u901a\u8fc7\u72b6\u6001\u7801\u5dee\u5f02\u8bc6\u522b\u76ee\u6807\u7cfb\u7edf&#034;&#034;&#034;<\/p>\n<p>    def __init__(self, target_url: str):<br \/>\n        self.target_url &#061; target_url<br \/>\n        self.fingerprint_db &#061; self._load_fingerprint_database()<\/p>\n<p>    def _load_fingerprint_database(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u52a0\u8f7d\u5df2\u77e5\u7cfb\u7edf\u7684\u72b6\u6001\u7801\u6307\u7eb9&#034;&#034;&#034;<br \/>\n        return {<br \/>\n            &#039;Apache\/2.4&#039;: {<br \/>\n                &#039;404&#039;: {&#039;body_contains&#039;: [&#039;Apache&#039;, &#039;Not Found&#039;]},<br \/>\n                &#039;403&#039;: {&#039;body_contains&#039;: [&#039;Forbidden&#039;]},<br \/>\n                &#039;500&#039;: {&#039;body_pattern&#039;: r&#039;Internal Server Error&#039;}<br \/>\n            },<br \/>\n            &#039;Nginx\/1.18&#039;: {<br \/>\n                &#039;404&#039;: {&#039;body_contains&#039;: [&#039;nginx&#039;, &#039;404 Not Found&#039;]},<br \/>\n                &#039;403&#039;: {&#039;body_contains&#039;: [&#039;403 Forbidden&#039;]},<br \/>\n                &#039;500&#039;: {&#039;body_pattern&#039;: r&#039;500 Internal Server Error&#039;}<br \/>\n            },<br \/>\n            &#039;IIS\/10.0&#039;: {<br \/>\n                &#039;404&#039;: {&#039;body_contains&#039;: [&#039;IIS&#039;, &#039;404&#039;]},<br \/>\n                &#039;403&#039;: {&#039;body_contains&#039;: [&#039;403&#039;, &#039;Forbidden&#039;]},<br \/>\n                &#039;500&#039;: {&#039;body_contains&#039;: [&#039;ASP.NET&#039;, &#039;Error&#039;]}<br \/>\n            }<br \/>\n        }<\/p>\n<p>    def probe_status_codes(self) -&gt; Dict[int, Dict]:<br \/>\n        &#034;&#034;&#034;\u63a2\u6d4b\u5404\u79cd\u72b6\u6001\u7801\u54cd\u5e94&#034;&#034;&#034;<br \/>\n        probes &#061; {<br \/>\n            # \u5e38\u89c1\u8def\u5f84\u63a2\u6d4b<br \/>\n            &#039;\/nonexistent&#039;: 404,<br \/>\n            &#039;\/admin&#039;: 403,<br \/>\n            &#039;\/test.php&#039;: 500,  # \u53ef\u80fd\u89e6\u53d1PHP\u9519\u8bef<br \/>\n            &#039;\/.git\/HEAD&#039;: 403,  # Git\u76ee\u5f55\u8bbf\u95ee<br \/>\n            &#039;\/wp-admin&#039;: 302,   # WordPress\u91cd\u5b9a\u5411<br \/>\n            # \u7279\u6b8a\u8bf7\u6c42\u63a2\u6d4b<br \/>\n            &#039;malformed&#039;: 400,   # \u7578\u5f62\u8bf7\u6c42<br \/>\n            &#039;oversized&#039;: 413,   # \u8fc7\u5927\u8bf7\u6c42\u4f53<br \/>\n        }<\/p>\n<p>        results &#061; {}<br \/>\n        for path, expected_code in probes.items():<br \/>\n            try:<br \/>\n                response &#061; requests.get(<br \/>\n                    f&#034;{self.target_url}{path}&#034;,<br \/>\n                    timeout&#061;3,<br \/>\n                    allow_redirects&#061;False<br \/>\n                )<br \/>\n                results[expected_code] &#061; {<br \/>\n                    &#039;actual_code&#039;: response.status_code,<br \/>\n                    &#039;headers&#039;: dict(response.headers),<br \/>\n                    &#039;body_sample&#039;: response.text[:500],<br \/>\n                    &#039;response_time&#039;: response.elapsed.total_seconds()<br \/>\n                }<br \/>\n            except Exception as e:<br \/>\n                results[expected_code] &#061; {&#039;error&#039;: str(e)}<\/p>\n<p>        return results<\/p>\n<p>    def identify_system(self, probe_results: Dict) -&gt; List[str]:<br \/>\n        &#034;&#034;&#034;\u6839\u636e\u63a2\u6d4b\u7ed3\u679c\u8bc6\u522b\u7cfb\u7edf&#034;&#034;&#034;<br \/>\n        matches &#061; []<\/p>\n<p>        for system_name, fingerprint in self.fingerprint_db.items():<br \/>\n            score &#061; 0<br \/>\n            total_checks &#061; 0<\/p>\n<p>            for expected_code, checks in fingerprint.items():<br \/>\n                if expected_code in probe_results:<br \/>\n                    result &#061; probe_results[expected_code]<\/p>\n<p>                    # \u68c0\u67e5\u54cd\u5e94\u4f53\u7279\u5f81<br \/>\n                    if &#039;body_contains&#039; in checks:<br \/>\n                        for substring in checks[&#039;body_contains&#039;]:<br \/>\n                            if substring in result.get(&#039;body_sample&#039;, &#039;&#039;):<br \/>\n                                score &#043;&#061; 1<br \/>\n                            total_checks &#043;&#061; 1<\/p>\n<p>                    # \u68c0\u67e5\u6b63\u5219\u6a21\u5f0f<br \/>\n                    if &#039;body_pattern&#039; in checks:<br \/>\n                        import re<br \/>\n                        if re.search(checks[&#039;body_pattern&#039;],<br \/>\n                                    result.get(&#039;body_sample&#039;, &#039;&#039;)):<br \/>\n                            score &#043;&#061; 1<br \/>\n                        total_checks &#043;&#061; 1<\/p>\n<p>            # \u8ba1\u7b97\u5339\u914d\u5ea6<br \/>\n            if total_checks &gt; 0:<br \/>\n                match_percentage &#061; (score \/ total_checks) * 100<br \/>\n                if match_percentage &gt; 70:  # 70%\u5339\u914d\u9608\u503c<br \/>\n                    matches.append({<br \/>\n                        &#039;system&#039;: system_name,<br \/>\n                        &#039;confidence&#039;: match_percentage,<br \/>\n                        &#039;evidence&#039;: self._get_evidence(probe_results, fingerprint)<br \/>\n                    })<\/p>\n<p>        return sorted(matches, key&#061;lambda x: x[&#039;confidence&#039;], reverse&#061;True)<\/p>\n<p>    def _get_evidence(self, results: Dict, fingerprint: Dict) -&gt; List[str]:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u5339\u914d\u8bc1\u636e&#034;&#034;&#034;<br \/>\n        evidence &#061; []<br \/>\n        for code, checks in fingerprint.items():<br \/>\n            if code in results:<br \/>\n                evidence.append(f&#034;Code {code}: {checks}&#034;)<br \/>\n        return evidence<\/p>\n<p># \u9632\u62a4\u63aa\u65bd&#xff1a;\u6807\u51c6\u5316\u9519\u8bef\u54cd\u5e94<br \/>\ndef secure_error_response(status_code: int, expose_details: bool &#061; False) -&gt; Dict:<br \/>\n    &#034;&#034;&#034;\u5b89\u5168\u7684\u9519\u8bef\u54cd\u5e94\u751f\u6210\u5668&#034;&#034;&#034;<br \/>\n    base_responses &#061; {<br \/>\n        400: {&#034;error&#034;: &#034;Bad Request&#034;},<br \/>\n        401: {&#034;error&#034;: &#034;Unauthorized&#034;},<br \/>\n        403: {&#034;error&#034;: &#034;Forbidden&#034;},<br \/>\n        404: {&#034;error&#034;: &#034;Not Found&#034;},<br \/>\n        500: {&#034;error&#034;: &#034;Internal Server Error&#034;},<br \/>\n        # &#8230; \u5176\u4ed6\u72b6\u6001\u7801<br \/>\n    }<\/p>\n<p>    response &#061; base_responses.get(status_code, {&#034;error&#034;: &#034;Unknown Error&#034;})<\/p>\n<p>    if expose_details:<br \/>\n        # \u751f\u4ea7\u73af\u5883\u4e0d\u66b4\u9732\u8be6\u7ec6\u4fe1\u606f<br \/>\n        if os.getenv(&#039;ENVIRONMENT&#039;) &#061;&#061; &#039;production&#039;:<br \/>\n            # \u8bb0\u5f55\u8be6\u7ec6\u9519\u8bef\u4f46\u4e0d\u8fd4\u56de\u7ed9\u5ba2\u6237\u7aef<br \/>\n            logger.error(f&#034;Detailed error for {status_code}&#034;)<br \/>\n            return response<\/p>\n<p>        # \u5f00\u53d1\u73af\u5883\u53ef\u4ee5\u5305\u542b\u66f4\u591a\u4fe1\u606f<br \/>\n        response[&#039;debug&#039;] &#061; {<br \/>\n            &#039;timestamp&#039;: datetime.now().isoformat(),<br \/>\n            &#039;request_id&#039;: request_id<br \/>\n        }<\/p>\n<p>    return response<\/p>\n<h5>37.1.2 \u7528\u6237\u679a\u4e3e\u653b\u51fb<\/h5>\n<p>\u72b6\u6001\u7801\u5dee\u5f02\u53ef\u80fd\u6cc4\u9732\u7528\u6237\u662f\u5426\u5b58\u5728&#xff1a;<\/p>\n<p>python<\/p>\n<p># \u7528\u6237\u679a\u4e3e\u653b\u51fb\u9632\u62a4<br \/>\nfrom flask import Flask, request, jsonify<br \/>\nfrom functools import wraps<\/p>\n<p>app &#061; Flask(__name__)<\/p>\n<p>class UserEnumerationProtection:<br \/>\n    &#034;&#034;&#034;\u7528\u6237\u679a\u4e3e\u653b\u51fb\u9632\u62a4&#034;&#034;&#034;<\/p>\n<p>    &#064;staticmethod<br \/>\n    def uniform_auth_responses():<br \/>\n        &#034;&#034;&#034;\u7edf\u4e00\u8ba4\u8bc1\u54cd\u5e94\u88c5\u9970\u5668&#034;&#034;&#034;<br \/>\n        def decorator(f):<br \/>\n            &#064;wraps(f)<br \/>\n            def decorated_function(*args, **kwargs):<br \/>\n                try:<br \/>\n                    return f(*args, **kwargs)<br \/>\n                except AuthenticationError as e:<br \/>\n                    # \u7edf\u4e00\u8fd4\u56de401&#xff0c;\u4e0d\u533a\u5206\u7528\u6237\u662f\u5426\u5b58\u5728<br \/>\n                    return jsonify({<br \/>\n                        &#039;error&#039;: &#039;Invalid credentials&#039;,<br \/>\n                        &#039;code&#039;: &#039;AUTH_ERROR&#039;<br \/>\n                    }), 401<br \/>\n                except UserNotFoundError:<br \/>\n                    # \u4e5f\u8fd4\u56de401&#xff0c;\u4e0d\u6cc4\u9732\u7528\u6237\u5b58\u5728\u4fe1\u606f<br \/>\n                    return jsonify({<br \/>\n                        &#039;error&#039;: &#039;Invalid credentials&#039;,<br \/>\n                        &#039;code&#039;: &#039;AUTH_ERROR&#039;<br \/>\n                    }), 401<br \/>\n            return decorated_function<br \/>\n        return decorator<\/p>\n<p>    &#064;staticmethod<br \/>\n    def rate_limit_by_username(username: str, endpoint: str) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u57fa\u4e8e\u7528\u6237\u540d\u7684\u901f\u7387\u9650\u5236&#034;&#034;&#034;<br \/>\n        key &#061; f&#034;rate_limit:{endpoint}:{hash(username)}&#034;<br \/>\n        attempts &#061; redis.incr(key)<\/p>\n<p>        if attempts &#061;&#061; 1:<br \/>\n            redis.expire(key, 300)  # 5\u5206\u949f\u7a97\u53e3<\/p>\n<p>        if attempts &gt; 10:  # 10\u6b21\u5c1d\u8bd5\u540e\u9650\u5236<br \/>\n            return False<\/p>\n<p>        return True<\/p>\n<p>    &#064;staticmethod<br \/>\n    def progressive_delay(attempts: int) -&gt; float:<br \/>\n        &#034;&#034;&#034;\u6e10\u8fdb\u5f0f\u5ef6\u8fdf\u54cd\u5e94&#034;&#034;&#034;<br \/>\n        if attempts &lt; 3:<br \/>\n            return 0  # \u65e0\u5ef6\u8fdf<br \/>\n        elif attempts &lt; 6:<br \/>\n            return 1.0  # 1\u79d2\u5ef6\u8fdf<br \/>\n        elif attempts &lt; 10:<br \/>\n            return 2.5  # 2.5\u79d2\u5ef6\u8fdf<br \/>\n        else:<br \/>\n            return 5.0  # 5\u79d2\u5ef6\u8fdf<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\n&#064;app.route(&#039;\/api\/login&#039;, methods&#061;[&#039;POST&#039;])<br \/>\n&#064;UserEnumerationProtection.uniform_auth_responses()<br \/>\ndef login():<br \/>\n    data &#061; request.get_json()<br \/>\n    username &#061; data.get(&#039;username&#039;)<br \/>\n    password &#061; data.get(&#039;password&#039;)<\/p>\n<p>    # \u5e94\u7528\u901f\u7387\u9650\u5236<br \/>\n    if not UserEnumerationProtection.rate_limit_by_username(username, &#039;login&#039;):<br \/>\n        return jsonify({<br \/>\n            &#039;error&#039;: &#039;Too many attempts&#039;,<br \/>\n            &#039;retry_after&#039;: 300<br \/>\n        }), 429<\/p>\n<p>    # \u9a8c\u8bc1\u7528\u6237&#xff08;\u7edf\u4e00\u9519\u8bef\u6d88\u606f&#xff09;<br \/>\n    user &#061; User.query.filter_by(username&#061;username).first()<br \/>\n    if not user or not user.verify_password(password):<br \/>\n        raise AuthenticationError()<\/p>\n<p>    # \u6210\u529f\u54cd\u5e94<br \/>\n    return jsonify({<br \/>\n        &#039;token&#039;: user.generate_token(),<br \/>\n        &#039;user_id&#039;: user.public_id  # \u4e0d\u8fd4\u56de\u5185\u90e8ID<br \/>\n    })<\/p>\n<p>&#064;app.route(&#039;\/api\/users\/&lt;username&gt;\/exists&#039;, methods&#061;[&#039;GET&#039;])<br \/>\ndef check_user_exists(username: str):<br \/>\n    &#034;&#034;&#034;\u68c0\u67e5\u7528\u6237\u662f\u5426\u5b58\u5728&#xff08;\u9632\u62a4\u7248\u672c&#xff09;&#034;&#034;&#034;<br \/>\n    # \u6c38\u8fdc\u8fd4\u56de\u76f8\u540c\u7ed3\u6784&#xff0c;\u4f46\u4e0d\u540c\u72b6\u6001\u7801<br \/>\n    user_exists &#061; User.query.filter_by(username&#061;username).first() is not None<\/p>\n<p>    # \u4e3a\u4e86\u5b89\u5168&#xff0c;\u603b\u662f\u8fd4\u56de200&#xff0c;\u5185\u5bb9\u76f8\u540c<br \/>\n    return jsonify({<br \/>\n        &#039;available&#039;: False,  # \u603b\u662f\u8fd4\u56deFalse<br \/>\n        &#039;message&#039;: &#039;Username check completed&#039;<br \/>\n    })<\/p>\n<h4>37.2 \u72b6\u6001\u7801\u76f8\u5173\u7684\u653b\u51fb\u5411\u91cf<\/h4>\n<h5>37.2.1 \u72b6\u6001\u7801\u6ce8\u5165\u653b\u51fb<\/h5>\n<p>python<\/p>\n<p># \u72b6\u6001\u7801\u6ce8\u5165\u653b\u51fb\u4e0e\u9632\u62a4<br \/>\nimport re<br \/>\nfrom http.client import HTTPResponse<br \/>\nfrom io import BytesIO<\/p>\n<p>class StatusCodeInjection:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u6ce8\u5165\u653b\u51fb\u793a\u4f8b&#034;&#034;&#034;<\/p>\n<p>    &#064;staticmethod<br \/>\n    def exploit_crlf_injection(url: str, user_input: str):<br \/>\n        &#034;&#034;&#034;CRLF\u6ce8\u5165\u653b\u51fb\u72b6\u6001\u884c&#034;&#034;&#034;<br \/>\n        # \u653b\u51fb\u8005\u53ef\u80fd\u5c1d\u8bd5\u6ce8\u5165\u72b6\u6001\u7801<br \/>\n        malicious_input &#061; f&#034;test\\\\r\\\\nHTTP\/1.1 200 OK\\\\r\\\\nContent-Type: text\/html\\\\r\\\\n\\\\r\\\\n&lt;h1&gt;Hacked&lt;\/h1&gt;&#034;<\/p>\n<p>        # \u5982\u679c\u670d\u52a1\u5668\u6ca1\u6709\u6b63\u786e\u8fc7\u6ee4&#xff0c;\u53ef\u80fd\u89e3\u6790\u6076\u610f\u72b6\u6001\u884c<br \/>\n        response &#061; requests.get(f&#034;{url}?input&#061;{malicious_input}&#034;)<\/p>\n<p>        # \u68c0\u67e5\u54cd\u5e94\u662f\u5426\u88ab\u6ce8\u5165<br \/>\n        if &#034;Hacked&#034; in response.text:<br \/>\n            print(&#034;CRLF\u6ce8\u5165\u6210\u529f&#xff01;&#034;)<br \/>\n            return True<br \/>\n        return False<\/p>\n<p>    &#064;staticmethod<br \/>\n    def exploit_header_injection(headers: Dict):<br \/>\n        &#034;&#034;&#034;\u901a\u8fc7\u5934\u90e8\u6ce8\u5165\u4f2a\u9020\u72b6\u6001&#034;&#034;&#034;<br \/>\n        # \u653b\u51fb\u8005\u5c1d\u8bd5\u6ce8\u5165\u6076\u610f\u5934\u90e8<br \/>\n        malicious_headers &#061; {<br \/>\n            &#039;X-Forwarded-Status&#039;: &#039;200&#039;,  # \u5c1d\u8bd5\u5f71\u54cd\u72b6\u6001\u7801\u5224\u65ad<br \/>\n            &#039;X-HTTP-Status-Override&#039;: &#039;200&#039;<br \/>\n        }<br \/>\n        headers.update(malicious_headers)<br \/>\n        return headers<\/p>\n<p>class StatusCodeInjectionProtection:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u6ce8\u5165\u9632\u62a4&#034;&#034;&#034;<\/p>\n<p>    &#064;staticmethod<br \/>\n    def validate_status_code(code: int) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u9a8c\u8bc1\u72b6\u6001\u7801\u6709\u6548\u6027&#034;&#034;&#034;<br \/>\n        # \u5141\u8bb8\u7684\u72b6\u6001\u7801\u8303\u56f4<br \/>\n        valid_codes &#061; set(range(100, 600))  # 100-599<\/p>\n<p>        # \u5e38\u89c1\u72b6\u6001\u7801\u68c0\u67e5<br \/>\n        if code not in valid_codes:<br \/>\n            return False<\/p>\n<p>        # \u4e0d\u5141\u8bb8\u7684\u72b6\u6001\u7801&#xff08;\u53ef\u80fd\u7528\u4e8e\u653b\u51fb&#xff09;<br \/>\n        forbidden_codes &#061; {<br \/>\n            000,  # \u975e\u6807\u51c6<br \/>\n            666,  # \u53ef\u80fd\u88ab\u6076\u610f\u4f7f\u7528<br \/>\n            777,<br \/>\n            888,<br \/>\n            999<br \/>\n        }<\/p>\n<p>        if code in forbidden_codes:<br \/>\n            return False<\/p>\n<p>        return True<\/p>\n<p>    &#064;staticmethod<br \/>\n    def sanitize_headers(headers: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u6e05\u7406\u53ef\u80fd\u5f71\u54cd\u72b6\u6001\u7801\u7684\u5934\u90e8&#034;&#034;&#034;<br \/>\n        dangerous_headers &#061; [<br \/>\n            &#039;X-Forwarded-Status&#039;,<br \/>\n            &#039;X-HTTP-Status-Override&#039;,<br \/>\n            &#039;X-Status&#039;,<br \/>\n            &#039;Status-Code&#039;,<br \/>\n            &#039;X-Response-Status&#039;<br \/>\n        ]<\/p>\n<p>        sanitized &#061; {}<br \/>\n        for key, value in headers.items():<br \/>\n            # \u68c0\u67e5\u5934\u90e8\u540d\u79f0<br \/>\n            key_lower &#061; key.lower()<\/p>\n<p>            # \u79fb\u9664\u5371\u9669\u5934\u90e8<br \/>\n            if any(dangerous in key_lower for dangerous in dangerous_headers):<br \/>\n                continue<\/p>\n<p>            # \u6e05\u7406\u5934\u90e8\u503c\u4e2d\u7684CRLF<br \/>\n            sanitized_value &#061; re.sub(r&#039;[\\\\r\\\\n]&#039;, &#039;&#039;, str(value))<\/p>\n<p>            # \u957f\u5ea6\u9650\u5236<br \/>\n            if len(sanitized_value) &gt; 8192:  # 8KB\u9650\u5236<br \/>\n                sanitized_value &#061; sanitized_value[:8192]<\/p>\n<p>            sanitized[key] &#061; sanitized_value<\/p>\n<p>        return sanitized<\/p>\n<p>    &#064;staticmethod<br \/>\n    def parse_response_safely(raw_response: bytes) -&gt; HTTPResponse:<br \/>\n        &#034;&#034;&#034;\u5b89\u5168\u89e3\u6790HTTP\u54cd\u5e94&#034;&#034;&#034;<br \/>\n        # \u4f7f\u7528\u5b89\u5168\u89e3\u6790\u5668<br \/>\n        response &#061; HTTPResponse(BytesIO(raw_response))<\/p>\n<p>        try:<br \/>\n            response.begin()<\/p>\n<p>            # \u9a8c\u8bc1\u72b6\u6001\u884c<br \/>\n            status_line &#061; str(response.status) &#043; &#039; &#039; &#043; response.reason<\/p>\n<p>            # \u68c0\u67e5\u72b6\u6001\u884c\u683c\u5f0f<br \/>\n            if not re.match(r&#039;^\\\\d{3} [^\\\\r\\\\n]&#043;$&#039;, status_line):<br \/>\n                raise ValueError(&#034;Invalid status line&#034;)<\/p>\n<p>            # \u68c0\u67e5\u72b6\u6001\u7801\u8303\u56f4<br \/>\n            status_code &#061; response.status<br \/>\n            if not (100 &lt;&#061; status_code &lt;&#061; 599):<br \/>\n                raise ValueError(&#034;Invalid status code range&#034;)<\/p>\n<p>            return response<\/p>\n<p>        except Exception as e:<br \/>\n            # \u89e3\u6790\u5931\u8d25\u65f6\u8fd4\u56de\u5b89\u5168\u9ed8\u8ba4\u503c<br \/>\n            fake_response &#061; HTTPResponse(BytesIO(<br \/>\n                b&#034;HTTP\/1.1 500 Internal Server Error\\\\r\\\\n&#034;<br \/>\n                b&#034;Content-Type: text\/plain\\\\r\\\\n&#034;<br \/>\n                b&#034;\\\\r\\\\n&#034;<br \/>\n                b&#034;Invalid response&#034;<br \/>\n            ))<br \/>\n            fake_response.begin()<br \/>\n            return fake_response<\/p>\n<h5>37.2.2 \u72b6\u6001\u7801\u91cd\u653e\u653b\u51fb<\/h5>\n<p>python<\/p>\n<p># \u72b6\u6001\u7801\u91cd\u653e\u653b\u51fb\u9632\u62a4<br \/>\nimport hashlib<br \/>\nimport time<br \/>\nfrom typing import Optional<\/p>\n<p>class StatusCodeReplayProtection:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u91cd\u653e\u653b\u51fb\u9632\u62a4&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.processed_requests &#061; set()<br \/>\n        self.window_size &#061; 300  # 5\u5206\u949f\u7a97\u53e3<\/p>\n<p>    def generate_request_signature(self,<br \/>\n                                  request_data: Dict,<br \/>\n                                  timestamp: int) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u8bf7\u6c42\u7b7e\u540d&#034;&#034;&#034;<br \/>\n        # \u57fa\u4e8e\u8bf7\u6c42\u5185\u5bb9\u548c\u65f6\u95f4\u6233\u751f\u6210\u7b7e\u540d<br \/>\n        components &#061; [<br \/>\n            request_data.get(&#039;method&#039;, &#039;GET&#039;),<br \/>\n            request_data.get(&#039;path&#039;, &#039;&#039;),<br \/>\n            str(timestamp),<br \/>\n            request_data.get(&#039;body_hash&#039;, &#039;&#039;),<br \/>\n            request_data.get(&#039;nonce&#039;, &#039;&#039;)<br \/>\n        ]<\/p>\n<p>        signature_string &#061; &#039;|&#039;.join(components)<br \/>\n        return hashlib.sha256(signature_string.encode()).hexdigest()<\/p>\n<p>    def check_replay_attack(self,<br \/>\n                           request_signature: str,<br \/>\n                           request_timestamp: int) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u91cd\u653e\u653b\u51fb&#034;&#034;&#034;<br \/>\n        current_time &#061; int(time.time())<\/p>\n<p>        # \u68c0\u67e5\u65f6\u95f4\u6233\u6709\u6548\u6027<br \/>\n        time_diff &#061; abs(current_time &#8211; request_timestamp)<br \/>\n        if time_diff &gt; self.window_size:<br \/>\n            # \u65f6\u95f4\u6233\u8d85\u51fa\u7a97\u53e3<br \/>\n            return True<\/p>\n<p>        # \u68c0\u67e5\u7b7e\u540d\u662f\u5426\u5df2\u5904\u7406<br \/>\n        if request_signature in self.processed_requests:<br \/>\n            # \u91cd\u653e\u653b\u51fb\u68c0\u6d4b<br \/>\n            return True<\/p>\n<p>        # \u6dfb\u52a0\u5230\u5df2\u5904\u7406\u96c6\u5408<br \/>\n        self.processed_requests.add(request_signature)<\/p>\n<p>        # \u6e05\u7406\u8fc7\u671f\u7b7e\u540d<br \/>\n        self._cleanup_old_signatures()<\/p>\n<p>        return False<\/p>\n<p>    def _cleanup_old_signatures(self):<br \/>\n        &#034;&#034;&#034;\u6e05\u7406\u8fc7\u671f\u7b7e\u540d&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u57fa\u4e8e\u65f6\u95f4\u6233\u6e05\u7406\u65e7\u7b7e\u540d<br \/>\n        # \u7b80\u5316\u5b9e\u73b0&#xff1a;\u5b9a\u671f\u6e05\u7406<br \/>\n        if len(self.processed_requests) &gt; 10000:<br \/>\n            # \u5f53\u96c6\u5408\u8fc7\u5927\u65f6\u6e05\u7406\u4e00\u534a<br \/>\n            self.processed_requests &#061; set(list(self.processed_requests)[5000:])<\/p>\n<p>    def add_timestamp_protection(self, response: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u4e3a\u54cd\u5e94\u6dfb\u52a0\u65f6\u95f4\u6233\u4fdd\u62a4&#034;&#034;&#034;<br \/>\n        protected_response &#061; response.copy()<\/p>\n<p>        # \u6dfb\u52a0\u65f6\u95f4\u6233<br \/>\n        protected_response[&#039;timestamp&#039;] &#061; int(time.time())<\/p>\n<p>        # \u6dfb\u52a0\u54cd\u5e94\u7b7e\u540d<br \/>\n        response_hash &#061; hashlib.sha256(<br \/>\n            str(response).encode()<br \/>\n        ).hexdigest()<br \/>\n        protected_response[&#039;signature&#039;] &#061; response_hash<\/p>\n<p>        # \u6dfb\u52a0\u6709\u6548\u671f<br \/>\n        protected_response[&#039;expires_at&#039;] &#061; int(time.time()) &#043; 300  # 5\u5206\u949f<\/p>\n<p>        return protected_response<\/p>\n<p>    def verify_response_freshness(self,<br \/>\n                                 response: Dict,<br \/>\n                                 max_age: int &#061; 300) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u9a8c\u8bc1\u54cd\u5e94\u65b0\u9c9c\u5ea6&#034;&#034;&#034;<br \/>\n        timestamp &#061; response.get(&#039;timestamp&#039;)<br \/>\n        expires_at &#061; response.get(&#039;expires_at&#039;)<\/p>\n<p>        if not timestamp or not expires_at:<br \/>\n            return False<\/p>\n<p>        current_time &#061; int(time.time())<\/p>\n<p>        # \u68c0\u67e5\u662f\u5426\u8fc7\u671f<br \/>\n        if current_time &gt; expires_at:<br \/>\n            return False<\/p>\n<p>        # \u53ef\u9009&#xff1a;\u9a8c\u8bc1\u54cd\u5e94\u7b7e\u540d<br \/>\n        if &#039;signature&#039; in response:<br \/>\n            response_copy &#061; response.copy()<br \/>\n            expected_signature &#061; response_copy.pop(&#039;signature&#039;)<\/p>\n<p>            actual_signature &#061; hashlib.sha256(<br \/>\n                str(response_copy).encode()<br \/>\n            ).hexdigest()<\/p>\n<p>            if actual_signature !&#061; expected_signature:<br \/>\n                return False<\/p>\n<p>        return True<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nclass ProtectedAPI:<br \/>\n    def __init__(self):<br \/>\n        self.replay_protection &#061; StatusCodeReplayProtection()<\/p>\n<p>    def handle_request(self, request_data: Dict) -&gt; Dict:<br \/>\n        # \u63d0\u53d6\u7b7e\u540d\u548c\u65f6\u95f4\u6233<br \/>\n        request_signature &#061; request_data.get(&#039;signature&#039;)<br \/>\n        request_timestamp &#061; request_data.get(&#039;timestamp&#039;)<\/p>\n<p>        if not request_signature or not request_timestamp:<br \/>\n            return {<br \/>\n                &#039;error&#039;: &#039;Missing security headers&#039;,<br \/>\n                &#039;code&#039;: 400<br \/>\n            }<\/p>\n<p>        # \u68c0\u67e5\u91cd\u653e\u653b\u51fb<br \/>\n        if self.replay_protection.check_replay_attack(<br \/>\n            request_signature, request_timestamp<br \/>\n        ):<br \/>\n            return {<br \/>\n                &#039;error&#039;: &#039;Possible replay attack detected&#039;,<br \/>\n                &#039;code&#039;: 400<br \/>\n            }<\/p>\n<p>        # \u5904\u7406\u4e1a\u52a1\u903b\u8f91<br \/>\n        response &#061; self.process_business_logic(request_data)<\/p>\n<p>        # \u6dfb\u52a0\u4fdd\u62a4<br \/>\n        protected_response &#061; self.replay_protection.add_timestamp_protection(<br \/>\n            response<br \/>\n        )<\/p>\n<p>        return protected_response<\/p>\n<h4>37.3 \u5b89\u5168\u72b6\u6001\u7801\u5904\u7406\u6700\u4f73\u5b9e\u8df5<\/h4>\n<h5>37.3.1 \u751f\u4ea7\u73af\u5883\u9519\u8bef\u5904\u7406<\/h5>\n<p>python<\/p>\n<p># \u751f\u4ea7\u73af\u5883\u5b89\u5168\u7684\u72b6\u6001\u7801\u5904\u7406<br \/>\nimport logging<br \/>\nfrom enum import Enum<br \/>\nfrom dataclasses import dataclass<br \/>\nfrom typing import Dict, Any, Optional<\/p>\n<p># \u914d\u7f6e\u65e5\u5fd7<br \/>\nlogging.basicConfig(<br \/>\n    level&#061;logging.INFO,<br \/>\n    format&#061;&#039;%(asctime)s &#8211; %(name)s &#8211; %(levelname)s &#8211; %(message)s&#039;<br \/>\n)<br \/>\nlogger &#061; logging.getLogger(__name__)<\/p>\n<p>class Environment(Enum):<br \/>\n    DEVELOPMENT &#061; &#034;development&#034;<br \/>\n    STAGING &#061; &#034;staging&#034;<br \/>\n    PRODUCTION &#061; &#034;production&#034;<\/p>\n<p>class ErrorDetailLevel(Enum):<br \/>\n    &#034;&#034;&#034;\u9519\u8bef\u8be6\u60c5\u7ea7\u522b&#034;&#034;&#034;<br \/>\n    NONE &#061; &#034;none&#034;        # \u65e0\u8be6\u60c5<br \/>\n    MINIMAL &#061; &#034;minimal&#034;  # \u6700\u5c0f\u8be6\u60c5<br \/>\n    STANDARD &#061; &#034;standard&#034; # \u6807\u51c6\u8be6\u60c5<br \/>\n    VERBOSE &#061; &#034;verbose&#034;  # \u8be6\u7ec6\u8be6\u60c5<\/p>\n<p>&#064;dataclass<br \/>\nclass SecurityConfig:<br \/>\n    &#034;&#034;&#034;\u5b89\u5168\u914d\u7f6e&#034;&#034;&#034;<br \/>\n    environment: Environment<br \/>\n    error_detail_level: ErrorDetailLevel<br \/>\n    expose_stack_trace: bool &#061; False<br \/>\n    log_sensitive_errors: bool &#061; False<br \/>\n    custom_error_pages: bool &#061; True<\/p>\n<p>    &#064;property<br \/>\n    def is_production(self) -&gt; bool:<br \/>\n        return self.environment &#061;&#061; Environment.PRODUCTION<\/p>\n<p>class SecureErrorHandler:<br \/>\n    &#034;&#034;&#034;\u5b89\u5168\u9519\u8bef\u5904\u7406\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self, config: SecurityConfig):<br \/>\n        self.config &#061; config<br \/>\n        self.error_templates &#061; self._load_error_templates()<\/p>\n<p>    def _load_error_templates(self) -&gt; Dict[int, Dict]:<br \/>\n        &#034;&#034;&#034;\u52a0\u8f7d\u9519\u8bef\u6a21\u677f&#034;&#034;&#034;<br \/>\n        return {<br \/>\n            400: {<br \/>\n                &#039;title&#039;: &#039;Bad Request&#039;,<br \/>\n                &#039;message&#039;: &#039;The request could not be understood by the server.&#039;,<br \/>\n                &#039;user_message&#039;: &#039;Please check your request and try again.&#039;<br \/>\n            },<br \/>\n            401: {<br \/>\n                &#039;title&#039;: &#039;Unauthorized&#039;,<br \/>\n                &#039;message&#039;: &#039;Authentication is required and has failed.&#039;,<br \/>\n                &#039;user_message&#039;: &#039;Please log in and try again.&#039;<br \/>\n            },<br \/>\n            403: {<br \/>\n                &#039;title&#039;: &#039;Forbidden&#039;,<br \/>\n                &#039;message&#039;: &#039;You do not have permission to access this resource.&#039;,<br \/>\n                &#039;user_message&#039;: &#039;Contact your administrator for access.&#039;<br \/>\n            },<br \/>\n            404: {<br \/>\n                &#039;title&#039;: &#039;Not Found&#039;,<br \/>\n                &#039;message&#039;: &#039;The requested resource was not found.&#039;,<br \/>\n                &#039;user_message&#039;: &#039;The page you are looking for does not exist.&#039;<br \/>\n            },<br \/>\n            500: {<br \/>\n                &#039;title&#039;: &#039;Internal Server Error&#039;,<br \/>\n                &#039;message&#039;: &#039;An unexpected error occurred on the server.&#039;,<br \/>\n                &#039;user_message&#039;: &#039;We are working to fix this issue. Please try again later.&#039;<br \/>\n            },<br \/>\n            # \u66f4\u591a\u72b6\u6001\u7801&#8230;<br \/>\n        }<\/p>\n<p>    def handle_error(self,<br \/>\n                    status_code: int,<br \/>\n                    error: Optional[Exception] &#061; None,<br \/>\n                    context: Optional[Dict[str, Any]] &#061; None) -&gt; Dict[str, Any]:<br \/>\n        &#034;&#034;&#034;\u5904\u7406\u9519\u8bef\u5e76\u8fd4\u56de\u5b89\u5168\u54cd\u5e94&#034;&#034;&#034;<\/p>\n<p>        # \u9a8c\u8bc1\u72b6\u6001\u7801<br \/>\n        if not self._is_valid_status_code(status_code):<br \/>\n            status_code &#061; 500  # \u964d\u7ea7\u5230500<\/p>\n<p>        # \u83b7\u53d6\u6a21\u677f<br \/>\n        template &#061; self.error_templates.get(<br \/>\n            status_code,<br \/>\n            self.error_templates[500]<br \/>\n        )<\/p>\n<p>        # \u6784\u5efa\u57fa\u7840\u54cd\u5e94<br \/>\n        response &#061; {<br \/>\n            &#039;error&#039;: {<br \/>\n                &#039;code&#039;: status_code,<br \/>\n                &#039;title&#039;: template[&#039;title&#039;],<br \/>\n                &#039;user_message&#039;: template[&#039;user_message&#039;]<br \/>\n            }<br \/>\n        }<\/p>\n<p>        # \u6839\u636e\u73af\u5883\u6dfb\u52a0\u8be6\u60c5<br \/>\n        if not self.config.is_production:<br \/>\n            response[&#039;error&#039;][&#039;developer_message&#039;] &#061; template[&#039;message&#039;]<\/p>\n<p>            if error and self.config.expose_stack_trace:<br \/>\n                response[&#039;error&#039;][&#039;exception&#039;] &#061; str(error)<\/p>\n<p>                if self.config.error_detail_level &#061;&#061; ErrorDetailLevel.VERBOSE:<br \/>\n                    import traceback<br \/>\n                    response[&#039;error&#039;][&#039;stack_trace&#039;] &#061; traceback.format_exc()<\/p>\n<p>        # \u6dfb\u52a0\u8bf7\u6c42ID\u7528\u4e8e\u8ffd\u8e2a<br \/>\n        if context and &#039;request_id&#039; in context:<br \/>\n            response[&#039;request_id&#039;] &#061; context[&#039;request_id&#039;]<\/p>\n<p>            # \u8bb0\u5f55\u9519\u8bef\u65e5\u5fd7<br \/>\n            self._log_error(status_code, error, context)<\/p>\n<p>        # \u6dfb\u52a0\u5b89\u5168\u5934\u90e8<br \/>\n        security_headers &#061; self._get_security_headers()<\/p>\n<p>        return {<br \/>\n            &#039;status_code&#039;: status_code,<br \/>\n            &#039;body&#039;: response,<br \/>\n            &#039;headers&#039;: security_headers<br \/>\n        }<\/p>\n<p>    def _is_valid_status_code(self, code: int) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u9a8c\u8bc1\u72b6\u6001\u7801\u6709\u6548\u6027&#034;&#034;&#034;<br \/>\n        if not isinstance(code, int):<br \/>\n            return False<\/p>\n<p>        if code &lt; 100 or code &gt; 599:<br \/>\n            return False<\/p>\n<p>        # \u4e0d\u5141\u8bb8\u7684\u72b6\u6001\u7801<br \/>\n        forbidden_codes &#061; {000, 666, 777, 888, 999}<br \/>\n        if code in forbidden_codes:<br \/>\n            return False<\/p>\n<p>        return True<\/p>\n<p>    def _log_error(self,<br \/>\n                  status_code: int,<br \/>\n                  error: Optional[Exception],<br \/>\n                  context: Dict[str, Any]):<br \/>\n        &#034;&#034;&#034;\u5b89\u5168\u5730\u8bb0\u5f55\u9519\u8bef\u65e5\u5fd7&#034;&#034;&#034;<br \/>\n        log_data &#061; {<br \/>\n            &#039;status_code&#039;: status_code,<br \/>\n            &#039;request_id&#039;: context.get(&#039;request_id&#039;),<br \/>\n            &#039;endpoint&#039;: context.get(&#039;endpoint&#039;),<br \/>\n            &#039;user_id&#039;: context.get(&#039;user_id&#039;),<br \/>\n            &#039;timestamp&#039;: context.get(&#039;timestamp&#039;)<br \/>\n        }<\/p>\n<p>        if error:<br \/>\n            log_data[&#039;error_type&#039;] &#061; type(error).__name__<br \/>\n            log_data[&#039;error_message&#039;] &#061; str(error)<\/p>\n<p>            # \u53ea\u6709\u5728\u914d\u7f6e\u5141\u8bb8\u65f6\u8bb0\u5f55\u8be6\u7ec6\u9519\u8bef<br \/>\n            if self.config.log_sensitive_errors:<br \/>\n                import traceback<br \/>\n                log_data[&#039;stack_trace&#039;] &#061; traceback.format_exc()<\/p>\n<p>        # \u6839\u636e\u72b6\u6001\u7801\u7ea7\u522b\u8bb0\u5f55<br \/>\n        if status_code &gt;&#061; 500:<br \/>\n            logger.error(f&#034;Server error: {log_data}&#034;)<br \/>\n        elif status_code &gt;&#061; 400:<br \/>\n            logger.warning(f&#034;Client error: {log_data}&#034;)<br \/>\n        else:<br \/>\n            logger.info(f&#034;Info response: {log_data}&#034;)<\/p>\n<p>    def _get_security_headers(self) -&gt; Dict[str, str]:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u5b89\u5168\u5934\u90e8&#034;&#034;&#034;<br \/>\n        headers &#061; {<br \/>\n            &#039;X-Content-Type-Options&#039;: &#039;nosniff&#039;,<br \/>\n            &#039;X-Frame-Options&#039;: &#039;DENY&#039;,<br \/>\n            &#039;X-XSS-Protection&#039;: &#039;1; mode&#061;block&#039;,<br \/>\n            &#039;Referrer-Policy&#039;: &#039;strict-origin-when-cross-origin&#039;,<br \/>\n            &#039;Content-Security-Policy&#039;: &#034;default-src &#039;self&#039;&#034;<br \/>\n        }<\/p>\n<p>        if self.config.is_production:<br \/>\n            headers[&#039;Strict-Transport-Security&#039;] &#061; &#039;max-age&#061;31536000; includeSubDomains&#039;<\/p>\n<p>        return headers<\/p>\n<p># Flask\u96c6\u6210\u793a\u4f8b<br \/>\nfrom flask import Flask, jsonify, request, g<br \/>\nimport uuid<\/p>\n<p>app &#061; Flask(__name__)<\/p>\n<p># \u914d\u7f6e\u5b89\u5168\u5904\u7406\u5668<br \/>\nsecurity_config &#061; SecurityConfig(<br \/>\n    environment&#061;Environment.PRODUCTION,<br \/>\n    error_detail_level&#061;ErrorDetailLevel.MINIMAL,<br \/>\n    expose_stack_trace&#061;False<br \/>\n)<br \/>\nerror_handler &#061; SecureErrorHandler(security_config)<\/p>\n<p>&#064;app.before_request<br \/>\ndef before_request():<br \/>\n    &#034;&#034;&#034;\u8bf7\u6c42\u524d\u8bbe\u7f6e\u4e0a\u4e0b\u6587&#034;&#034;&#034;<br \/>\n    g.request_id &#061; str(uuid.uuid4())<br \/>\n    g.start_time &#061; time.time()<\/p>\n<p>&#064;app.errorhandler(Exception)<br \/>\ndef handle_exception(error):<br \/>\n    &#034;&#034;&#034;\u5168\u5c40\u5f02\u5e38\u5904\u7406\u5668&#034;&#034;&#034;<br \/>\n    context &#061; {<br \/>\n        &#039;request_id&#039;: g.get(&#039;request_id&#039;),<br \/>\n        &#039;endpoint&#039;: request.path,<br \/>\n        &#039;user_id&#039;: getattr(g, &#039;user_id&#039;, None),<br \/>\n        &#039;timestamp&#039;: datetime.now().isoformat(),<br \/>\n        &#039;method&#039;: request.method,<br \/>\n        &#039;ip_address&#039;: request.remote_addr<br \/>\n    }<\/p>\n<p>    # \u6839\u636e\u5f02\u5e38\u7c7b\u578b\u786e\u5b9a\u72b6\u6001\u7801<br \/>\n    if isinstance(error, NotFound):<br \/>\n        status_code &#061; 404<br \/>\n    elif isinstance(error, Unauthorized):<br \/>\n        status_code &#061; 401<br \/>\n    elif isinstance(error, Forbidden):<br \/>\n        status_code &#061; 403<br \/>\n    elif isinstance(error, BadRequest):<br \/>\n        status_code &#061; 400<br \/>\n    else:<br \/>\n        status_code &#061; 500<\/p>\n<p>    # \u4f7f\u7528\u5b89\u5168\u5904\u7406\u5668<br \/>\n    error_response &#061; error_handler.handle_error(<br \/>\n        status_code, error, context<br \/>\n    )<\/p>\n<p>    # \u8fd4\u56de\u54cd\u5e94<br \/>\n    response &#061; jsonify(error_response[&#039;body&#039;])<br \/>\n    response.status_code &#061; error_response[&#039;status_code&#039;]<\/p>\n<p>    # \u6dfb\u52a0\u5b89\u5168\u5934\u90e8<br \/>\n    for key, value in error_response[&#039;headers&#039;].items():<br \/>\n        response.headers[key] &#061; value<\/p>\n<p>    return response<\/p>\n<p>&#064;app.route(&#039;\/api\/sensitive-operation&#039;)<br \/>\ndef sensitive_operation():<br \/>\n    &#034;&#034;&#034;\u654f\u611f\u64cd\u4f5c\u793a\u4f8b&#034;&#034;&#034;<br \/>\n    # \u4e1a\u52a1\u903b\u8f91<br \/>\n    try:<br \/>\n        result &#061; perform_sensitive_operation()<br \/>\n        return jsonify({&#039;result&#039;: result})<br \/>\n    except SensitiveDataException as e:<br \/>\n        # \u654f\u611f\u6570\u636e\u9519\u8bef&#xff0c;\u4e0d\u66b4\u9732\u8be6\u60c5<br \/>\n        context &#061; {<br \/>\n            &#039;request_id&#039;: g.request_id,<br \/>\n            &#039;endpoint&#039;: request.path,<br \/>\n            &#039;timestamp&#039;: datetime.now().isoformat()<br \/>\n        }<\/p>\n<p>        error_response &#061; error_handler.handle_error(<br \/>\n            400, None, context  # \u4e0d\u4f20\u9012\u5f02\u5e38<br \/>\n        )<\/p>\n<p>        response &#061; jsonify(error_response[&#039;body&#039;])<br \/>\n        response.status_code &#061; error_response[&#039;status_code&#039;]<br \/>\n        return response<\/p>\n<h5>37.3.2 \u72b6\u6001\u7801\u5ba1\u8ba1\u4e0e\u76d1\u63a7<\/h5>\n<p>python<\/p>\n<p># \u72b6\u6001\u7801\u5b89\u5168\u5ba1\u8ba1\u7cfb\u7edf<br \/>\nfrom datetime import datetime, timedelta<br \/>\nfrom collections import defaultdict<br \/>\nfrom typing import List, Dict, Set<br \/>\nimport json<\/p>\n<p>class StatusCodeSecurityAudit:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u5b89\u5168\u5ba1\u8ba1\u7cfb\u7edf&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.suspicious_patterns &#061; self._load_suspicious_patterns()<br \/>\n        self.audit_log &#061; []<br \/>\n        self.anomaly_detector &#061; AnomalyDetector()<\/p>\n<p>    def _load_suspicious_patterns(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u52a0\u8f7d\u53ef\u7591\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        return {<br \/>\n            &#039;status_code_enumeration&#039;: {<br \/>\n                &#039;description&#039;: &#039;Rapid enumeration of status codes&#039;,<br \/>\n                &#039;threshold&#039;: 10,  # 10\u6b21\/\u5206\u949f<br \/>\n                &#039;window_minutes&#039;: 1<br \/>\n            },<br \/>\n            &#039;unusual_success_rate&#039;: {<br \/>\n                &#039;description&#039;: &#039;Unusual success rate for endpoint&#039;,<br \/>\n                &#039;threshold&#039;: 0.95,  # 95%\u6210\u529f\u7387<br \/>\n                &#039;window_minutes&#039;: 5<br \/>\n            },<br \/>\n            &#039;error_spike&#039;: {<br \/>\n                &#039;description&#039;: &#039;Sudden spike in error responses&#039;,<br \/>\n                &#039;threshold&#039;: 5,  # 5\u500d\u589e\u957f<br \/>\n                &#039;window_minutes&#039;: 1<br \/>\n            },<br \/>\n            &#039;custom_code_abuse&#039;: {<br \/>\n                &#039;description&#039;: &#039;Abuse of custom status codes&#039;,<br \/>\n                &#039;threshold&#039;: 50,  # 50\u6b21\/\u5c0f\u65f6<br \/>\n                &#039;window_minutes&#039;: 60<br \/>\n            }<br \/>\n        }<\/p>\n<p>    def audit_request(self,<br \/>\n                     request_data: Dict,<br \/>\n                     response_data: Dict) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u5ba1\u8ba1\u5355\u4e2a\u8bf7\u6c42&#034;&#034;&#034;<br \/>\n        findings &#061; []<\/p>\n<p>        # 1. \u68c0\u67e5\u72b6\u6001\u7801\u6709\u6548\u6027<br \/>\n        status_code &#061; response_data.get(&#039;status_code&#039;)<br \/>\n        if not self._is_valid_status_code(status_code):<br \/>\n            findings.append({<br \/>\n                &#039;type&#039;: &#039;INVALID_STATUS_CODE&#039;,<br \/>\n                &#039;severity&#039;: &#039;HIGH&#039;,<br \/>\n                &#039;description&#039;: f&#039;Invalid status code: {status_code}&#039;,<br \/>\n                &#039;request&#039;: request_data,<br \/>\n                &#039;response&#039;: response_data,<br \/>\n                &#039;timestamp&#039;: datetime.now()<br \/>\n            })<\/p>\n<p>        # 2. \u68c0\u67e5\u4fe1\u606f\u6cc4\u9732<br \/>\n        if self._has_information_leak(response_data):<br \/>\n            findings.append({<br \/>\n                &#039;type&#039;: &#039;INFORMATION_LEAK&#039;,<br \/>\n                &#039;severity&#039;: &#039;MEDIUM&#039;,<br \/>\n                &#039;description&#039;: &#039;Potential information leak in response&#039;,<br \/>\n                &#039;request&#039;: request_data,<br \/>\n                &#039;response&#039;: self._sanitize_response(response_data),<br \/>\n                &#039;timestamp&#039;: datetime.now()<br \/>\n            })<\/p>\n<p>        # 3. \u68c0\u67e5\u53ef\u7591\u6a21\u5f0f<br \/>\n        pattern_findings &#061; self._check_suspicious_patterns(<br \/>\n            request_data, response_data<br \/>\n        )<br \/>\n        findings.extend(pattern_findings)<\/p>\n<p>        # \u8bb0\u5f55\u5ba1\u8ba1\u65e5\u5fd7<br \/>\n        if findings:<br \/>\n            self.audit_log.extend(findings)<br \/>\n            self._notify_security_team(findings)<\/p>\n<p>        return findings<\/p>\n<p>    def _is_valid_status_code(self, code: int) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u9a8c\u8bc1\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        if not isinstance(code, int):<br \/>\n            return False<\/p>\n<p>        # \u6807\u51c6\u8303\u56f4<br \/>\n        if code &lt; 100 or code &gt; 599:<br \/>\n            return False<\/p>\n<p>        # \u68c0\u67e5\u4fdd\u7559\u8303\u56f4<br \/>\n        if 600 &lt;&#061; code &lt;&#061; 999:<br \/>\n            # \u4fdd\u7559\u8303\u56f4&#xff0c;\u53ef\u80fd\u9700\u8981\u7279\u6b8a\u5904\u7406<br \/>\n            return self._is_valid_custom_code(code)<\/p>\n<p>        return True<\/p>\n<p>    def _is_valid_custom_code(self, code: int) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u9a8c\u8bc1\u81ea\u5b9a\u4e49\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        # \u68c0\u67e5\u662f\u5426\u5728\u5141\u8bb8\u7684\u81ea\u5b9a\u4e49\u8303\u56f4\u5185<br \/>\n        allowed_ranges &#061; [<br \/>\n            (420, 429),  # \u5b9e\u9a8c\u6027<br \/>\n            (450, 499),  # \u4e1a\u52a1\u7279\u5b9a<br \/>\n            (520, 599)   # \u7cfb\u7edf\u6269\u5c55<br \/>\n        ]<\/p>\n<p>        for start, end in allowed_ranges:<br \/>\n            if start &lt;&#061; code &lt;&#061; end:<br \/>\n                return True<\/p>\n<p>        return False<\/p>\n<p>    def _has_information_leak(self, response: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u4fe1\u606f\u6cc4\u9732&#034;&#034;&#034;<br \/>\n        body &#061; json.dumps(response.get(&#039;body&#039;, {}))<\/p>\n<p>        # \u654f\u611f\u6a21\u5f0f\u68c0\u67e5<br \/>\n        sensitive_patterns &#061; [<br \/>\n            r&#039;stack trace&#039;,<br \/>\n            r&#039;line \\\\d&#043;&#039;,<br \/>\n            r&#039;file &#034;.*&#034;&#039;,<br \/>\n            r&#039;password&#039;,<br \/>\n            r&#039;secret&#039;,<br \/>\n            r&#039;api[_-]?key&#039;,<br \/>\n            r&#039;token&#039;,<br \/>\n            r&#039;database&#039;,<br \/>\n            r&#039;query:&#039;,<br \/>\n            r&#039;sql&#039;<br \/>\n        ]<\/p>\n<p>        import re<br \/>\n        for pattern in sensitive_patterns:<br \/>\n            if re.search(pattern, body, re.IGNORECASE):<br \/>\n                return True<\/p>\n<p>        # \u68c0\u67e5\u5934\u90e8\u6cc4\u9732<br \/>\n        headers &#061; response.get(&#039;headers&#039;, {})<br \/>\n        dangerous_headers &#061; [<br \/>\n            &#039;server&#039;, &#039;x-powered-by&#039;, &#039;x-aspnet-version&#039;<br \/>\n        ]<\/p>\n<p>        for header in dangerous_headers:<br \/>\n            if header in headers:<br \/>\n                return True<\/p>\n<p>        return False<\/p>\n<p>    def _sanitize_response(self, response: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u6e05\u7406\u54cd\u5e94\u4e2d\u7684\u654f\u611f\u4fe1\u606f&#034;&#034;&#034;<br \/>\n        sanitized &#061; response.copy()<\/p>\n<p>        if &#039;body&#039; in sanitized:<br \/>\n            body &#061; sanitized[&#039;body&#039;]<br \/>\n            if isinstance(body, dict):<br \/>\n                # \u79fb\u9664\u654f\u611f\u5b57\u6bb5<br \/>\n                sensitive_fields &#061; [&#039;password&#039;, &#039;token&#039;, &#039;secret&#039;]<br \/>\n                for field in sensitive_fields:<br \/>\n                    if field in body:<br \/>\n                        body[field] &#061; &#039;***REDACTED***&#039;<br \/>\n                sanitized[&#039;body&#039;] &#061; body<\/p>\n<p>        if &#039;headers&#039; in sanitized:<br \/>\n            headers &#061; sanitized[&#039;headers&#039;]<br \/>\n            # \u79fb\u9664\u654f\u611f\u5934\u90e8<br \/>\n            sensitive_headers &#061; [&#039;authorization&#039;, &#039;cookie&#039;, &#039;set-cookie&#039;]<br \/>\n            for header in sensitive_headers:<br \/>\n                if header in headers:<br \/>\n                    del headers[header]<br \/>\n            sanitized[&#039;headers&#039;] &#061; headers<\/p>\n<p>        return sanitized<\/p>\n<p>    def _check_suspicious_patterns(self,<br \/>\n                                  request: Dict,<br \/>\n                                  response: Dict) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u53ef\u7591\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        findings &#061; []<\/p>\n<p>        # \u83b7\u53d6\u5ba2\u6237\u7aef\u6807\u8bc6<br \/>\n        client_id &#061; self._get_client_identifier(request)<br \/>\n        endpoint &#061; request.get(&#039;path&#039;, &#039;&#039;)<br \/>\n        status_code &#061; response.get(&#039;status_code&#039;)<\/p>\n<p>        # \u66f4\u65b0\u7edf\u8ba1<br \/>\n        self._update_statistics(client_id, endpoint, status_code)<\/p>\n<p>        # \u68c0\u67e5\u5404\u4e2a\u6a21\u5f0f<br \/>\n        for pattern_name, config in self.suspicious_patterns.items():<br \/>\n            if self._detect_pattern(pattern_name, client_id, endpoint, config):<br \/>\n                findings.append({<br \/>\n                    &#039;type&#039;: f&#039;SUSPICIOUS_PATTERN_{pattern_name.upper()}&#039;,<br \/>\n                    &#039;severity&#039;: &#039;MEDIUM&#039;,<br \/>\n                    &#039;description&#039;: config[&#039;description&#039;],<br \/>\n                    &#039;client&#039;: client_id,<br \/>\n                    &#039;endpoint&#039;: endpoint,<br \/>\n                    &#039;pattern&#039;: pattern_name,<br \/>\n                    &#039;timestamp&#039;: datetime.now()<br \/>\n                })<\/p>\n<p>        # \u5f02\u5e38\u68c0\u6d4b<br \/>\n        anomaly &#061; self.anomaly_detector.detect(<br \/>\n            client_id, endpoint, status_code<br \/>\n        )<br \/>\n        if anomaly:<br \/>\n            findings.append({<br \/>\n                &#039;type&#039;: &#039;ANOMALY_DETECTED&#039;,<br \/>\n                &#039;severity&#039;: &#039;HIGH&#039;,<br \/>\n                &#039;description&#039;: anomaly[&#039;description&#039;],<br \/>\n                &#039;client&#039;: client_id,<br \/>\n                &#039;endpoint&#039;: endpoint,<br \/>\n                &#039;details&#039;: anomaly[&#039;details&#039;],<br \/>\n                &#039;timestamp&#039;: datetime.now()<br \/>\n            })<\/p>\n<p>        return findings<\/p>\n<p>    def _get_client_identifier(self, request: Dict) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u5ba2\u6237\u7aef\u6807\u8bc6&#034;&#034;&#034;<br \/>\n        # \u7ec4\u5408\u591a\u4e2a\u56e0\u7d20\u521b\u5efa\u6807\u8bc6<br \/>\n        factors &#061; [<br \/>\n            request.get(&#039;ip_address&#039;, &#039;&#039;),<br \/>\n            request.get(&#039;user_agent&#039;, &#039;&#039;),<br \/>\n            request.get(&#039;user_id&#039;, &#039;anonymous&#039;)<br \/>\n        ]<\/p>\n<p>        # \u4f7f\u7528\u54c8\u5e0c\u4fdd\u62a4\u9690\u79c1<br \/>\n        import hashlib<br \/>\n        identifier &#061; &#039;|&#039;.join(str(f) for f in factors)<br \/>\n        return hashlib.sha256(identifier.encode()).hexdigest()[:16]<\/p>\n<p>    def _update_statistics(self,<br \/>\n                          client_id: str,<br \/>\n                          endpoint: str,<br \/>\n                          status_code: int):<br \/>\n        &#034;&#034;&#034;\u66f4\u65b0\u7edf\u8ba1\u4fe1\u606f&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u66f4\u65b0\u65f6\u95f4\u5e8f\u5217\u6570\u636e\u5e93<br \/>\n        pass<\/p>\n<p>    def _detect_pattern(self,<br \/>\n                       pattern_name: str,<br \/>\n                       client_id: str,<br \/>\n                       endpoint: str,<br \/>\n                       config: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u7279\u5b9a\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        # \u5b9e\u9645\u4e2d\u4f1a\u67e5\u8be2\u65f6\u95f4\u5e8f\u5217\u6570\u636e<\/p>\n<p>        if pattern_name &#061;&#061; &#039;status_code_enumeration&#039;:<br \/>\n            # \u68c0\u67e5\u77ed\u65f6\u95f4\u5185\u5927\u91cf\u4e0d\u540c\u72b6\u6001\u7801<br \/>\n            return self._check_enumeration(client_id, config)<\/p>\n<p>        elif pattern_name &#061;&#061; &#039;unusual_success_rate&#039;:<br \/>\n            # \u68c0\u67e5\u5f02\u5e38\u9ad8\u7684\u6210\u529f\u7387<br \/>\n            return self._check_success_rate(endpoint, config)<\/p>\n<p>        elif pattern_name &#061;&#061; &#039;error_spike&#039;:<br \/>\n            # \u68c0\u67e5\u9519\u8bef\u7387\u7a81\u589e<br \/>\n            return self._check_error_spike(endpoint, config)<\/p>\n<p>        elif pattern_name &#061;&#061; &#039;custom_code_abuse&#039;:<br \/>\n            # \u68c0\u67e5\u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u6ee5\u7528<br \/>\n            return self._check_custom_code_abuse(client_id, config)<\/p>\n<p>        return False<\/p>\n<p>    def _notify_security_team(self, findings: List[Dict]):<br \/>\n        &#034;&#034;&#034;\u901a\u77e5\u5b89\u5168\u56e2\u961f&#034;&#034;&#034;<br \/>\n        # \u6839\u636e\u4e25\u91cd\u7a0b\u5ea6\u9009\u62e9\u901a\u77e5\u65b9\u5f0f<br \/>\n        high_severity &#061; any(f[&#039;severity&#039;] &#061;&#061; &#039;HIGH&#039; for f in findings)<\/p>\n<p>        if high_severity:<br \/>\n            # \u7acb\u5373\u901a\u77e5<br \/>\n            self._send_alert(&#039;HIGH&#039;, findings)<br \/>\n        else:<br \/>\n            # \u8bb0\u5f55\u65e5\u5fd7\u4f9b\u540e\u7eed\u5206\u6790<br \/>\n            for finding in findings:<br \/>\n                logger.warning(f&#034;Security finding: {finding}&#034;)<\/p>\n<p>class AnomalyDetector:<br \/>\n    &#034;&#034;&#034;\u5f02\u5e38\u68c0\u6d4b\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.historical_data &#061; defaultdict(list)<br \/>\n        self.window_size &#061; timedelta(hours&#061;24)<\/p>\n<p>    def detect(self,<br \/>\n              client_id: str,<br \/>\n              endpoint: str,<br \/>\n              status_code: int) -&gt; Optional[Dict]:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u5f02\u5e38&#034;&#034;&#034;<br \/>\n        current_time &#061; datetime.now()<\/p>\n<p>        # \u6e05\u7406\u65e7\u6570\u636e<br \/>\n        self._clean_old_data(current_time)<\/p>\n<p>        # \u8bb0\u5f55\u5f53\u524d\u8bf7\u6c42<br \/>\n        self.historical_data[(client_id, endpoint)].append({<br \/>\n            &#039;timestamp&#039;: current_time,<br \/>\n            &#039;status_code&#039;: status_code<br \/>\n        })<\/p>\n<p>        # \u5206\u6790\u6a21\u5f0f<br \/>\n        recent_requests &#061; self._get_recent_requests(<br \/>\n            client_id, endpoint, current_time<br \/>\n        )<\/p>\n<p>        if len(recent_requests) &lt; 10:<br \/>\n            # \u6570\u636e\u4e0d\u8db3<br \/>\n            return None<\/p>\n<p>        # \u8ba1\u7b97\u7edf\u8ba1\u7279\u5f81<br \/>\n        features &#061; self._extract_features(recent_requests)<\/p>\n<p>        # \u68c0\u6d4b\u5f02\u5e38<br \/>\n        if self._is_anomalous(features):<br \/>\n            return {<br \/>\n                &#039;description&#039;: &#039;Unusual request pattern detected&#039;,<br \/>\n                &#039;details&#039;: {<br \/>\n                    &#039;client&#039;: client_id,<br \/>\n                    &#039;endpoint&#039;: endpoint,<br \/>\n                    &#039;features&#039;: features,<br \/>\n                    &#039;request_count&#039;: len(recent_requests)<br \/>\n                }<br \/>\n            }<\/p>\n<p>        return None<\/p>\n<p>    def _clean_old_data(self, current_time: datetime):<br \/>\n        &#034;&#034;&#034;\u6e05\u7406\u65e7\u6570\u636e&#034;&#034;&#034;<br \/>\n        cutoff &#061; current_time &#8211; self.window_size<\/p>\n<p>        for key in list(self.historical_data.keys()):<br \/>\n            self.historical_data[key] &#061; [<br \/>\n                req for req in self.historical_data[key]<br \/>\n                if req[&#039;timestamp&#039;] &gt; cutoff<br \/>\n            ]<\/p>\n<p>            if not self.historical_data[key]:<br \/>\n                del self.historical_data[key]<\/p>\n<p>    def _get_recent_requests(self,<br \/>\n                            client_id: str,<br \/>\n                            endpoint: str,<br \/>\n                            current_time: datetime) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u6700\u8fd1\u8bf7\u6c42&#034;&#034;&#034;<br \/>\n        key &#061; (client_id, endpoint)<br \/>\n        if key not in self.historical_data:<br \/>\n            return []<\/p>\n<p>        # \u6700\u8fd15\u5206\u949f<br \/>\n        cutoff &#061; current_time &#8211; timedelta(minutes&#061;5)<\/p>\n<p>        return [<br \/>\n            req for req in self.historical_data[key]<br \/>\n            if req[&#039;timestamp&#039;] &gt; cutoff<br \/>\n        ]<\/p>\n<p>    def _extract_features(self, requests: List[Dict]) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u63d0\u53d6\u7279\u5f81&#034;&#034;&#034;<br \/>\n        status_codes &#061; [req[&#039;status_code&#039;] for req in requests]<\/p>\n<p>        return {<br \/>\n            &#039;total_requests&#039;: len(requests),<br \/>\n            &#039;unique_status_codes&#039;: len(set(status_codes)),<br \/>\n            &#039;success_rate&#039;: sum(1 for code in status_codes<br \/>\n                               if 200 &lt;&#061; code &lt; 300) \/ len(status_codes),<br \/>\n            &#039;error_rate&#039;: sum(1 for code in status_codes<br \/>\n                             if code &gt;&#061; 400) \/ len(status_codes),<br \/>\n            &#039;status_code_entropy&#039;: self._calculate_entropy(status_codes)<br \/>\n        }<\/p>\n<p>    def _calculate_entropy(self, codes: List[int]) -&gt; float:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u72b6\u6001\u7801\u71b5\u503c&#034;&#034;&#034;<br \/>\n        from collections import Counter<br \/>\n        import math<\/p>\n<p>        counter &#061; Counter(codes)<br \/>\n        total &#061; len(codes)<\/p>\n<p>        entropy &#061; 0.0<br \/>\n        for count in counter.values():<br \/>\n            probability &#061; count \/ total<br \/>\n            entropy -&#061; probability * math.log2(probability)<\/p>\n<p>        return entropy<\/p>\n<p>    def _is_anomalous(self, features: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u5224\u65ad\u662f\u5426\u5f02\u5e38&#034;&#034;&#034;<br \/>\n        # \u7b80\u5316\u7684\u5f02\u5e38\u68c0\u6d4b<br \/>\n        # \u5b9e\u9645\u4e2d\u4f1a\u4f7f\u7528\u673a\u5668\u5b66\u4e60\u6a21\u578b<\/p>\n<p>        # \u5f02\u5e38\u9ad8\u7684\u8bf7\u6c42\u6570<br \/>\n        if features[&#039;total_requests&#039;] &gt; 100:  # 5\u5206\u949f\u5185100&#043;\u8bf7\u6c42<br \/>\n            return True<\/p>\n<p>        # \u5f02\u5e38\u591a\u7684\u4e0d\u540c\u72b6\u6001\u7801<br \/>\n        if features[&#039;unique_status_codes&#039;] &gt; 20:<br \/>\n            return True<\/p>\n<p>        # \u5f02\u5e38\u4f4e\u7684\u6210\u529f\u7387<br \/>\n        if features[&#039;success_rate&#039;] &lt; 0.1:  # \u6210\u529f\u7387\u4f4e\u4e8e10%<br \/>\n            return True<\/p>\n<p>        # \u5f02\u5e38\u9ad8\u7684\u71b5\u503c&#xff08;\u72b6\u6001\u7801\u5206\u5e03\u8fc7\u4e8e\u5747\u5300&#xff09;<br \/>\n        if features[&#039;status_code_entropy&#039;] &gt; 3.0:<br \/>\n            return True<\/p>\n<p>        return False<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\naudit_system &#061; StatusCodeSecurityAudit()<\/p>\n<p># \u6a21\u62df\u8bf7\u6c42\u5904\u7406<br \/>\ndef process_request(request: Dict) -&gt; Dict:<br \/>\n    # \u5904\u7406\u8bf7\u6c42&#8230;<br \/>\n    response &#061; {<br \/>\n        &#039;status_code&#039;: 200,<br \/>\n        &#039;body&#039;: {&#039;result&#039;: &#039;success&#039;},<br \/>\n        &#039;headers&#039;: {&#039;Content-Type&#039;: &#039;application\/json&#039;}<br \/>\n    }<\/p>\n<p>    # \u5ba1\u8ba1\u8bf7\u6c42<br \/>\n    findings &#061; audit_system.audit_request(request, response)<\/p>\n<p>    if findings:<br \/>\n        # \u8bb0\u5f55\u5b89\u5168\u4e8b\u4ef6<br \/>\n        for finding in findings:<br \/>\n            if finding[&#039;severity&#039;] &#061;&#061; &#039;HIGH&#039;:<br \/>\n                # \u53ef\u80fd\u9700\u8981\u963b\u6b62\u8bf7\u6c42<br \/>\n                response &#061; {<br \/>\n                    &#039;status_code&#039;: 429,<br \/>\n                    &#039;body&#039;: {&#039;error&#039;: &#039;Too many requests&#039;},<br \/>\n                    &#039;headers&#039;: {&#039;Retry-After&#039;: &#039;60&#039;}<br \/>\n                }<br \/>\n                break<\/p>\n<p>    return response<\/p>\n<h4>37.4 \u9632\u5fa1\u7b56\u7565\u4e0e\u5b89\u5168\u67b6\u6784<\/h4>\n<h5>37.4.1 \u6df1\u5ea6\u9632\u5fa1\u67b6\u6784<\/h5>\n<p>python<\/p>\n<p># \u72b6\u6001\u7801\u5b89\u5168\u6df1\u5ea6\u9632\u5fa1\u67b6\u6784<br \/>\nfrom abc import ABC, abstractmethod<br \/>\nfrom typing import List, Dict, Optional<br \/>\nfrom dataclasses import dataclass<br \/>\nimport asyncio<\/p>\n<p>&#064;dataclass<br \/>\nclass SecurityLayerConfig:<br \/>\n    &#034;&#034;&#034;\u5b89\u5168\u5c42\u914d\u7f6e&#034;&#034;&#034;<br \/>\n    name: str<br \/>\n    enabled: bool &#061; True<br \/>\n    priority: int &#061; 0<br \/>\n    fail_open: bool &#061; False  # \u5931\u8d25\u65f6\u662f\u5426\u653e\u884c<\/p>\n<p>class SecurityLayer(ABC):<br \/>\n    &#034;&#034;&#034;\u5b89\u5168\u5c42\u62bd\u8c61\u57fa\u7c7b&#034;&#034;&#034;<\/p>\n<p>    def __init__(self, config: SecurityLayerConfig):<br \/>\n        self.config &#061; config<\/p>\n<p>    &#064;abstractmethod<br \/>\n    async def inspect_request(self,<br \/>\n                             request: Dict) -&gt; Optional[Dict]:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u8bf7\u6c42&#034;&#034;&#034;<br \/>\n        pass<\/p>\n<p>    &#064;abstractmethod<br \/>\n    async def inspect_response(self,<br \/>\n                              request: Dict,<br \/>\n                              response: Dict) -&gt; Optional[Dict]:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u54cd\u5e94&#034;&#034;&#034;<br \/>\n        pass<\/p>\n<p>class StatusCodeValidationLayer(SecurityLayer):<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u9a8c\u8bc1\u5c42&#034;&#034;&#034;<\/p>\n<p>    async def inspect_request(self, request: Dict) -&gt; Optional[Dict]:<br \/>\n        # \u8bf7\u6c42\u9636\u6bb5\u4e0d\u9700\u8981\u9a8c\u8bc1\u72b6\u6001\u7801<br \/>\n        return None<\/p>\n<p>    async def inspect_response(self,<br \/>\n                              request: Dict,<br \/>\n                              response: Dict) -&gt; Optional[Dict]:<br \/>\n        status_code &#061; response.get(&#039;status_code&#039;)<\/p>\n<p>        # \u9a8c\u8bc1\u72b6\u6001\u7801<br \/>\n        if not self._is_valid_status_code(status_code):<br \/>\n            return {<br \/>\n                &#039;layer&#039;: self.config.name,<br \/>\n                &#039;action&#039;: &#039;MODIFY&#039;,<br \/>\n                &#039;new_response&#039;: {<br \/>\n                    &#039;status_code&#039;: 500,<br \/>\n                    &#039;body&#039;: {&#039;error&#039;: &#039;Invalid response&#039;},<br \/>\n                    &#039;headers&#039;: response.get(&#039;headers&#039;, {})<br \/>\n                },<br \/>\n                &#039;reason&#039;: f&#039;Invalid status code: {status_code}&#039;<br \/>\n            }<\/p>\n<p>        # \u68c0\u67e5\u4fe1\u606f\u6cc4\u9732<br \/>\n        if self._has_sensitive_information(response):<br \/>\n            return {<br \/>\n                &#039;layer&#039;: self.config.name,<br \/>\n                &#039;action&#039;: &#039;SANITIZE&#039;,<br \/>\n                &#039;sanitized_response&#039;: self._sanitize_response(response),<br \/>\n                &#039;reason&#039;: &#039;Sensitive information detected&#039;<br \/>\n            }<\/p>\n<p>        return None<\/p>\n<p>    def _is_valid_status_code(self, code: int) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u9a8c\u8bc1\u72b6\u6001\u7801\u6709\u6548\u6027&#034;&#034;&#034;<br \/>\n        if not isinstance(code, int):<br \/>\n            return False<\/p>\n<p>        # \u6807\u51c6HTTP\u72b6\u6001\u7801\u8303\u56f4<br \/>\n        if 100 &lt;&#061; code &lt;&#061; 599:<br \/>\n            return True<\/p>\n<p>        # \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u68c0\u67e5<br \/>\n        if self._is_valid_custom_code(code):<br \/>\n            return True<\/p>\n<p>        return False<\/p>\n<p>    def _is_valid_custom_code(self, code: int) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u9a8c\u8bc1\u81ea\u5b9a\u4e49\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        # \u68c0\u67e5\u662f\u5426\u5728\u5141\u8bb8\u8303\u56f4\u5185<br \/>\n        allowed_ranges &#061; [<br \/>\n            (420, 429),  # \u5b9e\u9a8c\u6027<br \/>\n            (450, 499),  # \u4e1a\u52a1\u7279\u5b9a<br \/>\n            (520, 599)   # \u7cfb\u7edf\u6269\u5c55<br \/>\n        ]<\/p>\n<p>        for start, end in allowed_ranges:<br \/>\n            if start &lt;&#061; code &lt;&#061; end:<br \/>\n                return True<\/p>\n<p>        return False<\/p>\n<p>    def _has_sensitive_information(self, response: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u654f\u611f\u4fe1\u606f&#034;&#034;&#034;<br \/>\n        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        body_str &#061; str(response.get(&#039;body&#039;, &#039;&#039;))<br \/>\n        sensitive_indicators &#061; [<br \/>\n            &#039;stack trace&#039;, &#039;password&#039;, &#039;secret&#039;,<br \/>\n            &#039;database&#039;, &#039;query:&#039;, &#039;exception at&#039;<br \/>\n        ]<\/p>\n<p>        for indicator in sensitive_indicators:<br \/>\n            if indicator in body_str.lower():<br \/>\n                return True<\/p>\n<p>        return False<\/p>\n<p>    def _sanitize_response(self, response: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u6e05\u7406\u54cd\u5e94&#034;&#034;&#034;<br \/>\n        sanitized &#061; response.copy()<\/p>\n<p>        if &#039;body&#039; in sanitized:<br \/>\n            body &#061; sanitized[&#039;body&#039;]<br \/>\n            if isinstance(body, dict) and &#039;error&#039; in body:<br \/>\n                # \u53ea\u4fdd\u7559\u57fa\u672c\u9519\u8bef\u4fe1\u606f<br \/>\n                sanitized[&#039;body&#039;] &#061; {<br \/>\n                    &#039;error&#039;: body[&#039;error&#039;],<br \/>\n                    &#039;code&#039;: body.get(&#039;code&#039;, &#039;UNKNOWN&#039;)<br \/>\n                }<\/p>\n<p>        return sanitized<\/p>\n<p>class RateLimitingLayer(SecurityLayer):<br \/>\n    &#034;&#034;&#034;\u901f\u7387\u9650\u5236\u5c42&#034;&#034;&#034;<\/p>\n<p>    def __init__(self, config: SecurityLayerConfig):<br \/>\n        super().__init__(config)<br \/>\n        self.request_counts &#061; {}<\/p>\n<p>    async def inspect_request(self, request: Dict) -&gt; Optional[Dict]:<br \/>\n        client_id &#061; request.get(&#039;client_id&#039;, &#039;unknown&#039;)<br \/>\n        endpoint &#061; request.get(&#039;path&#039;, &#039;&#039;)<\/p>\n<p>        # \u68c0\u67e5\u901f\u7387\u9650\u5236<br \/>\n        key &#061; f&#034;{client_id}:{endpoint}&#034;<br \/>\n        current_count &#061; self.request_counts.get(key, 0)<\/p>\n<p>        # \u4e0d\u540c\u7aef\u70b9\u7684\u4e0d\u540c\u9650\u5236<br \/>\n        limits &#061; self._get_limits(endpoint)<\/p>\n<p>        if current_count &gt;&#061; limits[&#039;requests_per_minute&#039;]:<br \/>\n            return {<br \/>\n                &#039;layer&#039;: self.config.name,<br \/>\n                &#039;action&#039;: &#039;BLOCK&#039;,<br \/>\n                &#039;response&#039;: {<br \/>\n                    &#039;status_code&#039;: 429,<br \/>\n                    &#039;body&#039;: {&#039;error&#039;: &#039;Rate limit exceeded&#039;},<br \/>\n                    &#039;headers&#039;: {&#039;Retry-After&#039;: str(limits[&#039;retry_after&#039;])}<br \/>\n                },<br \/>\n                &#039;reason&#039;: f&#039;Rate limit exceeded for {key}&#039;<br \/>\n            }<\/p>\n<p>        # \u66f4\u65b0\u8ba1\u6570<br \/>\n        self.request_counts[key] &#061; current_count &#043; 1<\/p>\n<p>        # \u5b9a\u671f\u6e05\u7406<br \/>\n        await self._cleanup_counts()<\/p>\n<p>        return None<\/p>\n<p>    def _get_limits(self, endpoint: str) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u7aef\u70b9\u9650\u5236&#034;&#034;&#034;<br \/>\n        # \u6839\u636e\u4e0d\u540c\u7aef\u70b9\u8bbe\u7f6e\u4e0d\u540c\u9650\u5236<br \/>\n        if &#039;\/api\/auth\/&#039; in endpoint:<br \/>\n            return {<br \/>\n                &#039;requests_per_minute&#039;: 10,<br \/>\n                &#039;retry_after&#039;: 60<br \/>\n            }<br \/>\n        elif &#039;\/api\/admin\/&#039; in endpoint:<br \/>\n            return {<br \/>\n                &#039;requests_per_minute&#039;: 30,<br \/>\n                &#039;retry_after&#039;: 30<br \/>\n            }<br \/>\n        else:<br \/>\n            return {<br \/>\n                &#039;requests_per_minute&#039;: 100,<br \/>\n                &#039;retry_after&#039;: 10<br \/>\n            }<\/p>\n<p>    async def _cleanup_counts(self):<br \/>\n        &#034;&#034;&#034;\u6e05\u7406\u8ba1\u6570&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u6709\u57fa\u4e8e\u65f6\u95f4\u7684\u6e05\u7406\u903b\u8f91<br \/>\n        pass<\/p>\n<p>class AnomalyDetectionLayer(SecurityLayer):<br \/>\n    &#034;&#034;&#034;\u5f02\u5e38\u68c0\u6d4b\u5c42&#034;&#034;&#034;<\/p>\n<p>    def __init__(self, config: SecurityLayerConfig):<br \/>\n        super().__init__(config)<br \/>\n        self.pattern_detector &#061; PatternDetector()<\/p>\n<p>    async def inspect_response(self,<br \/>\n                              request: Dict,<br \/>\n                              response: Dict) -&gt; Optional[Dict]:<br \/>\n        # \u68c0\u6d4b\u5f02\u5e38\u6a21\u5f0f<br \/>\n        anomaly &#061; await self.pattern_detector.detect(<br \/>\n            request, response<br \/>\n        )<\/p>\n<p>        if anomaly:<br \/>\n            return {<br \/>\n                &#039;layer&#039;: self.config.name,<br \/>\n                &#039;action&#039;: &#039;LOG&#039;,<br \/>\n                &#039;log_level&#039;: &#039;WARNING&#039;,<br \/>\n                &#039;anomaly&#039;: anomaly,<br \/>\n                &#039;reason&#039;: &#039;Anomalous pattern detected&#039;<br \/>\n            }<\/p>\n<p>        return None<\/p>\n<p>class PatternDetector:<br \/>\n    &#034;&#034;&#034;\u6a21\u5f0f\u68c0\u6d4b\u5668&#034;&#034;&#034;<\/p>\n<p>    async def detect(self, request: Dict, response: Dict) -&gt; Optional[Dict]:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u5f02\u5e38\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        status_code &#061; response.get(&#039;status_code&#039;)<br \/>\n        endpoint &#061; request.get(&#039;path&#039;)<\/p>\n<p>        # 1. \u72b6\u6001\u7801\u679a\u4e3e\u68c0\u6d4b<br \/>\n        if await self._detect_status_enumeration(request, status_code):<br \/>\n            return {<br \/>\n                &#039;type&#039;: &#039;STATUS_CODE_ENUMERATION&#039;,<br \/>\n                &#039;confidence&#039;: 0.8,<br \/>\n                &#039;description&#039;: &#039;Possible status code enumeration attack&#039;<br \/>\n            }<\/p>\n<p>        # 2. \u9519\u8bef\u7387\u7a81\u589e\u68c0\u6d4b<br \/>\n        if await self._detect_error_spike(endpoint, status_code):<br \/>\n            return {<br \/>\n                &#039;type&#039;: &#039;ERROR_RATE_SPIKE&#039;,<br \/>\n                &#039;confidence&#039;: 0.7,<br \/>\n                &#039;description&#039;: &#039;Sudden increase in error responses&#039;<br \/>\n            }<\/p>\n<p>        # 3. \u4e0d\u5bfb\u5e38\u7684\u6210\u529f\u6a21\u5f0f<br \/>\n        if await self._detect_unusual_success(request, response):<br \/>\n            return {<br \/>\n                &#039;type&#039;: &#039;UNUSUAL_SUCCESS_PATTERN&#039;,<br \/>\n                &#039;confidence&#039;: 0.6,<br \/>\n                &#039;description&#039;: &#039;Unusual pattern in successful responses&#039;<br \/>\n            }<\/p>\n<p>        return None<\/p>\n<p>    async def _detect_status_enumeration(self,<br \/>\n                                       request: Dict,<br \/>\n                                       status_code: int) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u72b6\u6001\u7801\u679a\u4e3e&#034;&#034;&#034;<br \/>\n        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        client_id &#061; request.get(&#039;client_id&#039;)<\/p>\n<p>        # \u68c0\u67e5\u77ed\u65f6\u95f4\u5185\u5c1d\u8bd5\u7684\u4e0d\u540c\u72b6\u6001\u7801\u6570\u91cf<br \/>\n        # \u5b9e\u9645\u4e2d\u4f1a\u67e5\u8be2\u5386\u53f2\u6570\u636e<\/p>\n<p>        return False<\/p>\n<p>    async def _detect_error_spike(self,<br \/>\n                                 endpoint: str,<br \/>\n                                 status_code: int) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u9519\u8bef\u7387\u7a81\u589e&#034;&#034;&#034;<br \/>\n        # \u68c0\u67e5\u7279\u5b9a\u7aef\u70b9\u7684\u9519\u8bef\u7387<\/p>\n<p>        return False<\/p>\n<p>    async def _detect_unusual_success(self,<br \/>\n                                     request: Dict,<br \/>\n                                     response: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u4e0d\u5bfb\u5e38\u7684\u6210\u529f\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        # \u68c0\u67e5\u4e0d\u5bfb\u5e38\u7684\u54cd\u5e94\u6a21\u5f0f<\/p>\n<p>        return False<\/p>\n<p>class SecurityOrchestrator:<br \/>\n    &#034;&#034;&#034;\u5b89\u5168\u7f16\u6392\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self, layers: List[SecurityLayer]):<br \/>\n        # \u6309\u4f18\u5148\u7ea7\u6392\u5e8f<br \/>\n        self.layers &#061; sorted(layers, key&#061;lambda x: x.config.priority)<\/p>\n<p>    async def process_request(self, request: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u5904\u7406\u8bf7\u6c42&#xff08;\u6df1\u5ea6\u9632\u5fa1&#xff09;&#034;&#034;&#034;<br \/>\n        current_request &#061; request.copy()<br \/>\n        current_response &#061; None<\/p>\n<p>        # \u8bf7\u6c42\u9636\u6bb5\u68c0\u67e5<br \/>\n        for layer in self.layers:<br \/>\n            if not layer.config.enabled:<br \/>\n                continue<\/p>\n<p>            try:<br \/>\n                result &#061; await layer.inspect_request(current_request)<\/p>\n<p>                if result:<br \/>\n                    if result[&#039;action&#039;] &#061;&#061; &#039;BLOCK&#039;:<br \/>\n                        # \u76f4\u63a5\u8fd4\u56de\u62e6\u622a\u54cd\u5e94<br \/>\n                        return result[&#039;response&#039;]<br \/>\n                    elif result[&#039;action&#039;] &#061;&#061; &#039;MODIFY&#039;:<br \/>\n                        # \u4fee\u6539\u8bf7\u6c42<br \/>\n                        current_request.update(result.get(&#039;modified_request&#039;, {}))<\/p>\n<p>                    # \u8bb0\u5f55\u5b89\u5168\u4e8b\u4ef6<br \/>\n                    await self._log_security_event(result)<\/p>\n<p>            except Exception as e:<br \/>\n                if layer.config.fail_open:<br \/>\n                    # \u5931\u8d25\u65f6\u653e\u884c<br \/>\n                    continue<br \/>\n                else:<br \/>\n                    # \u5931\u8d25\u65f6\u963b\u65ad<br \/>\n                    return {<br \/>\n                        &#039;status_code&#039;: 500,<br \/>\n                        &#039;body&#039;: {&#039;error&#039;: &#039;Security check failed&#039;},<br \/>\n                        &#039;headers&#039;: {}<br \/>\n                    }<\/p>\n<p>        # \u5904\u7406\u4e1a\u52a1\u903b\u8f91&#xff08;\u6a21\u62df&#xff09;<br \/>\n        current_response &#061; await self._process_business_logic(current_request)<\/p>\n<p>        # \u54cd\u5e94\u9636\u6bb5\u68c0\u67e5<br \/>\n        for layer in self.layers:<br \/>\n            if not layer.config.enabled:<br \/>\n                continue<\/p>\n<p>            try:<br \/>\n                result &#061; await layer.inspect_response(<br \/>\n                    current_request, current_response<br \/>\n                )<\/p>\n<p>                if result:<br \/>\n                    if result[&#039;action&#039;] &#061;&#061; &#039;MODIFY&#039;:<br \/>\n                        # \u4fee\u6539\u54cd\u5e94<br \/>\n                        current_response &#061; result[&#039;new_response&#039;]<br \/>\n                    elif result[&#039;action&#039;] &#061;&#061; &#039;SANITIZE&#039;:<br \/>\n                        # \u6e05\u7406\u54cd\u5e94<br \/>\n                        current_response &#061; result[&#039;sanitized_response&#039;]<\/p>\n<p>                    # \u8bb0\u5f55\u5b89\u5168\u4e8b\u4ef6<br \/>\n                    await self._log_security_event(result)<\/p>\n<p>            except Exception as e:<br \/>\n                if not layer.config.fail_open:<br \/>\n                    # \u5931\u8d25\u65f6\u8fd4\u56de\u5b89\u5168\u54cd\u5e94<br \/>\n                    current_response &#061; {<br \/>\n                        &#039;status_code&#039;: 500,<br \/>\n                        &#039;body&#039;: {&#039;error&#039;: &#039;Security processing failed&#039;},<br \/>\n                        &#039;headers&#039;: {}<br \/>\n                    }<\/p>\n<p>        return current_response<\/p>\n<p>    async def _process_business_logic(self, request: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u5904\u7406\u4e1a\u52a1\u903b\u8f91&#xff08;\u6a21\u62df&#xff09;&#034;&#034;&#034;<br \/>\n        # \u8fd9\u91cc\u5e94\u8be5\u662f\u5b9e\u9645\u7684\u4e1a\u52a1\u5904\u7406<br \/>\n        return {<br \/>\n            &#039;status_code&#039;: 200,<br \/>\n            &#039;body&#039;: {&#039;result&#039;: &#039;success&#039;},<br \/>\n            &#039;headers&#039;: {&#039;Content-Type&#039;: &#039;application\/json&#039;}<br \/>\n        }<\/p>\n<p>    async def _log_security_event(self, event: Dict):<br \/>\n        &#034;&#034;&#034;\u8bb0\u5f55\u5b89\u5168\u4e8b\u4ef6&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u8bb0\u5f55\u5230\u5b89\u5168\u4fe1\u606f\u4e8b\u4ef6\u7ba1\u7406&#xff08;SIEM&#xff09;\u7cfb\u7edf<br \/>\n        print(f&#034;Security event: {event}&#034;)<\/p>\n<p># \u914d\u7f6e\u548c\u4f7f\u7528\u793a\u4f8b<br \/>\ndef create_security_orchestrator() -&gt; SecurityOrchestrator:<br \/>\n    &#034;&#034;&#034;\u521b\u5efa\u5b89\u5168\u7f16\u6392\u5668&#034;&#034;&#034;<br \/>\n    layers &#061; [<br \/>\n        RateLimitingLayer(SecurityLayerConfig(<br \/>\n            name&#061;&#034;rate_limiting&#034;,<br \/>\n            enabled&#061;True,<br \/>\n            priority&#061;10,<br \/>\n            fail_open&#061;False<br \/>\n        )),<br \/>\n        StatusCodeValidationLayer(SecurityLayerConfig(<br \/>\n            name&#061;&#034;status_code_validation&#034;,<br \/>\n            enabled&#061;True,<br \/>\n            priority&#061;20,<br \/>\n            fail_open&#061;True  # \u9a8c\u8bc1\u5931\u8d25\u65f6\u8fd4\u56de500&#xff0c;\u800c\u4e0d\u662f\u963b\u65ad<br \/>\n        )),<br \/>\n        AnomalyDetectionLayer(SecurityLayerConfig(<br \/>\n            name&#061;&#034;anomaly_detection&#034;,<br \/>\n            enabled&#061;True,<br \/>\n            priority&#061;30,<br \/>\n            fail_open&#061;True<br \/>\n        ))<br \/>\n    ]<\/p>\n<p>    return SecurityOrchestrator(layers)<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nasync def handle_http_request(request_data: Dict) -&gt; Dict:<br \/>\n    orchestrator &#061; create_security_orchestrator()<br \/>\n    return await orchestrator.process_request(request_data)<\/p>\n<h4>37.5 \u672a\u6765\u5b89\u5168\u8d8b\u52bf\u4e0e\u6311\u6218<\/h4>\n<h5>37.5.1 \u91cf\u5b50\u8ba1\u7b97\u5bf9\u5b89\u5168\u7684\u5f71\u54cd<\/h5>\n<p>python<\/p>\n<p># \u540e\u91cf\u5b50\u65f6\u4ee3\u7684\u72b6\u6001\u7801\u5b89\u5168\u8003\u8651<br \/>\nfrom typing import Dict, Any<br \/>\nimport hashlib<\/p>\n<p>class PostQuantumSecurity:<br \/>\n    &#034;&#034;&#034;\u540e\u91cf\u5b50\u5b89\u5168\u8003\u8651&#034;&#034;&#034;<\/p>\n<p>    &#064;staticmethod<br \/>\n    def quantum_resistant_status_codes() -&gt; Dict[int, str]:<br \/>\n        &#034;&#034;&#034;\u91cf\u5b50\u5b89\u5168\u7684\u72b6\u6001\u7801\u8bbe\u8ba1&#034;&#034;&#034;<br \/>\n        # \u5728\u672a\u6765&#xff0c;\u53ef\u80fd\u9700\u8981\u8003\u8651\u91cf\u5b50\u8ba1\u7b97\u5bf9\u5b89\u5168\u7684\u6311\u6218<\/p>\n<p>        return {<br \/>\n            # \u6807\u51c6\u72b6\u6001\u7801\u4fdd\u6301\u4e0d\u53d8<br \/>\n            400: &#034;Bad Request&#034;,<br \/>\n            401: &#034;Unauthorized&#034;,<br \/>\n            403: &#034;Forbidden&#034;,<br \/>\n            404: &#034;Not Found&#034;,<br \/>\n            500: &#034;Internal Server Error&#034;,<\/p>\n<p>            # \u65b0\u589e\u91cf\u5b50\u76f8\u5173\u72b6\u6001\u7801<br \/>\n            580: &#034;Quantum Security Required&#034;,<br \/>\n            581: &#034;Post-Quantum Algorithm Not Supported&#034;,<br \/>\n            582: &#034;Quantum Key Exchange Failed&#034;,<br \/>\n            583: &#034;Quantum Signature Verification Failed&#034;,<\/p>\n<p>            # \u91cf\u5b50\u8ba1\u7b97\u5f71\u54cd\u7684\u72b6\u6001\u7801<br \/>\n            590: &#034;Resource Exhausted (Quantum)&#034;,<br \/>\n            591: &#034;Computation Timeout (Quantum)&#034;,<br \/>\n            592: &#034;Quantum Resource Unavailable&#034;<br \/>\n        }<\/p>\n<p>    &#064;staticmethod<br \/>\n    def quantum_safe_error_response(error_code: int,<br \/>\n                                   details: Dict[str, Any]) -&gt; Dict[str, Any]:<br \/>\n        &#034;&#034;&#034;\u91cf\u5b50\u5b89\u5168\u7684\u9519\u8bef\u54cd\u5e94&#034;&#034;&#034;<br \/>\n        response &#061; {<br \/>\n            &#039;error&#039;: {<br \/>\n                &#039;code&#039;: error_code,<br \/>\n                &#039;message&#039;: PostQuantumSecurity.quantum_resistant_status_codes().get(<br \/>\n                    error_code, &#039;Unknown Error&#039;<br \/>\n                ),<br \/>\n                &#039;timestamp&#039;: int(time.time()),<br \/>\n                &#039;nonce&#039;: PostQuantumSecurity.generate_quantum_safe_nonce()<br \/>\n            }<br \/>\n        }<\/p>\n<p>        # \u6dfb\u52a0\u91cf\u5b50\u5b89\u5168\u7b7e\u540d<br \/>\n        response[&#039;signature&#039;] &#061; PostQuantumSecurity.quantum_safe_signature(<br \/>\n            response[&#039;error&#039;]<br \/>\n        )<\/p>\n<p>        return response<\/p>\n<p>    &#064;staticmethod<br \/>\n    def generate_quantum_safe_nonce() -&gt; str:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u91cf\u5b50\u5b89\u5168\u7684\u968f\u673a\u6570&#034;&#034;&#034;<br \/>\n        # \u4f7f\u7528\u91cf\u5b50\u5b89\u5168\u7684\u968f\u673a\u6570\u751f\u6210\u5668<br \/>\n        # \u5b9e\u9645\u4e2d\u53ef\u80fd\u4f7f\u7528\u4e13\u95e8\u7684\u786c\u4ef6<\/p>\n<p>        # \u8fd9\u91cc\u4f7f\u7528\u591a\u4e2a\u6e90\u7684\u7ec4\u5408<br \/>\n        import secrets<br \/>\n        import os<br \/>\n        import time<\/p>\n<p>        # \u7ec4\u5408\u591a\u4e2a\u71b5\u6e90<br \/>\n        entropy_sources &#061; [<br \/>\n            secrets.token_bytes(32),<br \/>\n            os.urandom(32),<br \/>\n            str(time.time_ns()).encode(),<br \/>\n            hashlib.sha512(str(os.getpid()).encode()).digest()<br \/>\n        ]<\/p>\n<p>        # \u7ec4\u5408\u5e76\u54c8\u5e0c<br \/>\n        combined &#061; b&#039;&#039;.join(entropy_sources)<br \/>\n        nonce &#061; hashlib.sha3_512(combined).hexdigest()<\/p>\n<p>        return nonce<\/p>\n<p>    &#064;staticmethod<br \/>\n    def quantum_safe_signature(data: Dict[str, Any]) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u91cf\u5b50\u5b89\u5168\u7b7e\u540d&#xff08;\u6982\u5ff5&#xff09;&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u4f7f\u7528\u540e\u91cf\u5b50\u5bc6\u7801\u5b66\u7b97\u6cd5<\/p>\n<p>        # \u793a\u4f8b&#xff1a;\u4f7f\u7528\u54c8\u5e0c-based\u7b7e\u540d&#xff08;\u5982XMSS, LMS&#xff09;<br \/>\n        import json<\/p>\n<p>        # \u5e8f\u5217\u5316\u6570\u636e<br \/>\n        data_str &#061; json.dumps(data, sort_keys&#061;True)<\/p>\n<p>        # \u4f7f\u7528\u6297\u91cf\u5b50\u54c8\u5e0c\u7b97\u6cd5<br \/>\n        # SHA-3 (Keccak) \u88ab\u8ba4\u4e3a\u5bf9\u91cf\u5b50\u653b\u51fb\u6709\u4e00\u5b9a\u62b5\u6297\u6027<br \/>\n        signature &#061; hashlib.sha3_512(data_str.encode()).hexdigest()<\/p>\n<p>        return signature<\/p>\n<p>    &#064;staticmethod<br \/>\n    def handle_quantum_computation_error() -&gt; Dict[str, Any]:<br \/>\n        &#034;&#034;&#034;\u5904\u7406\u91cf\u5b50\u8ba1\u7b97\u76f8\u5173\u7684\u9519\u8bef&#034;&#034;&#034;<br \/>\n        # \u5f53\u68c0\u6d4b\u5230\u53ef\u80fd\u7684\u91cf\u5b50\u8ba1\u7b97\u653b\u51fb\u65f6<\/p>\n<p>        return {<br \/>\n            &#039;status_code&#039;: 590,<br \/>\n            &#039;body&#039;: PostQuantumSecurity.quantum_safe_error_response(590, {<br \/>\n                &#039;description&#039;: &#039;Resource exhaustion possibly due to quantum computation&#039;,<br \/>\n                &#039;recommendation&#039;: &#039;Implement quantum-resistant algorithms&#039;,<br \/>\n                &#039;mitigation&#039;: &#039;Rate limiting and computational puzzles&#039;<br \/>\n            }),<br \/>\n            &#039;headers&#039;: {<br \/>\n                &#039;X-Quantum-Threat-Detected&#039;: &#039;true&#039;,<br \/>\n                &#039;Retry-After&#039;: &#039;3600&#039;,<br \/>\n                &#039;Content-Security-Policy&#039;: &#034;default-src &#039;self&#039;; upgrade-insecure-requests&#034;<br \/>\n            }<br \/>\n        }<\/p>\n<p>class QuantumThreatDetection:<br \/>\n    &#034;&#034;&#034;\u91cf\u5b50\u5a01\u80c1\u68c0\u6d4b&#034;&#034;&#034;<\/p>\n<p>    &#064;staticmethod<br \/>\n    def detect_quantum_patterns(request_pattern: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u53ef\u80fd\u7684\u91cf\u5b50\u8ba1\u7b97\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        # \u91cf\u5b50\u8ba1\u7b97\u673a\u53ef\u80fd\u5c55\u793a\u7684\u6a21\u5f0f&#xff1a;<br \/>\n        # 1. \u6781\u5feb\u7684\u8bf7\u6c42\u901f\u7387<br \/>\n        # 2. \u540c\u65f6\u89e3\u51b3\u591a\u4e2a\u8ba1\u7b97\u96be\u9898<br \/>\n        # 3. \u7834\u89e3\u4f20\u7edf\u52a0\u5bc6\u7684\u901f\u5ea6\u5f02\u5e38<\/p>\n<p>        suspicious_indicators &#061; 0<\/p>\n<p>        # \u68c0\u67e5\u8bf7\u6c42\u901f\u7387<br \/>\n        if request_pattern.get(&#039;requests_per_second&#039;, 0) &gt; 10000:<br \/>\n            suspicious_indicators &#043;&#061; 1<\/p>\n<p>        # \u68c0\u67e5\u8ba1\u7b97\u96be\u9898\u89e3\u51b3\u65f6\u95f4<br \/>\n        if request_pattern.get(&#039;puzzle_solve_time_ms&#039;, 9999) &lt; 10:<br \/>\n            suspicious_indicators &#043;&#061; 1<\/p>\n<p>        # \u68c0\u67e5\u52a0\u5bc6\u76f8\u5173\u6a21\u5f0f<br \/>\n        if request_pattern.get(&#039;crypto_operations&#039;, 0) &gt; 1000:<br \/>\n            suspicious_indicators &#043;&#061; 1<\/p>\n<p>        return suspicious_indicators &gt;&#061; 2<\/p>\n<p>    &#064;staticmethod<br \/>\n    def quantum_aware_rate_limiting(client_id: str) -&gt; Dict[str, Any]:<br \/>\n        &#034;&#034;&#034;\u91cf\u5b50\u611f\u77e5\u7684\u901f\u7387\u9650\u5236&#034;&#034;&#034;<br \/>\n        # \u5bf9\u53ef\u80fd\u7684\u91cf\u5b50\u8ba1\u7b97\u5b9e\u65bd\u66f4\u4e25\u683c\u7684\u9650\u5236<\/p>\n<p>        return {<br \/>\n            &#039;max_requests_per_second&#039;: 1,  # \u975e\u5e38\u4e25\u683c\u7684\u9650\u5236<br \/>\n            &#039;require_proof_of_work&#039;: True,<br \/>\n            &#039;proof_of_work_difficulty&#039;: &#039;HIGH&#039;,<br \/>\n            &#039;additional_authentication&#039;: True,<br \/>\n            &#039;quantum_resistant_challenge&#039;: True<br \/>\n        }<\/p>\n<h5>37.5.2 AI\u4e0e\u673a\u5668\u5b66\u4e60\u5728\u5b89\u5168\u4e2d\u7684\u5e94\u7528<\/h5>\n<p>python<\/p>\n<p># AI\u589e\u5f3a\u7684\u72b6\u6001\u7801\u5b89\u5168<br \/>\nfrom typing import List, Dict, Any<br \/>\nimport numpy as np<br \/>\nfrom dataclasses import dataclass<br \/>\nfrom datetime import datetime<\/p>\n<p>&#064;dataclass<br \/>\nclass AISecurityModel:<br \/>\n    &#034;&#034;&#034;AI\u5b89\u5168\u6a21\u578b\u914d\u7f6e&#034;&#034;&#034;<br \/>\n    model_type: str  # &#039;anomaly_detection&#039;, &#039;threat_classification&#039;, &#039;predictive&#039;<br \/>\n    training_data_size: int<br \/>\n    update_frequency: str  # &#039;realtime&#039;, &#039;daily&#039;, &#039;weekly&#039;<br \/>\n    confidence_threshold: float &#061; 0.8<\/p>\n<p>class AIEnhancedSecurity:<br \/>\n    &#034;&#034;&#034;AI\u589e\u5f3a\u7684\u5b89\u5168\u7cfb\u7edf&#034;&#034;&#034;<\/p>\n<p>    def __init__(self, model_config: AISecurityModel):<br \/>\n        self.model_config &#061; model_config<br \/>\n        self.models &#061; self._initialize_models()<br \/>\n        self.training_data &#061; []<\/p>\n<p>    def _initialize_models(self) -&gt; Dict[str, Any]:<br \/>\n        &#034;&#034;&#034;\u521d\u59cb\u5316AI\u6a21\u578b&#034;&#034;&#034;<br \/>\n        models &#061; {}<\/p>\n<p>        if self.model_config.model_type &#061;&#061; &#039;anomaly_detection&#039;:<br \/>\n            models[&#039;anomaly&#039;] &#061; self._create_anomaly_detection_model()<\/p>\n<p>        if self.model_config.model_type &#061;&#061; &#039;threat_classification&#039;:<br \/>\n            models[&#039;classification&#039;] &#061; self._create_threat_classification_model()<\/p>\n<p>        if self.model_config.model_type &#061;&#061; &#039;predictive&#039;:<br \/>\n            models[&#039;predictive&#039;] &#061; self._create_predictive_model()<\/p>\n<p>        return models<\/p>\n<p>    def _create_anomaly_detection_model(self):<br \/>\n        &#034;&#034;&#034;\u521b\u5efa\u5f02\u5e38\u68c0\u6d4b\u6a21\u578b&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u4f7f\u7528scikit-learn\u3001TensorFlow\u7b49<\/p>\n<p>        class AnomalyDetectionModel:<br \/>\n            def __init__(self):<br \/>\n                self.normal_patterns &#061; []<br \/>\n                self.threshold &#061; 0.1<\/p>\n<p>            def fit(self, data: List[Dict]):<br \/>\n                &#034;&#034;&#034;\u8bad\u7ec3\u6a21\u578b&#034;&#034;&#034;<br \/>\n                # \u5b66\u4e60\u6b63\u5e38\u6a21\u5f0f<br \/>\n                self.normal_patterns &#061; self._extract_patterns(data)<\/p>\n<p>            def predict(self, features: Dict) -&gt; float:<br \/>\n                &#034;&#034;&#034;\u9884\u6d4b\u5f02\u5e38\u5206\u6570&#034;&#034;&#034;<br \/>\n                # \u8ba1\u7b97\u4e0e\u6b63\u5e38\u6a21\u5f0f\u7684\u504f\u5dee<br \/>\n                deviation &#061; self._calculate_deviation(features)<br \/>\n                return deviation<\/p>\n<p>            def _extract_patterns(self, data: List[Dict]) -&gt; List[Dict]:<br \/>\n                &#034;&#034;&#034;\u63d0\u53d6\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n                # \u7b80\u5316\u5b9e\u73b0<br \/>\n                return []<\/p>\n<p>            def _calculate_deviation(self, features: Dict) -&gt; float:<br \/>\n                &#034;&#034;&#034;\u8ba1\u7b97\u504f\u5dee&#034;&#034;&#034;<br \/>\n                # \u7b80\u5316\u5b9e\u73b0<br \/>\n                return 0.0<\/p>\n<p>        return AnomalyDetectionModel()<\/p>\n<p>    def analyze_status_code_pattern(self,<br \/>\n                                  request: Dict,<br \/>\n                                  response: Dict) -&gt; Dict[str, Any]:<br \/>\n        &#034;&#034;&#034;\u5206\u6790\u72b6\u6001\u7801\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        features &#061; self._extract_features(request, response)<\/p>\n<p>        if &#039;anomaly&#039; in self.models:<br \/>\n            anomaly_score &#061; self.models[&#039;anomaly&#039;].predict(features)<\/p>\n<p>            if anomaly_score &gt; self.model_config.confidence_threshold:<br \/>\n                return {<br \/>\n                    &#039;detection&#039;: &#039;ANOMALY&#039;,<br \/>\n                    &#039;score&#039;: anomaly_score,<br \/>\n                    &#039;features&#039;: features,<br \/>\n                    &#039;recommendation&#039;: &#039;Investigate this pattern&#039;<br \/>\n                }<\/p>\n<p>        if &#039;classification&#039; in self.models:<br \/>\n            threat_class &#061; self.models[&#039;classification&#039;].predict(features)<\/p>\n<p>            if threat_class !&#061; &#039;NORMAL&#039;:<br \/>\n                return {<br \/>\n                    &#039;detection&#039;: &#039;THREAT&#039;,<br \/>\n                    &#039;class&#039;: threat_class,<br \/>\n                    &#039;confidence&#039;: 0.9,<br \/>\n                    &#039;features&#039;: features,<br \/>\n                    &#039;action&#039;: self._get_action_for_threat(threat_class)<br \/>\n                }<\/p>\n<p>        return {&#039;detection&#039;: &#039;NORMAL&#039;}<\/p>\n<p>    def _extract_features(self, request: Dict, response: Dict) -&gt; Dict[str, Any]:<br \/>\n        &#034;&#034;&#034;\u63d0\u53d6\u7279\u5f81&#034;&#034;&#034;<br \/>\n        status_code &#061; response.get(&#039;status_code&#039;, 0)<\/p>\n<p>        features &#061; {<br \/>\n            &#039;status_code&#039;: status_code,<br \/>\n            &#039;status_code_category&#039;: self._categorize_status_code(status_code),<br \/>\n            &#039;response_time_ms&#039;: response.get(&#039;response_time&#039;, 0),<br \/>\n            &#039;request_size_bytes&#039;: len(str(request)),<br \/>\n            &#039;response_size_bytes&#039;: len(str(response.get(&#039;body&#039;, &#039;&#039;))),<br \/>\n            &#039;timestamp_hour&#039;: datetime.now().hour,<br \/>\n            &#039;endpoint_complexity&#039;: self._calculate_endpoint_complexity(<br \/>\n                request.get(&#039;path&#039;, &#039;&#039;)<br \/>\n            ),<br \/>\n            &#039;client_reputation&#039;: self._get_client_reputation(<br \/>\n                request.get(&#039;client_id&#039;, &#039;&#039;)<br \/>\n            )<br \/>\n        }<\/p>\n<p>        # \u6dfb\u52a0\u65f6\u5e8f\u7279\u5f81<br \/>\n        if hasattr(self, &#039;previous_request&#039;):<br \/>\n            time_diff &#061; datetime.now() &#8211; self.previous_request[&#039;timestamp&#039;]<br \/>\n            features[&#039;time_since_last_request&#039;] &#061; time_diff.total_seconds()<br \/>\n            features[&#039;previous_status_code&#039;] &#061; self.previous_request.get(&#039;status_code&#039;)<\/p>\n<p>        self.previous_request &#061; {<br \/>\n            &#039;timestamp&#039;: datetime.now(),<br \/>\n            &#039;status_code&#039;: status_code<br \/>\n        }<\/p>\n<p>        return features<\/p>\n<p>    def _categorize_status_code(self, code: int) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u5206\u7c7b\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        if 100 &lt;&#061; code &lt;&#061; 199:<br \/>\n            return &#039;INFORMATIONAL&#039;<br \/>\n        elif 200 &lt;&#061; code &lt;&#061; 299:<br \/>\n            return &#039;SUCCESS&#039;<br \/>\n        elif 300 &lt;&#061; code &lt;&#061; 399:<br \/>\n            return &#039;REDIRECTION&#039;<br \/>\n        elif 400 &lt;&#061; code &lt;&#061; 499:<br \/>\n            return &#039;CLIENT_ERROR&#039;<br \/>\n        elif 500 &lt;&#061; code &lt;&#061; 599:<br \/>\n            return &#039;SERVER_ERROR&#039;<br \/>\n        else:<br \/>\n            return &#039;UNKNOWN&#039;<\/p>\n<p>    def _calculate_endpoint_complexity(self, endpoint: str) -&gt; float:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u7aef\u70b9\u590d\u6742\u5ea6&#034;&#034;&#034;<br \/>\n        # \u57fa\u4e8e\u8def\u5f84\u957f\u5ea6\u3001\u53c2\u6570\u6570\u91cf\u7b49<br \/>\n        complexity &#061; len(endpoint.split(&#039;\/&#039;))<\/p>\n<p>        if &#039;?&#039; in endpoint:<br \/>\n            complexity &#043;&#061; len(endpoint.split(&#039;?&#039;)[1].split(&#039;&amp;&#039;))<\/p>\n<p>        return float(complexity)<\/p>\n<p>    def _get_client_reputation(self, client_id: str) -&gt; float:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u5ba2\u6237\u7aef\u4fe1\u8a89\u5206&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u67e5\u8be2\u4fe1\u8a89\u6570\u636e\u5e93<\/p>\n<p>        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        return 0.5  # \u4e2d\u6027<\/p>\n<p>    def _get_action_for_threat(self, threat_class: str) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u6839\u636e\u5a01\u80c1\u7c7b\u522b\u83b7\u53d6\u884c\u52a8&#034;&#034;&#034;<br \/>\n        actions &#061; {<br \/>\n            &#039;ENUMERATION&#039;: &#039;BLOCK&#039;,<br \/>\n            &#039;INJECTION&#039;: &#039;BLOCK&#039;,<br \/>\n            &#039;DOS&#039;: &#039;RATE_LIMIT&#039;,<br \/>\n            &#039;RECONNAISSANCE&#039;: &#039;LOG&#039;,<br \/>\n            &#039;EXPLOITATION&#039;: &#039;BLOCK_AND_ALERT&#039;<br \/>\n        }<\/p>\n<p>        return actions.get(threat_class, &#039;LOG&#039;)<\/p>\n<p>    def update_models(self, new_data: List[Dict]):<br \/>\n        &#034;&#034;&#034;\u66f4\u65b0AI\u6a21\u578b&#034;&#034;&#034;<br \/>\n        self.training_data.extend(new_data)<\/p>\n<p>        if len(self.training_data) &gt; self.model_config.training_data_size:<br \/>\n            # \u91cd\u65b0\u8bad\u7ec3\u6a21\u578b<br \/>\n            for model in self.models.values():<br \/>\n                if hasattr(model, &#039;fit&#039;):<br \/>\n                    model.fit(self.training_data)<\/p>\n<p>            # \u4fdd\u7559\u6700\u65b0\u6570\u636e<br \/>\n            self.training_data &#061; self.training_data[<br \/>\n                -self.model_config.training_data_size:<br \/>\n            ]<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nai_security &#061; AIEnhancedSecurity(<br \/>\n    AISecurityModel(<br \/>\n        model_type&#061;&#039;anomaly_detection&#039;,<br \/>\n        training_data_size&#061;10000,<br \/>\n        update_frequency&#061;&#039;daily&#039;,<br \/>\n        confidence_threshold&#061;0.85<br \/>\n    )<br \/>\n)<\/p>\n<p># \u6a21\u62df\u5904\u7406\u8bf7\u6c42<br \/>\ndef process_request_with_ai(request: Dict, response: Dict) -&gt; Dict:<br \/>\n    # AI\u5206\u6790<br \/>\n    ai_result &#061; ai_security.analyze_status_code_pattern(request, response)<\/p>\n<p>    if ai_result[&#039;detection&#039;] !&#061; &#039;NORMAL&#039;:<br \/>\n        # \u91c7\u53d6\u5b89\u5168\u63aa\u65bd<br \/>\n        if ai_result.get(&#039;action&#039;) &#061;&#061; &#039;BLOCK&#039;:<br \/>\n            return {<br \/>\n                &#039;status_code&#039;: 403,<br \/>\n                &#039;body&#039;: {&#039;error&#039;: &#039;Request blocked by security system&#039;},<br \/>\n                &#039;headers&#039;: {<br \/>\n                    &#039;X-Security-Action&#039;: &#039;BLOCKED&#039;,<br \/>\n                    &#039;X-Threat-Type&#039;: ai_result.get(&#039;class&#039;, &#039;UNKNOWN&#039;)<br \/>\n                }<br \/>\n            }<br \/>\n        elif ai_result.get(&#039;action&#039;) &#061;&#061; &#039;RATE_LIMIT&#039;:<br \/>\n            return {<br \/>\n                &#039;status_code&#039;: 429,<br \/>\n                &#039;body&#039;: {&#039;error&#039;: &#039;Rate limit applied&#039;},<br \/>\n                &#039;headers&#039;: {&#039;Retry-After&#039;: &#039;60&#039;}<br \/>\n            }<\/p>\n<p>    # \u6b63\u5e38\u5904\u7406<br \/>\n    return response<\/p>\n<h4>37.6 \u603b\u7ed3<\/h4>\n<p>\u72b6\u6001\u7801\u5b89\u5168\u662fWeb\u5e94\u7528\u5b89\u5168\u7684\u91cd\u8981\u7ec4\u6210\u90e8\u5206&#xff0c;\u6d89\u53ca\u591a\u4e2a\u65b9\u9762&#xff1a;<\/p>\n<p>\u4e3b\u8981\u98ce\u9669&#xff1a;<\/p>\n<li>\n<p>\u4fe1\u606f\u6cc4\u9732 &#8211; \u901a\u8fc7\u72b6\u6001\u7801\u5dee\u5f02\u66b4\u9732\u7cfb\u7edf\u4fe1\u606f<\/p>\n<\/li>\n<li>\n<p>\u7528\u6237\u679a\u4e3e &#8211; \u5229\u7528\u8ba4\u8bc1\u54cd\u5e94\u7684\u5dee\u5f02<\/p>\n<\/li>\n<li>\n<p>\u6307\u7eb9\u8bc6\u522b &#8211; \u901a\u8fc7\u9519\u8bef\u54cd\u5e94\u7279\u5f81\u8bc6\u522b\u7cfb\u7edf<\/p>\n<\/li>\n<li>\n<p>\u6ce8\u5165\u653b\u51fb &#8211; \u5c1d\u8bd5\u64cd\u7eb5\u72b6\u6001\u7801<\/p>\n<\/li>\n<p>\u9632\u5fa1\u7b56\u7565&#xff1a;<\/p>\n<li>\n<p>\u6807\u51c6\u5316\u54cd\u5e94\u00a0&#8211; \u7edf\u4e00\u9519\u8bef\u54cd\u5e94\u683c\u5f0f\u548c\u5185\u5bb9<\/p>\n<\/li>\n<li>\n<p>\u901f\u7387\u9650\u5236\u00a0&#8211; \u9632\u6b62\u679a\u4e3e\u548c\u66b4\u529b\u653b\u51fb<\/p>\n<\/li>\n<li>\n<p>\u8f93\u5165\u9a8c\u8bc1\u00a0&#8211; \u9a8c\u8bc1\u6240\u6709\u8f93\u5165&#xff0c;\u5305\u62ec\u72b6\u6001\u7801<\/p>\n<\/li>\n<li>\n<p>\u5b89\u5168\u65e5\u5fd7\u00a0&#8211; \u8bb0\u5f55\u5b89\u5168\u4e8b\u4ef6\u4f46\u4e0d\u66b4\u9732\u654f\u611f\u4fe1\u606f<\/p>\n<\/li>\n<li>\n<p>\u6df1\u5ea6\u9632\u5fa1\u00a0&#8211; \u591a\u5c42\u5b89\u5168\u9632\u62a4<\/p>\n<\/li>\n<p>\u6700\u4f73\u5b9e\u8df5&#xff1a;<\/p>\n<li>\n<p>\u751f\u4ea7\u73af\u5883\u4f7f\u7528\u901a\u7528\u9519\u8bef\u6d88\u606f<\/p>\n<\/li>\n<li>\n<p>\u5b9e\u73b0\u9002\u5f53\u7684\u901f\u7387\u9650\u5236<\/p>\n<\/li>\n<li>\n<p>\u5b9a\u671f\u5ba1\u8ba1\u72b6\u6001\u7801\u4f7f\u7528<\/p>\n<\/li>\n<li>\n<p>\u76d1\u63a7\u5f02\u5e38\u6a21\u5f0f<\/p>\n<\/li>\n<li>\n<p>\u4fdd\u6301\u5b89\u5168\u66f4\u65b0<\/p>\n<\/li>\n<p>\u672a\u6765\u8d8b\u52bf&#xff1a;<\/p>\n<li>\n<p>AI\u548c\u673a\u5668\u5b66\u4e60\u5728\u5a01\u80c1\u68c0\u6d4b\u4e2d\u7684\u5e94\u7528<\/p>\n<\/li>\n<li>\n<p>\u91cf\u5b50\u5b89\u5168\u5bc6\u7801\u5b66\u7684\u9700\u6c42\u589e\u957f<\/p>\n<\/li>\n<li>\n<p>\u66f4\u667a\u80fd\u7684\u81ea\u52a8\u9632\u62a4\u7cfb\u7edf<\/p>\n<\/li>\n<li>\n<p>\u96f6\u4fe1\u4efb\u67b6\u6784\u7684\u666e\u53ca<\/p>\n<\/li>\n<p>\u901a\u8fc7\u7efc\u5408\u5e94\u7528\u8fd9\u4e9b\u7b56\u7565\u548c\u5b9e\u8df5&#xff0c;\u53ef\u4ee5\u663e\u8457\u63d0\u9ad8Web\u5e94\u7528\u7684\u5b89\u5168\u6027&#xff0c;\u4fdd\u62a4\u7528\u6237\u6570\u636e\u548c\u7cfb\u7edf\u8d44\u6e90\u3002<\/p>\n<hr \/>\n<h3>\u7b2c38\u7ae0&#xff1a;\u76d1\u63a7\u4e0e\u65e5\u5fd7\u4e2d\u7684\u72b6\u6001\u7801\u5206\u6790<\/h3>\n<h4>38.1 \u72b6\u6001\u7801\u76d1\u63a7\u4f53\u7cfb\u67b6\u6784<\/h4>\n<h5>38.1.1 \u591a\u7ef4\u5ea6\u76d1\u63a7\u4f53\u7cfb<\/h5>\n<p>python<\/p>\n<p># \u72b6\u6001\u7801\u76d1\u63a7\u7cfb\u7edf\u67b6\u6784<br \/>\nfrom typing import Dict, List, Optional, Tuple<br \/>\nfrom dataclasses import dataclass, asdict<br \/>\nfrom datetime import datetime, timedelta<br \/>\nfrom enum import Enum<br \/>\nimport asyncio<br \/>\nimport statistics<\/p>\n<p>class MetricDimension(Enum):<br \/>\n    &#034;&#034;&#034;\u76d1\u63a7\u7ef4\u5ea6\u679a\u4e3e&#034;&#034;&#034;<br \/>\n    STATUS_CODE &#061; &#034;status_code&#034;<br \/>\n    ENDPOINT &#061; &#034;endpoint&#034;<br \/>\n    METHOD &#061; &#034;method&#034;<br \/>\n    CLIENT &#061; &#034;client&#034;<br \/>\n    TIME &#061; &#034;time&#034;<br \/>\n    REGION &#061; &#034;region&#034;<br \/>\n    SERVICE &#061; &#034;service&#034;<\/p>\n<p>&#064;dataclass<br \/>\nclass StatusCodeMetric:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u6307\u6807\u6570\u636e\u7ed3\u6784&#034;&#034;&#034;<br \/>\n    timestamp: datetime<br \/>\n    status_code: int<br \/>\n    endpoint: str<br \/>\n    method: str<br \/>\n    response_time_ms: float<br \/>\n    client_ip: str<br \/>\n    user_agent: str<br \/>\n    service_name: str<br \/>\n    region: str<br \/>\n    additional_tags: Dict[str, str]<\/p>\n<p>    &#064;property<br \/>\n    def is_success(self) -&gt; bool:<br \/>\n        return 200 &lt;&#061; self.status_code &lt; 300<\/p>\n<p>    &#064;property<br \/>\n    def is_client_error(self) -&gt; bool:<br \/>\n        return 400 &lt;&#061; self.status_code &lt; 500<\/p>\n<p>    &#064;property<br \/>\n    def is_server_error(self) -&gt; bool:<br \/>\n        return 500 &lt;&#061; self.status_code &lt; 600<\/p>\n<p>    &#064;property<br \/>\n    def status_category(self) -&gt; str:<br \/>\n        if self.is_success:<br \/>\n            return &#034;success&#034;<br \/>\n        elif self.is_client_error:<br \/>\n            return &#034;client_error&#034;<br \/>\n        elif self.is_server_error:<br \/>\n            return &#034;server_error&#034;<br \/>\n        else:<br \/>\n            return &#034;informational&#034;<\/p>\n<p>class StatusCodeMonitor:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u76d1\u63a7\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self, retention_period: timedelta &#061; timedelta(days&#061;7)):<br \/>\n        self.retention_period &#061; retention_period<br \/>\n        self.metrics_buffer: List[StatusCodeMetric] &#061; []<br \/>\n        self.aggregated_metrics: Dict[str, Dict] &#061; {}<br \/>\n        self.alert_rules: List[AlertRule] &#061; []<\/p>\n<p>    def record_metric(self, metric: StatusCodeMetric):<br \/>\n        &#034;&#034;&#034;\u8bb0\u5f55\u6307\u6807&#034;&#034;&#034;<br \/>\n        self.metrics_buffer.append(metric)<\/p>\n<p>        # \u89e6\u53d1\u5b9e\u65f6\u5206\u6790<br \/>\n        self._real_time_analysis(metric)<\/p>\n<p>        # \u68c0\u67e5\u544a\u8b66\u89c4\u5219<br \/>\n        self._check_alerts(metric)<\/p>\n<p>        # \u5b9a\u671f\u6301\u4e45\u5316<br \/>\n        if len(self.metrics_buffer) &gt;&#061; 1000:<br \/>\n            self._persist_metrics()<\/p>\n<p>    def _real_time_analysis(self, metric: StatusCodeMetric):<br \/>\n        &#034;&#034;&#034;\u5b9e\u65f6\u5206\u6790&#034;&#034;&#034;<br \/>\n        # \u66f4\u65b0\u805a\u5408\u6307\u6807<br \/>\n        key &#061; self._get_aggregation_key(metric)<\/p>\n<p>        if key not in self.aggregated_metrics:<br \/>\n            self.aggregated_metrics[key] &#061; {<br \/>\n                &#039;count&#039;: 0,<br \/>\n                &#039;success_count&#039;: 0,<br \/>\n                &#039;error_count&#039;: 0,<br \/>\n                &#039;response_times&#039;: [],<br \/>\n                &#039;last_updated&#039;: metric.timestamp<br \/>\n            }<\/p>\n<p>        agg &#061; self.aggregated_metrics[key]<br \/>\n        agg[&#039;count&#039;] &#043;&#061; 1<br \/>\n        agg[&#039;last_updated&#039;] &#061; metric.timestamp<\/p>\n<p>        if metric.is_success:<br \/>\n            agg[&#039;success_count&#039;] &#043;&#061; 1<br \/>\n        else:<br \/>\n            agg[&#039;error_count&#039;] &#043;&#061; 1<\/p>\n<p>        agg[&#039;response_times&#039;].append(metric.response_time_ms)<\/p>\n<p>        # \u4fdd\u6301\u56fa\u5b9a\u5927\u5c0f<br \/>\n        if len(agg[&#039;response_times&#039;]) &gt; 1000:<br \/>\n            agg[&#039;response_times&#039;] &#061; agg[&#039;response_times&#039;][-1000:]<\/p>\n<p>    def _get_aggregation_key(self, metric: StatusCodeMetric) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u805a\u5408\u952e&#034;&#034;&#034;<br \/>\n        # \u6309\u5206\u949f\u805a\u5408<br \/>\n        minute_key &#061; metric.timestamp.strftime(&#034;%Y-%m-%d %H:%M&#034;)<br \/>\n        return f&#034;{metric.service_name}:{metric.endpoint}:{minute_key}&#034;<\/p>\n<p>    def get_metrics_summary(self,<br \/>\n                           start_time: datetime,<br \/>\n                           end_time: datetime,<br \/>\n                           dimensions: List[MetricDimension]) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u6307\u6807\u6458\u8981&#034;&#034;&#034;<br \/>\n        # \u8fc7\u6ee4\u65f6\u95f4\u8303\u56f4<br \/>\n        filtered_metrics &#061; [<br \/>\n            m for m in self.metrics_buffer<br \/>\n            if start_time &lt;&#061; m.timestamp &lt;&#061; end_time<br \/>\n        ]<\/p>\n<p>        summary &#061; {<br \/>\n            &#039;time_range&#039;: {<br \/>\n                &#039;start&#039;: start_time,<br \/>\n                &#039;end&#039;: end_time<br \/>\n            },<br \/>\n            &#039;total_requests&#039;: len(filtered_metrics),<br \/>\n            &#039;dimensions&#039;: {}<br \/>\n        }<\/p>\n<p>        # \u6309\u7ef4\u5ea6\u805a\u5408<br \/>\n        for dimension in dimensions:<br \/>\n            if dimension &#061;&#061; MetricDimension.STATUS_CODE:<br \/>\n                summary[&#039;dimensions&#039;][&#039;status_code&#039;] &#061; self._aggregate_by_status_code(filtered_metrics)<br \/>\n            elif dimension &#061;&#061; MetricDimension.ENDPOINT:<br \/>\n                summary[&#039;dimensions&#039;][&#039;endpoint&#039;] &#061; self._aggregate_by_endpoint(filtered_metrics)<br \/>\n            elif dimension &#061;&#061; MetricDimension.TIME:<br \/>\n                summary[&#039;dimensions&#039;][&#039;time&#039;] &#061; self._aggregate_by_time(filtered_metrics)<br \/>\n            # \u5176\u4ed6\u7ef4\u5ea6&#8230;<\/p>\n<p>        # \u8ba1\u7b97\u603b\u4f53\u6307\u6807<br \/>\n        summary[&#039;overall&#039;] &#061; self._calculate_overall_metrics(filtered_metrics)<\/p>\n<p>        return summary<\/p>\n<p>    def _aggregate_by_status_code(self, metrics: List[StatusCodeMetric]) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u6309\u72b6\u6001\u7801\u805a\u5408&#034;&#034;&#034;<br \/>\n        aggregation &#061; {}<\/p>\n<p>        for metric in metrics:<br \/>\n            code &#061; metric.status_code<br \/>\n            if code not in aggregation:<br \/>\n                aggregation[code] &#061; {<br \/>\n                    &#039;count&#039;: 0,<br \/>\n                    &#039;avg_response_time&#039;: 0,<br \/>\n                    &#039;response_times&#039;: [],<br \/>\n                    &#039;endpoints&#039;: set(),<br \/>\n                    &#039;clients&#039;: set()<br \/>\n                }<\/p>\n<p>            agg &#061; aggregation[code]<br \/>\n            agg[&#039;count&#039;] &#043;&#061; 1<br \/>\n            agg[&#039;response_times&#039;].append(metric.response_time_ms)<br \/>\n            agg[&#039;endpoints&#039;].add(metric.endpoint)<br \/>\n            agg[&#039;clients&#039;].add(metric.client_ip)<\/p>\n<p>            # \u8ba1\u7b97\u7edf\u8ba1\u4fe1\u606f<br \/>\n            if agg[&#039;response_times&#039;]:<br \/>\n                agg[&#039;avg_response_time&#039;] &#061; statistics.mean(agg[&#039;response_times&#039;])<br \/>\n                agg[&#039;p95_response_time&#039;] &#061; self._calculate_percentile(agg[&#039;response_times&#039;], 95)<br \/>\n                agg[&#039;p99_response_time&#039;] &#061; self._calculate_percentile(agg[&#039;response_times&#039;], 99)<\/p>\n<p>        return aggregation<\/p>\n<p>    def _aggregate_by_endpoint(self, metrics: List[StatusCodeMetric]) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u6309\u7aef\u70b9\u805a\u5408&#034;&#034;&#034;<br \/>\n        aggregation &#061; {}<\/p>\n<p>        for metric in metrics:<br \/>\n            endpoint &#061; metric.endpoint<br \/>\n            if endpoint not in aggregation:<br \/>\n                aggregation[endpoint] &#061; {<br \/>\n                    &#039;total_requests&#039;: 0,<br \/>\n                    &#039;status_codes&#039;: {},<br \/>\n                    &#039;avg_response_time&#039;: 0,<br \/>\n                    &#039;success_rate&#039;: 0,<br \/>\n                    &#039;error_rate&#039;: 0<br \/>\n                }<\/p>\n<p>            agg &#061; aggregation[endpoint]<br \/>\n            agg[&#039;total_requests&#039;] &#043;&#061; 1<\/p>\n<p>            # \u6309\u72b6\u6001\u7801\u7edf\u8ba1<br \/>\n            code &#061; metric.status_code<br \/>\n            if code not in agg[&#039;status_codes&#039;]:<br \/>\n                agg[&#039;status_codes&#039;][code] &#061; 0<br \/>\n            agg[&#039;status_codes&#039;][code] &#043;&#061; 1<\/p>\n<p>            # \u8ba1\u7b97\u54cd\u5e94\u65f6\u95f4<br \/>\n            if &#039;response_times&#039; not in agg:<br \/>\n                agg[&#039;response_times&#039;] &#061; []<br \/>\n            agg[&#039;response_times&#039;].append(metric.response_time_ms)<\/p>\n<p>        # \u8ba1\u7b97\u805a\u5408\u7edf\u8ba1<br \/>\n        for endpoint, data in aggregation.items():<br \/>\n            if data[&#039;response_times&#039;]:<br \/>\n                data[&#039;avg_response_time&#039;] &#061; statistics.mean(data[&#039;response_times&#039;])<br \/>\n                data[&#039;p95_response_time&#039;] &#061; self._calculate_percentile(data[&#039;response_times&#039;], 95)<\/p>\n<p>            # \u8ba1\u7b97\u6210\u529f\u7387<br \/>\n            total &#061; data[&#039;total_requests&#039;]<br \/>\n            success_count &#061; sum(count for code, count in data[&#039;status_codes&#039;].items()<br \/>\n                              if 200 &lt;&#061; code &lt; 300)<br \/>\n            data[&#039;success_rate&#039;] &#061; success_count \/ total if total &gt; 0 else 0<br \/>\n            data[&#039;error_rate&#039;] &#061; 1 &#8211; data[&#039;success_rate&#039;]<\/p>\n<p>        return aggregation<\/p>\n<p>    def _aggregate_by_time(self, metrics: List[StatusCodeMetric]) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u6309\u65f6\u95f4\u805a\u5408&#034;&#034;&#034;<br \/>\n        time_aggregation &#061; {}<\/p>\n<p>        for metric in metrics:<br \/>\n            # \u6309\u5c0f\u65f6\u805a\u5408<br \/>\n            hour_key &#061; metric.timestamp.strftime(&#034;%Y-%m-%d %H:00&#034;)<\/p>\n<p>            if hour_key not in time_aggregation:<br \/>\n                time_aggregation[hour_key] &#061; {<br \/>\n                    &#039;total_requests&#039;: 0,<br \/>\n                    &#039;status_codes&#039;: {},<br \/>\n                    &#039;avg_response_time&#039;: 0,<br \/>\n                    &#039;unique_endpoints&#039;: set(),<br \/>\n                    &#039;unique_clients&#039;: set()<br \/>\n                }<\/p>\n<p>            agg &#061; time_aggregation[hour_key]<br \/>\n            agg[&#039;total_requests&#039;] &#043;&#061; 1<br \/>\n            agg[&#039;unique_endpoints&#039;].add(metric.endpoint)<br \/>\n            agg[&#039;unique_clients&#039;].add(metric.client_ip)<\/p>\n<p>            # \u72b6\u6001\u7801\u7edf\u8ba1<br \/>\n            code &#061; metric.status_code<br \/>\n            if code not in agg[&#039;status_codes&#039;]:<br \/>\n                agg[&#039;status_codes&#039;][code] &#061; 0<br \/>\n            agg[&#039;status_codes&#039;][code] &#043;&#061; 1<\/p>\n<p>            # \u54cd\u5e94\u65f6\u95f4<br \/>\n            if &#039;response_times&#039; not in agg:<br \/>\n                agg[&#039;response_times&#039;] &#061; []<br \/>\n            agg[&#039;response_times&#039;].append(metric.response_time_ms)<\/p>\n<p>        # \u8ba1\u7b97\u6bcf\u5c0f\u65f6\u7edf\u8ba1<br \/>\n        for hour, data in time_aggregation.items():<br \/>\n            if data[&#039;response_times&#039;]:<br \/>\n                data[&#039;avg_response_time&#039;] &#061; statistics.mean(data[&#039;response_times&#039;])<\/p>\n<p>            data[&#039;unique_endpoints_count&#039;] &#061; len(data[&#039;unique_endpoints&#039;])<br \/>\n            data[&#039;unique_clients_count&#039;] &#061; len(data[&#039;unique_clients&#039;])<\/p>\n<p>            # \u8ba1\u7b97\u72b6\u6001\u7801\u5206\u5e03<br \/>\n            total &#061; data[&#039;total_requests&#039;]<br \/>\n            data[&#039;status_distribution&#039;] &#061; {<br \/>\n                code: count \/ total<br \/>\n                for code, count in data[&#039;status_codes&#039;].items()<br \/>\n            }<\/p>\n<p>        return time_aggregation<\/p>\n<p>    def _calculate_overall_metrics(self, metrics: List[StatusCodeMetric]) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u603b\u4f53\u6307\u6807&#034;&#034;&#034;<br \/>\n        if not metrics:<br \/>\n            return {}<\/p>\n<p>        response_times &#061; [m.response_time_ms for m in metrics]<br \/>\n        status_codes &#061; [m.status_code for m in metrics]<\/p>\n<p>        # \u6210\u529f\u7387\u8ba1\u7b97<br \/>\n        success_count &#061; sum(1 for code in status_codes if 200 &lt;&#061; code &lt; 300)<br \/>\n        error_count &#061; len(metrics) &#8211; success_count<\/p>\n<p>        overall &#061; {<br \/>\n            &#039;total_requests&#039;: len(metrics),<br \/>\n            &#039;success_count&#039;: success_count,<br \/>\n            &#039;error_count&#039;: error_count,<br \/>\n            &#039;success_rate&#039;: success_count \/ len(metrics) if metrics else 0,<br \/>\n            &#039;error_rate&#039;: error_count \/ len(metrics) if metrics else 0,<br \/>\n            &#039;avg_response_time&#039;: statistics.mean(response_times) if response_times else 0,<br \/>\n            &#039;p95_response_time&#039;: self._calculate_percentile(response_times, 95),<br \/>\n            &#039;p99_response_time&#039;: self._calculate_percentile(response_times, 99),<br \/>\n            &#039;status_code_distribution&#039;: self._calculate_status_distribution(status_codes)<br \/>\n        }<\/p>\n<p>        return overall<\/p>\n<p>    def _calculate_percentile(self, values: List[float], percentile: float) -&gt; float:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u767e\u5206\u4f4d\u6570&#034;&#034;&#034;<br \/>\n        if not values:<br \/>\n            return 0<\/p>\n<p>        sorted_values &#061; sorted(values)<br \/>\n        index &#061; (percentile \/ 100) * (len(sorted_values) &#8211; 1)<\/p>\n<p>        if index.is_integer():<br \/>\n            return sorted_values[int(index)]<br \/>\n        else:<br \/>\n            lower &#061; sorted_values[int(index)]<br \/>\n            upper &#061; sorted_values[int(index) &#043; 1]<br \/>\n            return lower &#043; (upper &#8211; lower) * (index &#8211; int(index))<\/p>\n<p>    def _calculate_status_distribution(self, status_codes: List[int]) -&gt; Dict[int, float]:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u72b6\u6001\u7801\u5206\u5e03&#034;&#034;&#034;<br \/>\n        total &#061; len(status_codes)<br \/>\n        distribution &#061; {}<\/p>\n<p>        for code in set(status_codes):<br \/>\n            count &#061; status_codes.count(code)<br \/>\n            distribution[code] &#061; count \/ total<\/p>\n<p>        return distribution<\/p>\n<p>    def _check_alerts(self, metric: StatusCodeMetric):<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u544a\u8b66\u89c4\u5219&#034;&#034;&#034;<br \/>\n        for rule in self.alert_rules:<br \/>\n            if rule.matches(metric):<br \/>\n                rule.trigger_alert(metric)<\/p>\n<p>    def _persist_metrics(self):<br \/>\n        &#034;&#034;&#034;\u6301\u4e45\u5316\u6307\u6807&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u5c06\u6307\u6807\u5199\u5165\u6570\u636e\u5e93\u6216\u6587\u4ef6<br \/>\n        # \u6e05\u7406\u65e7\u6570\u636e<br \/>\n        cutoff &#061; datetime.now() &#8211; self.retention_period<br \/>\n        self.metrics_buffer &#061; [<br \/>\n            m for m in self.metrics_buffer<br \/>\n            if m.timestamp &gt; cutoff<br \/>\n        ]<\/p>\n<p>class AlertRule:<br \/>\n    &#034;&#034;&#034;\u544a\u8b66\u89c4\u5219&#034;&#034;&#034;<\/p>\n<p>    def __init__(self,<br \/>\n                 name: str,<br \/>\n                 condition: Dict,<br \/>\n                 action: str,<br \/>\n                 cooldown_period: timedelta &#061; timedelta(minutes&#061;5)):<br \/>\n        self.name &#061; name<br \/>\n        self.condition &#061; condition<br \/>\n        self.action &#061; action<br \/>\n        self.cooldown_period &#061; cooldown_period<br \/>\n        self.last_triggered: Optional[datetime] &#061; None<\/p>\n<p>    def matches(self, metric: StatusCodeMetric) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u662f\u5426\u5339\u914d\u89c4\u5219&#034;&#034;&#034;<br \/>\n        # \u68c0\u67e5\u51b7\u5374\u671f<br \/>\n        if (self.last_triggered and<br \/>\n            datetime.now() &#8211; self.last_triggered &lt; self.cooldown_period):<br \/>\n            return False<\/p>\n<p>        # \u68c0\u67e5\u6761\u4ef6<br \/>\n        condition_type &#061; self.condition.get(&#039;type&#039;)<\/p>\n<p>        if condition_type &#061;&#061; &#039;status_code&#039;:<br \/>\n            return self._check_status_code_condition(metric)<br \/>\n        elif condition_type &#061;&#061; &#039;error_rate&#039;:<br \/>\n            return self._check_error_rate_condition(metric)<br \/>\n        elif condition_type &#061;&#061; &#039;response_time&#039;:<br \/>\n            return self._check_response_time_condition(metric)<\/p>\n<p>        return False<\/p>\n<p>    def _check_status_code_condition(self, metric: StatusCodeMetric) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u72b6\u6001\u7801\u6761\u4ef6&#034;&#034;&#034;<br \/>\n        target_codes &#061; self.condition.get(&#039;codes&#039;, [])<br \/>\n        return metric.status_code in target_codes<\/p>\n<p>    def _check_error_rate_condition(self, metric: StatusCodeMetric) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u9519\u8bef\u7387\u6761\u4ef6&#034;&#034;&#034;<br \/>\n        # \u9700\u8981\u57fa\u4e8e\u4e00\u6bb5\u65f6\u95f4\u5185\u7684\u6570\u636e\u8ba1\u7b97<br \/>\n        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        return False<\/p>\n<p>    def _check_response_time_condition(self, metric: StatusCodeMetric) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u54cd\u5e94\u65f6\u95f4\u6761\u4ef6&#034;&#034;&#034;<br \/>\n        threshold &#061; self.condition.get(&#039;threshold_ms&#039;, 1000)<br \/>\n        return metric.response_time_ms &gt; threshold<\/p>\n<p>    def trigger_alert(self, metric: StatusCodeMetric):<br \/>\n        &#034;&#034;&#034;\u89e6\u53d1\u544a\u8b66&#034;&#034;&#034;<br \/>\n        self.last_triggered &#061; datetime.now()<\/p>\n<p>        alert_message &#061; {<br \/>\n            &#039;rule_name&#039;: self.name,<br \/>\n            &#039;timestamp&#039;: datetime.now(),<br \/>\n            &#039;metric&#039;: asdict(metric),<br \/>\n            &#039;action&#039;: self.action<br \/>\n        }<\/p>\n<p>        # \u53d1\u9001\u544a\u8b66&#xff08;\u793a\u4f8b&#xff09;<br \/>\n        print(f&#034;ALERT: {alert_message}&#034;)<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nmonitor &#061; StatusCodeMonitor()<\/p>\n<p># \u6dfb\u52a0\u544a\u8b66\u89c4\u5219<br \/>\nmonitor.alert_rules.append(<br \/>\n    AlertRule(<br \/>\n        name&#061;&#034;High 5xx Errors&#034;,<br \/>\n        condition&#061;{<br \/>\n            &#039;type&#039;: &#039;status_code&#039;,<br \/>\n            &#039;codes&#039;: [500, 502, 503, 504]<br \/>\n        },<br \/>\n        action&#061;&#034;notify_ops&#034;<br \/>\n    )<br \/>\n)<\/p>\n<p>monitor.alert_rules.append(<br \/>\n    AlertRule(<br \/>\n        name&#061;&#034;Slow Response&#034;,<br \/>\n        condition&#061;{<br \/>\n            &#039;type&#039;: &#039;response_time&#039;,<br \/>\n            &#039;threshold_ms&#039;: 5000<br \/>\n        },<br \/>\n        action&#061;&#034;scale_up&#034;<br \/>\n    )<br \/>\n)<\/p>\n<p># \u8bb0\u5f55\u6307\u6807<br \/>\nmetric &#061; StatusCodeMetric(<br \/>\n    timestamp&#061;datetime.now(),<br \/>\n    status_code&#061;200,<br \/>\n    endpoint&#061;&#034;\/api\/users&#034;,<br \/>\n    method&#061;&#034;GET&#034;,<br \/>\n    response_time_ms&#061;150.5,<br \/>\n    client_ip&#061;&#034;192.168.1.1&#034;,<br \/>\n    user_agent&#061;&#034;Mozilla\/5.0&#034;,<br \/>\n    service_name&#061;&#034;user-service&#034;,<br \/>\n    region&#061;&#034;us-east-1&#034;,<br \/>\n    additional_tags&#061;{&#034;version&#034;: &#034;v1.2.3&#034;}<br \/>\n)<\/p>\n<p>monitor.record_metric(metric)<\/p>\n<p># \u83b7\u53d6\u6458\u8981<br \/>\nsummary &#061; monitor.get_metrics_summary(<br \/>\n    start_time&#061;datetime.now() &#8211; timedelta(hours&#061;1),<br \/>\n    end_time&#061;datetime.now(),<br \/>\n    dimensions&#061;[MetricDimension.STATUS_CODE, MetricDimension.ENDPOINT]<br \/>\n)<\/p>\n<p>print(f&#034;Total requests: {summary[&#039;overall&#039;][&#039;total_requests&#039;]}&#034;)<br \/>\nprint(f&#034;Success rate: {summary[&#039;overall&#039;][&#039;success_rate&#039;]:.2%}&#034;)<\/p>\n<h5>38.1.2 \u5b9e\u65f6\u6d41\u5904\u7406\u67b6\u6784<\/h5>\n<p>python<\/p>\n<p># \u57fa\u4e8e\u6d41\u5904\u7406\u7684\u72b6\u6001\u7801\u76d1\u63a7<br \/>\nfrom typing import Generator<br \/>\nimport asyncio<br \/>\nimport json<br \/>\nfrom datetime import datetime<\/p>\n<p>class StatusCodeStreamProcessor:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u6d41\u5904\u7406\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self,<br \/>\n                 window_size_seconds: int &#061; 300,  # 5\u5206\u949f\u7a97\u53e3<br \/>\n                 slide_interval_seconds: int &#061; 60):  # 1\u5206\u949f\u6ed1\u52a8<br \/>\n        self.window_size &#061; window_size_seconds<br \/>\n        self.slide_interval &#061; slide_interval_seconds<br \/>\n        self.streams: Dict[str, asyncio.Queue] &#061; {}<br \/>\n        self.processing_tasks: List[asyncio.Task] &#061; []<\/p>\n<p>    async def ingest_stream(self,<br \/>\n                           stream_name: str,<br \/>\n                           metric_generator: Generator[StatusCodeMetric, None, None]):<br \/>\n        &#034;&#034;&#034;\u6444\u5165\u6307\u6807\u6d41&#034;&#034;&#034;<br \/>\n        if stream_name not in self.streams:<br \/>\n            self.streams[stream_name] &#061; asyncio.Queue()<\/p>\n<p>        # \u542f\u52a8\u5904\u7406\u4efb\u52a1<br \/>\n        task &#061; asyncio.create_task(<br \/>\n            self._process_stream(stream_name)<br \/>\n        )<br \/>\n        self.processing_tasks.append(task)<\/p>\n<p>        # \u5c06\u6307\u6807\u653e\u5165\u961f\u5217<br \/>\n        async for metric in self._async_generator(metric_generator):<br \/>\n            await self.streams[stream_name].put(metric)<\/p>\n<p>    async def _async_generator(self, generator: Generator):<br \/>\n        &#034;&#034;&#034;\u5c06\u540c\u6b65\u751f\u6210\u5668\u8f6c\u6362\u4e3a\u5f02\u6b65&#034;&#034;&#034;<br \/>\n        try:<br \/>\n            while True:<br \/>\n                yield next(generator)<br \/>\n        except StopIteration:<br \/>\n            pass<\/p>\n<p>    async def _process_stream(self, stream_name: str):<br \/>\n        &#034;&#034;&#034;\u5904\u7406\u6d41&#034;&#034;&#034;<br \/>\n        window_buffer &#061; []<br \/>\n        last_slide_time &#061; datetime.now()<\/p>\n<p>        while True:<br \/>\n            try:<br \/>\n                # \u83b7\u53d6\u6307\u6807&#xff08;\u5e26\u8d85\u65f6&#xff09;<br \/>\n                metric &#061; await asyncio.wait_for(<br \/>\n                    self.streams[stream_name].get(),<br \/>\n                    timeout&#061;1.0<br \/>\n                )<\/p>\n<p>                # \u6dfb\u52a0\u5230\u7a97\u53e3\u7f13\u51b2\u533a<br \/>\n                window_buffer.append(metric)<\/p>\n<p>                # \u6e05\u7406\u8fc7\u671f\u6307\u6807<br \/>\n                current_time &#061; datetime.now()<br \/>\n                cutoff_time &#061; current_time &#8211; timedelta(seconds&#061;self.window_size)<br \/>\n                window_buffer &#061; [<br \/>\n                    m for m in window_buffer<br \/>\n                    if m.timestamp &gt; cutoff_time<br \/>\n                ]<\/p>\n<p>                # \u68c0\u67e5\u662f\u5426\u5e94\u8be5\u6ed1\u52a8\u7a97\u53e3<br \/>\n                time_since_slide &#061; (current_time &#8211; last_slide_time).total_seconds()<br \/>\n                if time_since_slide &gt;&#061; self.slide_interval:<br \/>\n                    # \u5904\u7406\u7a97\u53e3\u6570\u636e<br \/>\n                    await self._process_window(stream_name, window_buffer)<br \/>\n                    last_slide_time &#061; current_time<\/p>\n<p>            except asyncio.TimeoutError:<br \/>\n                # \u7ee7\u7eed\u7b49\u5f85<br \/>\n                continue<\/p>\n<p>    async def _process_window(self,<br \/>\n                             stream_name: str,<br \/>\n                             window_metrics: List[StatusCodeMetric]):<br \/>\n        &#034;&#034;&#034;\u5904\u7406\u7a97\u53e3\u6570\u636e&#034;&#034;&#034;<br \/>\n        if not window_metrics:<br \/>\n            return<\/p>\n<p>        # \u8ba1\u7b97\u7a97\u53e3\u7edf\u8ba1<br \/>\n        window_stats &#061; self._calculate_window_stats(window_metrics)<\/p>\n<p>        # \u68c0\u6d4b\u5f02\u5e38<br \/>\n        anomalies &#061; self._detect_anomalies(window_stats)<\/p>\n<p>        # \u89e6\u53d1\u544a\u8b66<br \/>\n        if anomalies:<br \/>\n            await self._trigger_alerts(stream_name, window_stats, anomalies)<\/p>\n<p>        # \u66f4\u65b0\u4eea\u8868\u677f<br \/>\n        await self._update_dashboard(stream_name, window_stats)<\/p>\n<p>        # \u6301\u4e45\u5316<br \/>\n        await self._persist_window_stats(stream_name, window_stats)<\/p>\n<p>    def _calculate_window_stats(self,<br \/>\n                               metrics: List[StatusCodeMetric]) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u7a97\u53e3\u7edf\u8ba1&#034;&#034;&#034;<br \/>\n        stats &#061; {<br \/>\n            &#039;window_start&#039;: min(m.timestamp for m in metrics),<br \/>\n            &#039;window_end&#039;: max(m.timestamp for m in metrics),<br \/>\n            &#039;total_requests&#039;: len(metrics),<br \/>\n            &#039;throughput_rps&#039;: len(metrics) \/ self.window_size,<br \/>\n            &#039;status_code_distribution&#039;: {},<br \/>\n            &#039;endpoint_distribution&#039;: {},<br \/>\n            &#039;response_time_stats&#039;: {},<br \/>\n            &#039;error_rate&#039;: 0<br \/>\n        }<\/p>\n<p>        # \u72b6\u6001\u7801\u5206\u5e03<br \/>\n        status_codes &#061; [m.status_code for m in metrics]<br \/>\n        for code in set(status_codes):<br \/>\n            count &#061; status_codes.count(code)<br \/>\n            stats[&#039;status_code_distribution&#039;][code] &#061; {<br \/>\n                &#039;count&#039;: count,<br \/>\n                &#039;percentage&#039;: count \/ len(metrics)<br \/>\n            }<\/p>\n<p>        # \u7aef\u70b9\u5206\u5e03<br \/>\n        endpoints &#061; [m.endpoint for m in metrics]<br \/>\n        for endpoint in set(endpoints):<br \/>\n            count &#061; endpoints.count(endpoint)<br \/>\n            stats[&#039;endpoint_distribution&#039;][endpoint] &#061; {<br \/>\n                &#039;count&#039;: count,<br \/>\n                &#039;percentage&#039;: count \/ len(metrics)<br \/>\n            }<\/p>\n<p>        # \u54cd\u5e94\u65f6\u95f4\u7edf\u8ba1<br \/>\n        response_times &#061; [m.response_time_ms for m in metrics]<br \/>\n        if response_times:<br \/>\n            import statistics<br \/>\n            stats[&#039;response_time_stats&#039;] &#061; {<br \/>\n                &#039;mean&#039;: statistics.mean(response_times),<br \/>\n                &#039;median&#039;: statistics.median(response_times),<br \/>\n                &#039;p90&#039;: self._calculate_percentile(response_times, 90),<br \/>\n                &#039;p95&#039;: self._calculate_percentile(response_times, 95),<br \/>\n                &#039;p99&#039;: self._calculate_percentile(response_times, 99),<br \/>\n                &#039;std_dev&#039;: statistics.stdev(response_times) if len(response_times) &gt; 1 else 0<br \/>\n            }<\/p>\n<p>        # \u9519\u8bef\u7387<br \/>\n        error_count &#061; sum(1 for code in status_codes if code &gt;&#061; 400)<br \/>\n        stats[&#039;error_rate&#039;] &#061; error_count \/ len(metrics) if metrics else 0<\/p>\n<p>        return stats<\/p>\n<p>    def _detect_anomalies(self, window_stats: Dict) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u5f02\u5e38&#034;&#034;&#034;<br \/>\n        anomalies &#061; []<\/p>\n<p>        # \u68c0\u6d4b\u9519\u8bef\u7387\u5f02\u5e38<br \/>\n        if window_stats[&#039;error_rate&#039;] &gt; 0.1:  # 10%\u9519\u8bef\u7387\u9608\u503c<br \/>\n            anomalies.append({<br \/>\n                &#039;type&#039;: &#039;HIGH_ERROR_RATE&#039;,<br \/>\n                &#039;value&#039;: window_stats[&#039;error_rate&#039;],<br \/>\n                &#039;threshold&#039;: 0.1<br \/>\n            })<\/p>\n<p>        # \u68c0\u6d4b\u7279\u5b9a\u72b6\u6001\u7801\u6fc0\u589e<br \/>\n        for code, dist in window_stats[&#039;status_code_distribution&#039;].items():<br \/>\n            if code &gt;&#061; 500 and dist[&#039;percentage&#039;] &gt; 0.05:  # 5xx\u8d85\u8fc75%<br \/>\n                anomalies.append({<br \/>\n                    &#039;type&#039;: f&#039;HIGH_{code}_RATE&#039;,<br \/>\n                    &#039;code&#039;: code,<br \/>\n                    &#039;value&#039;: dist[&#039;percentage&#039;],<br \/>\n                    &#039;threshold&#039;: 0.05<br \/>\n                })<\/p>\n<p>        # \u68c0\u6d4b\u54cd\u5e94\u65f6\u95f4\u5f02\u5e38<br \/>\n        response_stats &#061; window_stats[&#039;response_time_stats&#039;]<br \/>\n        if response_stats.get(&#039;p95&#039;, 0) &gt; 5000:  # P95\u54cd\u5e94\u65f6\u95f4\u8d85\u8fc75\u79d2<br \/>\n            anomalies.append({<br \/>\n                &#039;type&#039;: &#039;HIGH_P95_RESPONSE_TIME&#039;,<br \/>\n                &#039;value&#039;: response_stats[&#039;p95&#039;],<br \/>\n                &#039;threshold&#039;: 5000<br \/>\n            })<\/p>\n<p>        return anomalies<\/p>\n<p>    async def _trigger_alerts(self,<br \/>\n                             stream_name: str,<br \/>\n                             stats: Dict,<br \/>\n                             anomalies: List[Dict]):<br \/>\n        &#034;&#034;&#034;\u89e6\u53d1\u544a\u8b66&#034;&#034;&#034;<br \/>\n        alert_message &#061; {<br \/>\n            &#039;stream&#039;: stream_name,<br \/>\n            &#039;timestamp&#039;: datetime.now(),<br \/>\n            &#039;window_stats&#039;: stats,<br \/>\n            &#039;anomalies&#039;: anomalies,<br \/>\n            &#039;severity&#039;: self._calculate_severity(anomalies)<br \/>\n        }<\/p>\n<p>        # \u53d1\u9001\u544a\u8b66\u5230\u4e0d\u540c\u6e20\u9053<br \/>\n        await self._send_alert(alert_message)<\/p>\n<p>    def _calculate_severity(self, anomalies: List[Dict]) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u544a\u8b66\u4e25\u91cd\u7a0b\u5ea6&#034;&#034;&#034;<br \/>\n        # \u57fa\u4e8e\u5f02\u5e38\u7c7b\u578b\u548c\u503c\u8ba1\u7b97<br \/>\n        error_anomalies &#061; [a for a in anomalies if &#039;ERROR_RATE&#039; in a[&#039;type&#039;]]<br \/>\n        response_anomalies &#061; [a for a in anomalies if &#039;RESPONSE_TIME&#039; in a[&#039;type&#039;]]<\/p>\n<p>        if error_anomalies and any(a[&#039;value&#039;] &gt; 0.2 for a in error_anomalies):<br \/>\n            return &#039;CRITICAL&#039;<br \/>\n        elif error_anomalies or response_anomalies:<br \/>\n            return &#039;WARNING&#039;<br \/>\n        else:<br \/>\n            return &#039;INFO&#039;<\/p>\n<p>    async def _send_alert(self, alert: Dict):<br \/>\n        &#034;&#034;&#034;\u53d1\u9001\u544a\u8b66&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u96c6\u6210\u5230\u544a\u8b66\u7cfb\u7edf<br \/>\n        print(f&#034;ALERT: {json.dumps(alert, indent&#061;2, default&#061;str)}&#034;)<\/p>\n<p>    async def _update_dashboard(self,<br \/>\n                               stream_name: str,<br \/>\n                               stats: Dict):<br \/>\n        &#034;&#034;&#034;\u66f4\u65b0\u4eea\u8868\u677f&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u66f4\u65b0\u5b9e\u65f6\u4eea\u8868\u677f<br \/>\n        pass<\/p>\n<p>    async def _persist_window_stats(self,<br \/>\n                                   stream_name: str,<br \/>\n                                   stats: Dict):<br \/>\n        &#034;&#034;&#034;\u6301\u4e45\u5316\u7a97\u53e3\u7edf\u8ba1&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u5199\u5165\u65f6\u5e8f\u6570\u636e\u5e93<br \/>\n        pass<\/p>\n<p>    def _calculate_percentile(self, values: List[float], percentile: float) -&gt; float:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u767e\u5206\u4f4d\u6570&#034;&#034;&#034;<br \/>\n        if not values:<br \/>\n            return 0<\/p>\n<p>        sorted_values &#061; sorted(values)<br \/>\n        index &#061; (percentile \/ 100) * (len(sorted_values) &#8211; 1)<\/p>\n<p>        if index.is_integer():<br \/>\n            return sorted_values[int(index)]<br \/>\n        else:<br \/>\n            lower &#061; sorted_values[int(index)]<br \/>\n            upper &#061; sorted_values[int(index) &#043; 1]<br \/>\n            return lower &#043; (upper &#8211; lower) * (index &#8211; int(index))<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nasync def main():<br \/>\n    processor &#061; StatusCodeStreamProcessor()<\/p>\n<p>    # \u6a21\u62df\u6307\u6807\u751f\u6210\u5668<br \/>\n    def mock_metric_generator():<br \/>\n        import random<br \/>\n        import time<br \/>\n        from datetime import datetime<\/p>\n<p>        endpoints &#061; [&#039;\/api\/users&#039;, &#039;\/api\/products&#039;, &#039;\/api\/orders&#039;]<br \/>\n        status_codes &#061; [200, 201, 400, 401, 404, 500]<\/p>\n<p>        while True:<br \/>\n            yield StatusCodeMetric(<br \/>\n                timestamp&#061;datetime.now(),<br \/>\n                status_code&#061;random.choice(status_codes),<br \/>\n                endpoint&#061;random.choice(endpoints),<br \/>\n                method&#061;random.choice([&#039;GET&#039;, &#039;POST&#039;, &#039;PUT&#039;, &#039;DELETE&#039;]),<br \/>\n                response_time_ms&#061;random.uniform(50, 5000),<br \/>\n                client_ip&#061;f&#034;192.168.1.{random.randint(1, 255)}&#034;,<br \/>\n                user_agent&#061;&#034;Mock\/1.0&#034;,<br \/>\n                service_name&#061;&#034;mock-service&#034;,<br \/>\n                region&#061;&#034;us-east-1&#034;,<br \/>\n                additional_tags&#061;{}<br \/>\n            )<br \/>\n            time.sleep(random.uniform(0.01, 0.1))  # \u6a21\u62df\u8bf7\u6c42\u95f4\u9694<\/p>\n<p>    # \u5f00\u59cb\u6444\u5165\u6d41<br \/>\n    await processor.ingest_stream(&#034;main_api&#034;, mock_metric_generator())<\/p>\n<p>    # \u8fd0\u884c\u4e00\u6bb5\u65f6\u95f4<br \/>\n    await asyncio.sleep(300)  # \u8fd0\u884c5\u5206\u949f<\/p>\n<p># \u8fd0\u884c\u6d41\u5904\u7406\u5668<br \/>\n# asyncio.run(main())<\/p>\n<h4>38.2 \u65e5\u5fd7\u5206\u6790\u4e0e\u6a21\u5f0f\u8bc6\u522b<\/h4>\n<h5>38.2.1 \u7ed3\u6784\u5316\u65e5\u5fd7\u5206\u6790<\/h5>\n<p>python<\/p>\n<p># \u7ed3\u6784\u5316\u65e5\u5fd7\u5206\u6790\u7cfb\u7edf<br \/>\nimport re<br \/>\nimport json<br \/>\nfrom datetime import datetime<br \/>\nfrom collections import defaultdict, Counter<br \/>\nfrom typing import Dict, List, Pattern, Tuple<br \/>\nfrom dataclasses import dataclass, field<br \/>\nimport logging<\/p>\n<p>&#064;dataclass<br \/>\nclass LogPattern:<br \/>\n    &#034;&#034;&#034;\u65e5\u5fd7\u6a21\u5f0f\u5b9a\u4e49&#034;&#034;&#034;<br \/>\n    name: str<br \/>\n    pattern: str<br \/>\n    description: str<br \/>\n    severity: str &#061; &#034;INFO&#034;<br \/>\n    alert_threshold: int &#061; 10  # \u6bcf\u5206\u949f\u9608\u503c<\/p>\n<p>    &#064;property<br \/>\n    def compiled_pattern(self) -&gt; Pattern:<br \/>\n        return re.compile(self.pattern)<\/p>\n<p>&#064;dataclass<br \/>\nclass LogEntry:<br \/>\n    &#034;&#034;&#034;\u65e5\u5fd7\u6761\u76ee&#034;&#034;&#034;<br \/>\n    timestamp: datetime<br \/>\n    level: str<br \/>\n    message: str<br \/>\n    status_code: int<br \/>\n    endpoint: str<br \/>\n    method: str<br \/>\n    client_ip: str<br \/>\n    response_time_ms: float<br \/>\n    additional_fields: Dict[str, str] &#061; field(default_factory&#061;dict)<\/p>\n<p>    &#064;classmethod<br \/>\n    def from_json(cls, json_str: str) -&gt; &#039;LogEntry&#039;:<br \/>\n        &#034;&#034;&#034;\u4eceJSON\u521b\u5efa\u65e5\u5fd7\u6761\u76ee&#034;&#034;&#034;<br \/>\n        data &#061; json.loads(json_str)<\/p>\n<p>        # \u89e3\u6790\u65f6\u95f4\u6233<br \/>\n        if &#039;timestamp&#039; in data:<br \/>\n            if isinstance(data[&#039;timestamp&#039;], str):<br \/>\n                timestamp &#061; datetime.fromisoformat(data[&#039;timestamp&#039;].replace(&#039;Z&#039;, &#039;&#043;00:00&#039;))<br \/>\n            else:<br \/>\n                timestamp &#061; datetime.fromtimestamp(data[&#039;timestamp&#039;])<br \/>\n        else:<br \/>\n            timestamp &#061; datetime.now()<\/p>\n<p>        return cls(<br \/>\n            timestamp&#061;timestamp,<br \/>\n            level&#061;data.get(&#039;level&#039;, &#039;INFO&#039;),<br \/>\n            message&#061;data.get(&#039;message&#039;, &#039;&#039;),<br \/>\n            status_code&#061;data.get(&#039;status_code&#039;, 0),<br \/>\n            endpoint&#061;data.get(&#039;endpoint&#039;, &#039;&#039;),<br \/>\n            method&#061;data.get(&#039;method&#039;, &#039;&#039;),<br \/>\n            client_ip&#061;data.get(&#039;client_ip&#039;, &#039;&#039;),<br \/>\n            response_time_ms&#061;data.get(&#039;response_time_ms&#039;, 0),<br \/>\n            additional_fields&#061;data.get(&#039;additional_fields&#039;, {})<br \/>\n        )<\/p>\n<p>    def to_dict(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u8f6c\u6362\u4e3a\u5b57\u5178&#034;&#034;&#034;<br \/>\n        return {<br \/>\n            &#039;timestamp&#039;: self.timestamp.isoformat(),<br \/>\n            &#039;level&#039;: self.level,<br \/>\n            &#039;message&#039;: self.message,<br \/>\n            &#039;status_code&#039;: self.status_code,<br \/>\n            &#039;endpoint&#039;: self.endpoint,<br \/>\n            &#039;method&#039;: self.method,<br \/>\n            &#039;client_ip&#039;: self.client_ip,<br \/>\n            &#039;response_time_ms&#039;: self.response_time_ms,<br \/>\n            &#039;additional_fields&#039;: self.additional_fields<br \/>\n        }<\/p>\n<p>class StatusCodeLogAnalyzer:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u65e5\u5fd7\u5206\u6790\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.log_patterns &#061; self._initialize_patterns()<br \/>\n        self.stats &#061; defaultdict(lambda: defaultdict(int))<br \/>\n        self.pattern_counts &#061; defaultdict(int)<br \/>\n        self.anomaly_detector &#061; LogAnomalyDetector()<\/p>\n<p>    def _initialize_patterns(self) -&gt; List[LogPattern]:<br \/>\n        &#034;&#034;&#034;\u521d\u59cb\u5316\u65e5\u5fd7\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        return [<br \/>\n            # \u9519\u8bef\u6a21\u5f0f<br \/>\n            LogPattern(<br \/>\n                name&#061;&#034;HIGH_5XX_ERROR&#034;,<br \/>\n                pattern&#061;r&#039;5\\\\d{2}&#039;,<br \/>\n                description&#061;&#034;High server error rate&#034;,<br \/>\n                severity&#061;&#034;ERROR&#034;,<br \/>\n                alert_threshold&#061;5<br \/>\n            ),<br \/>\n            LogPattern(<br \/>\n                name&#061;&#034;RATE_LIMIT_HIT&#034;,<br \/>\n                pattern&#061;r&#039;429.*rate.*limit&#039;,<br \/>\n                description&#061;&#034;Rate limit exceeded&#034;,<br \/>\n                severity&#061;&#034;WARNING&#034;,<br \/>\n                alert_threshold&#061;20<br \/>\n            ),<br \/>\n            LogPattern(<br \/>\n                name&#061;&#034;AUTH_FAILURE&#034;,<br \/>\n                pattern&#061;r&#039;401|403.*auth&#039;,<br \/>\n                description&#061;&#034;Authentication\/authorization failures&#034;,<br \/>\n                severity&#061;&#034;WARNING&#034;,<br \/>\n                alert_threshold&#061;10<br \/>\n            ),<\/p>\n<p>            # \u6027\u80fd\u6a21\u5f0f<br \/>\n            LogPattern(<br \/>\n                name&#061;&#034;SLOW_RESPONSE&#034;,<br \/>\n                pattern&#061;r&#039;.*response_time.*&gt;\\\\d{4}&#039;,<br \/>\n                description&#061;&#034;Slow response time (&gt;1000ms)&#034;,<br \/>\n                severity&#061;&#034;INFO&#034;,<br \/>\n                alert_threshold&#061;50<br \/>\n            ),<\/p>\n<p>            # \u5b89\u5168\u6a21\u5f0f<br \/>\n            LogPattern(<br \/>\n                name&#061;&#034;SQL_INJECTION_ATTEMPT&#034;,<br \/>\n                pattern&#061;r&#039;.*(SELECT|INSERT|UPDATE|DELETE|UNION).*&#039;,<br \/>\n                description&#061;&#034;Possible SQL injection attempt&#034;,<br \/>\n                severity&#061;&#034;CRITICAL&#034;,<br \/>\n                alert_threshold&#061;1<br \/>\n            ),<br \/>\n            LogPattern(<br \/>\n                name&#061;&#034;XSS_ATTEMPT&#034;,<br \/>\n                pattern&#061;r&#039;.*&lt;script&gt;.*&#039;,<br \/>\n                description&#061;&#034;Possible XSS attempt&#034;,<br \/>\n                severity&#061;&#034;CRITICAL&#034;,<br \/>\n                alert_threshold&#061;1<br \/>\n            ),<\/p>\n<p>            # \u4e1a\u52a1\u6a21\u5f0f<br \/>\n            LogPattern(<br \/>\n                name&#061;&#034;OUT_OF_STOCK&#034;,<br \/>\n                pattern&#061;r&#039;.*460.*out.*stock&#039;,<br \/>\n                description&#061;&#034;Product out of stock&#034;,<br \/>\n                severity&#061;&#034;INFO&#034;,<br \/>\n                alert_threshold&#061;100<br \/>\n            ),<br \/>\n            LogPattern(<br \/>\n                name&#061;&#034;PAYMENT_FAILURE&#034;,<br \/>\n                pattern&#061;r&#039;.*4\\\\d{2}.*payment&#039;,<br \/>\n                description&#061;&#034;Payment processing failures&#034;,<br \/>\n                severity&#061;&#034;WARNING&#034;,<br \/>\n                alert_threshold&#061;10<br \/>\n            )<br \/>\n        ]<\/p>\n<p>    def analyze_log_entry(self, entry: LogEntry):<br \/>\n        &#034;&#034;&#034;\u5206\u6790\u65e5\u5fd7\u6761\u76ee&#034;&#034;&#034;<br \/>\n        # \u66f4\u65b0\u57fa\u672c\u7edf\u8ba1<br \/>\n        self._update_basic_stats(entry)<\/p>\n<p>        # \u6a21\u5f0f\u5339\u914d<br \/>\n        matched_patterns &#061; self._match_patterns(entry)<\/p>\n<p>        # \u66f4\u65b0\u6a21\u5f0f\u8ba1\u6570<br \/>\n        for pattern in matched_patterns:<br \/>\n            self.pattern_counts[pattern.name] &#043;&#061; 1<\/p>\n<p>        # \u5f02\u5e38\u68c0\u6d4b<br \/>\n        anomalies &#061; self.anomaly_detector.detect(entry, self.stats)<\/p>\n<p>        # \u89e6\u53d1\u544a\u8b66<br \/>\n        if matched_patterns or anomalies:<br \/>\n            self._trigger_alerts(entry, matched_patterns, anomalies)<\/p>\n<p>        # \u6301\u4e45\u5316\u5206\u6790\u7ed3\u679c<br \/>\n        self._persist_analysis(entry, matched_patterns, anomalies)<\/p>\n<p>    def _update_basic_stats(self, entry: LogEntry):<br \/>\n        &#034;&#034;&#034;\u66f4\u65b0\u57fa\u672c\u7edf\u8ba1&#034;&#034;&#034;<br \/>\n        minute_key &#061; entry.timestamp.strftime(&#034;%Y-%m-%d %H:%M&#034;)<\/p>\n<p>        # \u6309\u5206\u949f\u7edf\u8ba1<br \/>\n        self.stats[&#039;by_minute&#039;][minute_key] &#043;&#061; 1<\/p>\n<p>        # \u6309\u72b6\u6001\u7801\u7edf\u8ba1<br \/>\n        self.stats[&#039;by_status_code&#039;][entry.status_code] &#043;&#061; 1<\/p>\n<p>        # \u6309\u7aef\u70b9\u7edf\u8ba1<br \/>\n        self.stats[&#039;by_endpoint&#039;][entry.endpoint] &#043;&#061; 1<\/p>\n<p>        # \u6309\u5ba2\u6237\u7aef\u7edf\u8ba1<br \/>\n        self.stats[&#039;by_client&#039;][entry.client_ip] &#043;&#061; 1<\/p>\n<p>        # \u54cd\u5e94\u65f6\u95f4\u7edf\u8ba1<br \/>\n        if &#039;response_times&#039; not in self.stats:<br \/>\n            self.stats[&#039;response_times&#039;] &#061; []<br \/>\n        self.stats[&#039;response_times&#039;].append(entry.response_time_ms)<\/p>\n<p>        # \u4fdd\u6301\u6570\u636e\u91cf\u53ef\u63a7<br \/>\n        if len(self.stats[&#039;response_times&#039;]) &gt; 10000:<br \/>\n            self.stats[&#039;response_times&#039;] &#061; self.stats[&#039;response_times&#039;][-10000:]<\/p>\n<p>    def _match_patterns(self, entry: LogEntry) -&gt; List[LogPattern]:<br \/>\n        &#034;&#034;&#034;\u5339\u914d\u65e5\u5fd7\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        matched &#061; []<\/p>\n<p>        for pattern in self.log_patterns:<br \/>\n            # \u68c0\u67e5\u6d88\u606f\u5339\u914d<br \/>\n            if pattern.compiled_pattern.search(entry.message):<br \/>\n                matched.append(pattern)<\/p>\n<p>            # \u68c0\u67e5\u72b6\u6001\u7801\u5339\u914d<br \/>\n            if str(entry.status_code) in pattern.pattern:<br \/>\n                matched.append(pattern)<\/p>\n<p>        return matched<\/p>\n<p>    def _trigger_alerts(self,<br \/>\n                       entry: LogEntry,<br \/>\n                       patterns: List[LogPattern],<br \/>\n                       anomalies: List[Dict]):<br \/>\n        &#034;&#034;&#034;\u89e6\u53d1\u544a\u8b66&#034;&#034;&#034;<br \/>\n        # \u68c0\u67e5\u6a21\u5f0f\u9608\u503c<br \/>\n        for pattern in patterns:<br \/>\n            current_count &#061; self.pattern_counts[pattern.name]<br \/>\n            if current_count &gt;&#061; pattern.alert_threshold:<br \/>\n                self._send_alert({<br \/>\n                    &#039;type&#039;: &#039;PATTERN_THRESHOLD_EXCEEDED&#039;,<br \/>\n                    &#039;pattern&#039;: pattern.name,<br \/>\n                    &#039;count&#039;: current_count,<br \/>\n                    &#039;threshold&#039;: pattern.alert_threshold,<br \/>\n                    &#039;log_entry&#039;: entry.to_dict(),<br \/>\n                    &#039;timestamp&#039;: datetime.now()<br \/>\n                })<\/p>\n<p>        # \u53d1\u9001\u5f02\u5e38\u544a\u8b66<br \/>\n        for anomaly in anomalies:<br \/>\n            self._send_alert({<br \/>\n                &#039;type&#039;: &#039;ANOMALY_DETECTED&#039;,<br \/>\n                &#039;anomaly&#039;: anomaly,<br \/>\n                &#039;log_entry&#039;: entry.to_dict(),<br \/>\n                &#039;timestamp&#039;: datetime.now()<br \/>\n            })<\/p>\n<p>    def _send_alert(self, alert: Dict):<br \/>\n        &#034;&#034;&#034;\u53d1\u9001\u544a\u8b66&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u96c6\u6210\u5230\u544a\u8b66\u7cfb\u7edf<br \/>\n        logging.warning(f&#034;ALERT: {json.dumps(alert, indent&#061;2, default&#061;str)}&#034;)<\/p>\n<p>    def _persist_analysis(self,<br \/>\n                         entry: LogEntry,<br \/>\n                         patterns: List[LogPattern],<br \/>\n                         anomalies: List[Dict]):<br \/>\n        &#034;&#034;&#034;\u6301\u4e45\u5316\u5206\u6790\u7ed3\u679c&#034;&#034;&#034;<br \/>\n        analysis_result &#061; {<br \/>\n            &#039;log_entry&#039;: entry.to_dict(),<br \/>\n            &#039;matched_patterns&#039;: [p.name for p in patterns],<br \/>\n            &#039;anomalies&#039;: anomalies,<br \/>\n            &#039;analysis_timestamp&#039;: datetime.now().isoformat()<br \/>\n        }<\/p>\n<p>        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u5199\u5165\u5206\u6790\u6570\u636e\u5e93<br \/>\n        # \u7b80\u5316&#xff1a;\u8bb0\u5f55\u5230\u6587\u4ef6<br \/>\n        with open(&#039;log_analysis.jsonl&#039;, &#039;a&#039;) as f:<br \/>\n            f.write(json.dumps(analysis_result) &#043; &#039;\\\\n&#039;)<\/p>\n<p>    def generate_report(self,<br \/>\n                       start_time: datetime,<br \/>\n                       end_time: datetime) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u5206\u6790\u62a5\u544a&#034;&#034;&#034;<br \/>\n        report &#061; {<br \/>\n            &#039;time_range&#039;: {<br \/>\n                &#039;start&#039;: start_time,<br \/>\n                &#039;end&#039;: end_time<br \/>\n            },<br \/>\n            &#039;summary&#039;: self._generate_summary(start_time, end_time),<br \/>\n            &#039;top_patterns&#039;: self._get_top_patterns(),<br \/>\n            &#039;status_code_analysis&#039;: self._analyze_status_codes(),<br \/>\n            &#039;endpoint_analysis&#039;: self._analyze_endpoints(),<br \/>\n            &#039;performance_analysis&#039;: self._analyze_performance(),<br \/>\n            &#039;security_analysis&#039;: self._analyze_security(),<br \/>\n            &#039;recommendations&#039;: []<br \/>\n        }<\/p>\n<p>        # \u751f\u6210\u5efa\u8bae<br \/>\n        report[&#039;recommendations&#039;] &#061; self._generate_recommendations(report)<\/p>\n<p>        return report<\/p>\n<p>    def _generate_summary(self,<br \/>\n                         start_time: datetime,<br \/>\n                         end_time: datetime) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u6458\u8981&#034;&#034;&#034;<br \/>\n        total_logs &#061; sum(self.stats[&#039;by_status_code&#039;].values())<\/p>\n<p>        # \u8ba1\u7b97\u5404\u7c7b\u522b\u6570\u91cf<br \/>\n        success_count &#061; sum(count for code, count in self.stats[&#039;by_status_code&#039;].items()<br \/>\n                          if 200 &lt;&#061; code &lt; 300)<br \/>\n        client_error_count &#061; sum(count for code, count in self.stats[&#039;by_status_code&#039;].items()<br \/>\n                               if 400 &lt;&#061; code &lt; 500)<br \/>\n        server_error_count &#061; sum(count for code, count in self.stats[&#039;by_status_code&#039;].items()<br \/>\n                               if 500 &lt;&#061; code &lt; 600)<\/p>\n<p>        return {<br \/>\n            &#039;total_logs&#039;: total_logs,<br \/>\n            &#039;success_count&#039;: success_count,<br \/>\n            &#039;client_error_count&#039;: client_error_count,<br \/>\n            &#039;server_error_count&#039;: server_error_count,<br \/>\n            &#039;success_rate&#039;: success_count \/ total_logs if total_logs &gt; 0 else 0,<br \/>\n            &#039;error_rate&#039;: (client_error_count &#043; server_error_count) \/ total_logs if total_logs &gt; 0 else 0,<br \/>\n            &#039;unique_endpoints&#039;: len(self.stats[&#039;by_endpoint&#039;]),<br \/>\n            &#039;unique_clients&#039;: len(self.stats[&#039;by_client&#039;]),<br \/>\n            &#039;patterns_detected&#039;: len(self.pattern_counts),<br \/>\n            &#039;anomalies_detected&#039;: self.anomaly_detector.total_anomalies<br \/>\n        }<\/p>\n<p>    def _get_top_patterns(self) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u9876\u90e8\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        top_patterns &#061; sorted(<br \/>\n            self.pattern_counts.items(),<br \/>\n            key&#061;lambda x: x[1],<br \/>\n            reverse&#061;True<br \/>\n        )[:10]<\/p>\n<p>        return [<br \/>\n            {<br \/>\n                &#039;pattern&#039;: pattern,<br \/>\n                &#039;count&#039;: count,<br \/>\n                &#039;alert_threshold&#039;: next(<br \/>\n                    (p.alert_threshold for p in self.log_patterns<br \/>\n                     if p.name &#061;&#061; pattern), 0<br \/>\n                )<br \/>\n            }<br \/>\n            for pattern, count in top_patterns<br \/>\n        ]<\/p>\n<p>    def _analyze_status_codes(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u5206\u6790\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        analysis &#061; {<br \/>\n            &#039;distribution&#039;: dict(self.stats[&#039;by_status_code&#039;]),<br \/>\n            &#039;top_error_codes&#039;: [],<br \/>\n            &#039;custom_codes&#039;: {},<br \/>\n            &#039;trends&#039;: self._calculate_status_trends()<br \/>\n        }<\/p>\n<p>        # \u627e\u51fa\u6700\u591a\u9519\u8bef\u7684\u72b6\u6001\u7801<br \/>\n        error_codes &#061; [(code, count) for code, count in self.stats[&#039;by_status_code&#039;].items()<br \/>\n                      if code &gt;&#061; 400]<br \/>\n        analysis[&#039;top_error_codes&#039;] &#061; sorted(error_codes, key&#061;lambda x: x[1], reverse&#061;True)[:5]<\/p>\n<p>        # \u8bc6\u522b\u81ea\u5b9a\u4e49\u72b6\u6001\u7801<br \/>\n        analysis[&#039;custom_codes&#039;] &#061; {<br \/>\n            code: count for code, count in self.stats[&#039;by_status_code&#039;].items()<br \/>\n            if (450 &lt;&#061; code &lt;&#061; 499) or (520 &lt;&#061; code &lt;&#061; 599)<br \/>\n        }<\/p>\n<p>        return analysis<\/p>\n<p>    def _calculate_status_trends(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u72b6\u6001\u7801\u8d8b\u52bf&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u57fa\u4e8e\u65f6\u95f4\u5e8f\u5217\u6570\u636e\u5206\u6790\u8d8b\u52bf<br \/>\n        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        trends &#061; {<br \/>\n            &#039;increasing_errors&#039;: [],<br \/>\n            &#039;decreasing_success&#039;: [],<br \/>\n            &#039;new_patterns&#039;: []<br \/>\n        }<\/p>\n<p>        # \u6a21\u62df\u8d8b\u52bf\u5206\u6790<br \/>\n        if self.stats[&#039;by_status_code&#039;].get(500, 0) &gt; 100:<br \/>\n            trends[&#039;increasing_errors&#039;].append({<br \/>\n                &#039;code&#039;: 500,<br \/>\n                &#039;trend&#039;: &#039;increasing&#039;,<br \/>\n                &#039;rate&#039;: 0.15  # 15%\u589e\u957f\u7387<br \/>\n            })<\/p>\n<p>        return trends<\/p>\n<p>    def _analyze_endpoints(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u5206\u6790\u7aef\u70b9&#034;&#034;&#034;<br \/>\n        endpoint_stats &#061; []<\/p>\n<p>        for endpoint, count in self.stats[&#039;by_endpoint&#039;].items():<br \/>\n            # \u8ba1\u7b97\u7aef\u70b9\u7684\u9519\u8bef\u7387&#xff08;\u9700\u8981\u66f4\u591a\u6570\u636e&#xff09;<br \/>\n            error_count &#061; 0  # \u5b9e\u9645\u4e2d\u9700\u8981\u4ece\u65e5\u5fd7\u8ba1\u7b97<\/p>\n<p>            endpoint_stats.append({<br \/>\n                &#039;endpoint&#039;: endpoint,<br \/>\n                &#039;total_requests&#039;: count,<br \/>\n                &#039;error_rate&#039;: error_count \/ count if count &gt; 0 else 0,<br \/>\n                &#039;top_status_codes&#039;: self._get_top_codes_for_endpoint(endpoint)<br \/>\n            })<\/p>\n<p>        # \u6309\u8bf7\u6c42\u6570\u6392\u5e8f<br \/>\n        endpoint_stats.sort(key&#061;lambda x: x[&#039;total_requests&#039;], reverse&#061;True)<\/p>\n<p>        return {<br \/>\n            &#039;total_endpoints&#039;: len(endpoint_stats),<br \/>\n            &#039;top_endpoints&#039;: endpoint_stats[:10],<br \/>\n            &#039;high_error_endpoints&#039;: [<br \/>\n                ep for ep in endpoint_stats<br \/>\n                if ep[&#039;error_rate&#039;] &gt; 0.1<br \/>\n            ][:5]<br \/>\n        }<\/p>\n<p>    def _get_top_codes_for_endpoint(self, endpoint: str) -&gt; List[Tuple[int, int]]:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u7aef\u70b9\u7684\u9876\u90e8\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u9700\u8981\u4ece\u65e5\u5fd7\u6570\u636e\u8ba1\u7b97<br \/>\n        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        return []<\/p>\n<p>    def _analyze_performance(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u5206\u6790\u6027\u80fd&#034;&#034;&#034;<br \/>\n        response_times &#061; self.stats.get(&#039;response_times&#039;, [])<\/p>\n<p>        if not response_times:<br \/>\n            return {}<\/p>\n<p>        import statistics<\/p>\n<p>        return {<br \/>\n            &#039;avg_response_time&#039;: statistics.mean(response_times),<br \/>\n            &#039;median_response_time&#039;: statistics.median(response_times),<br \/>\n            &#039;p90_response_time&#039;: self._calculate_percentile(response_times, 90),<br \/>\n            &#039;p95_response_time&#039;: self._calculate_percentile(response_times, 95),<br \/>\n            &#039;p99_response_time&#039;: self._calculate_percentile(response_times, 99),<br \/>\n            &#039;slow_endpoints&#039;: self._identify_slow_endpoints(),<br \/>\n            &#039;performance_trends&#039;: self._analyze_performance_trends()<br \/>\n        }<\/p>\n<p>    def _identify_slow_endpoints(self) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u8bc6\u522b\u6162\u7aef\u70b9&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u9700\u8981\u7aef\u70b9\u7ea7\u522b\u7684\u54cd\u5e94\u65f6\u95f4\u6570\u636e<br \/>\n        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        return []<\/p>\n<p>    def _analyze_performance_trends(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u5206\u6790\u6027\u80fd\u8d8b\u52bf&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u5206\u6790\u54cd\u5e94\u65f6\u95f4\u8d8b\u52bf<br \/>\n        return {}<\/p>\n<p>    def _analyze_security(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u5206\u6790\u5b89\u5168&#034;&#034;&#034;<br \/>\n        security_patterns &#061; [<br \/>\n            p.name for p in self.log_patterns<br \/>\n            if p.severity in [&#039;CRITICAL&#039;, &#039;HIGH&#039;]<br \/>\n        ]<\/p>\n<p>        security_counts &#061; {<br \/>\n            pattern: self.pattern_counts.get(pattern, 0)<br \/>\n            for pattern in security_patterns<br \/>\n        }<\/p>\n<p>        return {<br \/>\n            &#039;security_events&#039;: sum(security_counts.values()),<br \/>\n            &#039;event_distribution&#039;: security_counts,<br \/>\n            &#039;top_attack_vectors&#039;: sorted(<br \/>\n                security_counts.items(),<br \/>\n                key&#061;lambda x: x[1],<br \/>\n                reverse&#061;True<br \/>\n            )[:5],<br \/>\n            &#039;suspicious_clients&#039;: self._identify_suspicious_clients()<br \/>\n        }<\/p>\n<p>    def _identify_suspicious_clients(self) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u8bc6\u522b\u53ef\u7591\u5ba2\u6237\u7aef&#034;&#034;&#034;<br \/>\n        suspicious &#061; []<\/p>\n<p>        for client_ip, count in self.stats[&#039;by_client&#039;].items():<br \/>\n            # \u7b80\u5355\u7684\u53ef\u7591\u6027\u68c0\u67e5<br \/>\n            if count &gt; 1000:  # \u5927\u91cf\u8bf7\u6c42<br \/>\n                error_rate &#061; 0  # \u5b9e\u9645\u4e2d\u9700\u8981\u8ba1\u7b97<br \/>\n                security_events &#061; 0  # \u5b9e\u9645\u4e2d\u9700\u8981\u4ece\u6a21\u5f0f\u5339\u914d\u83b7\u53d6<\/p>\n<p>                if error_rate &gt; 0.3 or security_events &gt; 5:<br \/>\n                    suspicious.append({<br \/>\n                        &#039;client_ip&#039;: client_ip,<br \/>\n                        &#039;request_count&#039;: count,<br \/>\n                        &#039;error_rate&#039;: error_rate,<br \/>\n                        &#039;security_events&#039;: security_events<br \/>\n                    })<\/p>\n<p>        return suspicious<\/p>\n<p>    def _generate_recommendations(self, report: Dict) -&gt; List[str]:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u5efa\u8bae&#034;&#034;&#034;<br \/>\n        recommendations &#061; []<\/p>\n<p>        # \u57fa\u4e8e\u9519\u8bef\u7387<br \/>\n        if report[&#039;summary&#039;][&#039;error_rate&#039;] &gt; 0.1:<br \/>\n            recommendations.append(<br \/>\n                &#034;High error rate detected. Consider reviewing error handling and monitoring.&#034;<br \/>\n            )<\/p>\n<p>        # \u57fa\u4e8e5xx\u9519\u8bef<br \/>\n        if report[&#039;summary&#039;][&#039;server_error_count&#039;] &gt; 100:<br \/>\n            recommendations.append(<br \/>\n                &#034;High server error count. Investigate backend services and infrastructure.&#034;<br \/>\n            )<\/p>\n<p>        # \u57fa\u4e8e\u5b89\u5168\u4e8b\u4ef6<br \/>\n        if report[&#039;security_analysis&#039;][&#039;security_events&#039;] &gt; 50:<br \/>\n            recommendations.append(<br \/>\n                &#034;Multiple security events detected. Review WAF rules and access patterns.&#034;<br \/>\n            )<\/p>\n<p>        # \u57fa\u4e8e\u6027\u80fd<br \/>\n        perf &#061; report.get(&#039;performance_analysis&#039;, {})<br \/>\n        if perf.get(&#039;p95_response_time&#039;, 0) &gt; 3000:<br \/>\n            recommendations.append(<br \/>\n                &#034;High p95 response time. Consider performance optimization and scaling.&#034;<br \/>\n            )<\/p>\n<p>        return recommendations<\/p>\n<p>class LogAnomalyDetector:<br \/>\n    &#034;&#034;&#034;\u65e5\u5fd7\u5f02\u5e38\u68c0\u6d4b\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.historical_patterns &#061; defaultdict(list)<br \/>\n        self.anomalies_detected &#061; 0<\/p>\n<p>    &#064;property<br \/>\n    def total_anomalies(self):<br \/>\n        return self.anomalies_detected<\/p>\n<p>    def detect(self, entry: LogEntry, stats: Dict) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u5f02\u5e38&#034;&#034;&#034;<br \/>\n        anomalies &#061; []<\/p>\n<p>        # 1. \u5f02\u5e38\u72b6\u6001\u7801\u9891\u7387<br \/>\n        if self._is_unusual_status_code(entry, stats):<br \/>\n            anomalies.append({<br \/>\n                &#039;type&#039;: &#039;UNUSUAL_STATUS_CODE&#039;,<br \/>\n                &#039;code&#039;: entry.status_code,<br \/>\n                &#039;description&#039;: f&#039;Unusual frequency of status code {entry.status_code}&#039;<br \/>\n            })<\/p>\n<p>        # 2. \u5f02\u5e38\u54cd\u5e94\u65f6\u95f4<br \/>\n        if self._is_unusual_response_time(entry):<br \/>\n            anomalies.append({<br \/>\n                &#039;type&#039;: &#039;UNUSUAL_RESPONSE_TIME&#039;,<br \/>\n                &#039;response_time&#039;: entry.response_time_ms,<br \/>\n                &#039;description&#039;: f&#039;Unusually high response time: {entry.response_time_ms}ms&#039;<br \/>\n            })<\/p>\n<p>        # 3. \u5f02\u5e38\u8bf7\u6c42\u6a21\u5f0f<br \/>\n        if self._is_unusual_request_pattern(entry):<br \/>\n            anomalies.append({<br \/>\n                &#039;type&#039;: &#039;UNUSUAL_REQUEST_PATTERN&#039;,<br \/>\n                &#039;endpoint&#039;: entry.endpoint,<br \/>\n                &#039;description&#039;: f&#039;Unusual request pattern for endpoint {entry.endpoint}&#039;<br \/>\n            })<\/p>\n<p>        if anomalies:<br \/>\n            self.anomalies_detected &#043;&#061; 1<\/p>\n<p>        return anomalies<\/p>\n<p>    def _is_unusual_status_code(self, entry: LogEntry, stats: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u5f02\u5e38\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        total_requests &#061; sum(stats[&#039;by_status_code&#039;].values())<br \/>\n        if total_requests &#061;&#061; 0:<br \/>\n            return False<\/p>\n<p>        code_count &#061; stats[&#039;by_status_code&#039;].get(entry.status_code, 0)<br \/>\n        frequency &#061; code_count \/ total_requests<\/p>\n<p>        # \u5982\u679c\u72b6\u6001\u7801\u9891\u7387\u5f02\u5e38\u9ad8<br \/>\n        if entry.status_code &gt;&#061; 400 and frequency &gt; 0.05:  # \u9519\u8bef\u7801\u8d85\u8fc75%<br \/>\n            return True<\/p>\n<p>        # \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u51fa\u73b0<br \/>\n        if (450 &lt;&#061; entry.status_code &lt;&#061; 499) or (520 &lt;&#061; entry.status_code &lt;&#061; 599):<br \/>\n            # \u9996\u6b21\u51fa\u73b0\u6216\u9891\u7387\u5f02\u5e38<br \/>\n            if code_count &#061;&#061; 1 or frequency &gt; 0.01:  # \u81ea\u5b9a\u4e49\u7801\u8d85\u8fc71%<br \/>\n                return True<\/p>\n<p>        return False<\/p>\n<p>    def _is_unusual_response_time(self, entry: LogEntry) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u5f02\u5e38\u54cd\u5e94\u65f6\u95f4&#034;&#034;&#034;<br \/>\n        # \u7b80\u5355\u7684\u9608\u503c\u68c0\u67e5<br \/>\n        if entry.response_time_ms &gt; 10000:  # \u8d85\u8fc710\u79d2<br \/>\n            return True<\/p>\n<p>        # \u57fa\u4e8e\u7aef\u70b9\u7c7b\u578b\u7684\u68c0\u67e5<br \/>\n        if &#039;\/api\/&#039; in entry.endpoint and entry.response_time_ms &gt; 5000:<br \/>\n            return True<\/p>\n<p>        return False<\/p>\n<p>    def _is_unusual_request_pattern(self, entry: LogEntry) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u5f02\u5e38\u8bf7\u6c42\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        # \u68c0\u67e5\u53ef\u7591\u7aef\u70b9\u8bbf\u95ee<br \/>\n        suspicious_patterns &#061; [<br \/>\n            r&#039;\\\\.\\\\.\/&#039;,  # \u8def\u5f84\u904d\u5386<br \/>\n            r&#039;\\\\.env&#039;,  # \u914d\u7f6e\u6587\u4ef6<br \/>\n            r&#039;wp-admin&#039;,  # WordPress\u7ba1\u7406<br \/>\n            r&#039;phpmyadmin&#039;,  # \u6570\u636e\u5e93\u7ba1\u7406<br \/>\n            r&#039;shell&#039;,  # \u53ef\u80fd\u7684\u547d\u4ee4\u6ce8\u5165<br \/>\n        ]<\/p>\n<p>        for pattern in suspicious_patterns:<br \/>\n            if re.search(pattern, entry.endpoint, re.IGNORECASE):<br \/>\n                return True<\/p>\n<p>        return False<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nanalyzer &#061; StatusCodeLogAnalyzer()<\/p>\n<p># \u6a21\u62df\u65e5\u5fd7\u5904\u7406<br \/>\nlog_data &#061; [<br \/>\n    &#039;{&#034;timestamp&#034;: &#034;2023-10-01T10:00:00Z&#034;, &#034;level&#034;: &#034;INFO&#034;, &#034;message&#034;: &#034;GET \/api\/users 200&#034;, &#034;status_code&#034;: 200, &#034;endpoint&#034;: &#034;\/api\/users&#034;, &#034;method&#034;: &#034;GET&#034;, &#034;client_ip&#034;: &#034;192.168.1.1&#034;, &#034;response_time_ms&#034;: 150}&#039;,<br \/>\n    &#039;{&#034;timestamp&#034;: &#034;2023-10-01T10:00:01Z&#034;, &#034;level&#034;: &#034;ERROR&#034;, &#034;message&#034;: &#034;POST \/api\/orders 500 Internal Server Error&#034;, &#034;status_code&#034;: 500, &#034;endpoint&#034;: &#034;\/api\/orders&#034;, &#034;method&#034;: &#034;POST&#034;, &#034;client_ip&#034;: &#034;192.168.1.2&#034;, &#034;response_time_ms&#034;: 5000}&#039;,<br \/>\n    &#039;{&#034;timestamp&#034;: &#034;2023-10-01T10:00:02Z&#034;, &#034;level&#034;: &#034;WARNING&#034;, &#034;message&#034;: &#034;GET \/api\/products 460 Out of Stock&#034;, &#034;status_code&#034;: 460, &#034;endpoint&#034;: &#034;\/api\/products&#034;, &#034;method&#034;: &#034;GET&#034;, &#034;client_ip&#034;: &#034;192.168.1.3&#034;, &#034;response_time_ms&#034;: 200}&#039;,<br \/>\n]<\/p>\n<p>for log_line in log_data:<br \/>\n    try:<br \/>\n        entry &#061; LogEntry.from_json(log_line)<br \/>\n        analyzer.analyze_log_entry(entry)<br \/>\n    except json.JSONDecodeError as e:<br \/>\n        print(f&#034;Failed to parse log line: {e}&#034;)<\/p>\n<p># \u751f\u6210\u62a5\u544a<br \/>\nreport &#061; analyzer.generate_report(<br \/>\n    start_time&#061;datetime(2023, 10, 1, 10, 0, 0),<br \/>\n    end_time&#061;datetime(2023, 10, 1, 10, 5, 0)<br \/>\n)<\/p>\n<p>print(json.dumps(report, indent&#061;2, default&#061;str))<\/p>\n<h5>38.2.2 \u673a\u5668\u5b66\u4e60\u5f02\u5e38\u68c0\u6d4b<\/h5>\n<p>python<\/p>\n<p># \u57fa\u4e8e\u673a\u5668\u5b66\u4e60\u7684\u65e5\u5fd7\u5f02\u5e38\u68c0\u6d4b<br \/>\nfrom typing import List, Dict, Tuple<br \/>\nimport numpy as np<br \/>\nfrom sklearn.ensemble import IsolationForest<br \/>\nfrom sklearn.preprocessing import StandardScaler<br \/>\nfrom sklearn.cluster import DBSCAN<br \/>\nimport pandas as pd<br \/>\nfrom dataclasses import dataclass<br \/>\nfrom datetime import datetime<\/p>\n<p>&#064;dataclass<br \/>\nclass MLFeatures:<br \/>\n    &#034;&#034;&#034;\u673a\u5668\u5b66\u4e60\u7279\u5f81&#034;&#034;&#034;<br \/>\n    status_code: int<br \/>\n    response_time_ms: float<br \/>\n    request_size_bytes: int<br \/>\n    response_size_bytes: int<br \/>\n    hour_of_day: int<br \/>\n    day_of_week: int<br \/>\n    endpoint_depth: int<br \/>\n    has_query_params: int  # 0 or 1<br \/>\n    is_authenticated: int  # 0 or 1<br \/>\n    client_request_rate: float<\/p>\n<p>    def to_array(self) -&gt; np.ndarray:<br \/>\n        &#034;&#034;&#034;\u8f6c\u6362\u4e3anumpy\u6570\u7ec4&#034;&#034;&#034;<br \/>\n        return np.array([<br \/>\n            self.status_code,<br \/>\n            self.response_time_ms,<br \/>\n            self.request_size_bytes,<br \/>\n            self.response_size_bytes,<br \/>\n            self.hour_of_day,<br \/>\n            self.day_of_week,<br \/>\n            self.endpoint_depth,<br \/>\n            self.has_query_params,<br \/>\n            self.is_authenticated,<br \/>\n            self.client_request_rate<br \/>\n        ])<\/p>\n<p>class MLAnomalyDetector:<br \/>\n    &#034;&#034;&#034;\u673a\u5668\u5b66\u4e60\u5f02\u5e38\u68c0\u6d4b\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.isolation_forest &#061; IsolationForest(<br \/>\n            n_estimators&#061;100,<br \/>\n            contamination&#061;0.1,  # \u9884\u671f\u5f02\u5e38\u6bd4\u4f8b<br \/>\n            random_state&#061;42<br \/>\n        )<br \/>\n        self.dbscan &#061; DBSCAN(eps&#061;0.5, min_samples&#061;10)<br \/>\n        self.scaler &#061; StandardScaler()<br \/>\n        self.is_trained &#061; False<br \/>\n        self.feature_history: List[np.ndarray] &#061; []<br \/>\n        self.max_history_size &#061; 10000<\/p>\n<p>    def extract_features(self, log_entry: LogEntry, context: Dict) -&gt; MLFeatures:<br \/>\n        &#034;&#034;&#034;\u4ece\u65e5\u5fd7\u6761\u76ee\u63d0\u53d6\u7279\u5f81&#034;&#034;&#034;<br \/>\n        # \u7aef\u70b9\u6df1\u5ea6&#xff08;\u659c\u6760\u6570\u91cf&#xff09;<br \/>\n        endpoint_depth &#061; len(log_entry.endpoint.split(&#039;\/&#039;)) &#8211; 1<\/p>\n<p>        # \u662f\u5426\u6709\u67e5\u8be2\u53c2\u6570<br \/>\n        has_query_params &#061; 1 if &#039;?&#039; in log_entry.endpoint else 0<\/p>\n<p>        # \u662f\u5426\u8ba4\u8bc1&#xff08;\u6839\u636e\u72b6\u6001\u7801\u63a8\u6d4b&#xff09;<br \/>\n        is_authenticated &#061; 0 if log_entry.status_code in [401, 403] else 1<\/p>\n<p>        # \u5ba2\u6237\u7aef\u8bf7\u6c42\u7387&#xff08;\u4ece\u4e0a\u4e0b\u6587\u83b7\u53d6&#xff09;<br \/>\n        client_request_rate &#061; context.get(&#039;client_request_rate&#039;, 0.0)<\/p>\n<p>        return MLFeatures(<br \/>\n            status_code&#061;log_entry.status_code,<br \/>\n            response_time_ms&#061;log_entry.response_time_ms,<br \/>\n            request_size_bytes&#061;context.get(&#039;request_size&#039;, 0),<br \/>\n            response_size_bytes&#061;context.get(&#039;response_size&#039;, 0),<br \/>\n            hour_of_day&#061;log_entry.timestamp.hour,<br \/>\n            day_of_week&#061;log_entry.timestamp.weekday(),<br \/>\n            endpoint_depth&#061;endpoint_depth,<br \/>\n            has_query_params&#061;has_query_params,<br \/>\n            is_authenticated&#061;is_authenticated,<br \/>\n            client_request_rate&#061;client_request_rate<br \/>\n        )<\/p>\n<p>    def train(self, training_data: List[MLFeatures]):<br \/>\n        &#034;&#034;&#034;\u8bad\u7ec3\u6a21\u578b&#034;&#034;&#034;<br \/>\n        if not training_data:<br \/>\n            raise ValueError(&#034;No training data provided&#034;)<\/p>\n<p>        # \u8f6c\u6362\u4e3a\u7279\u5f81\u77e9\u9635<br \/>\n        X &#061; np.array([f.to_array() for f in training_data])<\/p>\n<p>        # \u6807\u51c6\u5316\u7279\u5f81<br \/>\n        X_scaled &#061; self.scaler.fit_transform(X)<\/p>\n<p>        # \u8bad\u7ec3\u9694\u79bb\u68ee\u6797<br \/>\n        self.isolation_forest.fit(X_scaled)<\/p>\n<p>        # \u8bad\u7ec3DBSCAN&#xff08;\u7528\u4e8e\u805a\u7c7b\u5206\u6790&#xff09;<br \/>\n        self.dbscan.fit(X_scaled)<\/p>\n<p>        self.is_trained &#061; True<br \/>\n        self.feature_history &#061; list(X_scaled)<\/p>\n<p>        print(f&#034;Trained on {len(training_data)} samples&#034;)<\/p>\n<p>    def detect_anomalies(self, features: MLFeatures) -&gt; Dict[str, any]:<br \/>\n        &#034;&#034;&#034;\u68c0\u6d4b\u5f02\u5e38&#034;&#034;&#034;<br \/>\n        if not self.is_trained:<br \/>\n            return {&#039;is_anomaly&#039;: False, &#039;reason&#039;: &#039;Model not trained&#039;}<\/p>\n<p>        # \u8f6c\u6362\u4e3a\u7279\u5f81\u5411\u91cf<br \/>\n        X &#061; features.to_array().reshape(1, -1)<br \/>\n        X_scaled &#061; self.scaler.transform(X)<\/p>\n<p>        # \u4f7f\u7528\u9694\u79bb\u68ee\u6797\u9884\u6d4b<br \/>\n        isolation_pred &#061; self.isolation_forest.predict(X_scaled)[0]<br \/>\n        isolation_score &#061; self.isolation_forest.decision_function(X_scaled)[0]<\/p>\n<p>        # \u4f7f\u7528DBSCAN\u805a\u7c7b<br \/>\n        cluster_label &#061; self.dbscan.fit_predict(<br \/>\n            np.vstack([self.feature_history, X_scaled])<br \/>\n        )[-1]<\/p>\n<p>        # \u66f4\u65b0\u5386\u53f2<br \/>\n        self.feature_history.append(X_scaled[0])<br \/>\n        if len(self.feature_history) &gt; self.max_history_size:<br \/>\n            self.feature_history &#061; self.feature_history[-self.max_history_size:]<\/p>\n<p>        # \u5206\u6790\u7ed3\u679c<br \/>\n        is_anomaly &#061; isolation_pred &#061;&#061; -1<br \/>\n        anomaly_type &#061; self._classify_anomaly(features, isolation_score, cluster_label)<\/p>\n<p>        return {<br \/>\n            &#039;is_anomaly&#039;: is_anomaly,<br \/>\n            &#039;anomaly_score&#039;: float(isolation_score),<br \/>\n            &#039;cluster_label&#039;: int(cluster_label),<br \/>\n            &#039;anomaly_type&#039;: anomaly_type,<br \/>\n            &#039;features&#039;: features.to_array().tolist(),<br \/>\n            &#039;explanation&#039;: self._explain_anomaly(features, anomaly_type)<br \/>\n        }<\/p>\n<p>    def _classify_anomaly(self,<br \/>\n                         features: MLFeatures,<br \/>\n                         anomaly_score: float,<br \/>\n                         cluster_label: int) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u5206\u7c7b\u5f02\u5e38\u7c7b\u578b&#034;&#034;&#034;<br \/>\n        # \u57fa\u4e8e\u7279\u5f81\u503c\u5206\u7c7b<\/p>\n<p>        # 1. \u72b6\u6001\u7801\u5f02\u5e38<br \/>\n        if features.status_code &gt;&#061; 500:<br \/>\n            return &#039;SERVER_ERROR_ANOMALY&#039;<\/p>\n<p>        # 2. \u54cd\u5e94\u65f6\u95f4\u5f02\u5e38<br \/>\n        if features.response_time_ms &gt; 10000:<br \/>\n            return &#039;EXTREME_LATENCY&#039;<br \/>\n        elif features.response_time_ms &gt; 5000:<br \/>\n            return &#039;HIGH_LATENCY&#039;<\/p>\n<p>        # 3. \u8bf7\u6c42\u6a21\u5f0f\u5f02\u5e38<br \/>\n        if features.client_request_rate &gt; 100:  # 100 requests per second<br \/>\n            return &#039;HIGH_REQUEST_RATE&#039;<\/p>\n<p>        # 4. \u5b64\u7acb\u70b9&#xff08;\u4e0d\u5c5e\u4e8e\u4efb\u4f55\u805a\u7c7b&#xff09;<br \/>\n        if cluster_label &#061;&#061; -1:<br \/>\n            return &#039;OUTLIER_PATTERN&#039;<\/p>\n<p>        # 5. \u57fa\u4e8e\u5f02\u5e38\u5206\u6570<br \/>\n        if anomaly_score &lt; -0.5:<br \/>\n            return &#039;STRONG_ANOMALY&#039;<br \/>\n        elif anomaly_score &lt; -0.2:<br \/>\n            return &#039;MODERATE_ANOMALY&#039;<\/p>\n<p>        return &#039;UNKNOWN_ANOMALY&#039;<\/p>\n<p>    def _explain_anomaly(self, features: MLFeatures, anomaly_type: str) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u89e3\u91ca\u5f02\u5e38&#034;&#034;&#034;<br \/>\n        explanations &#061; {<br \/>\n            &#039;SERVER_ERROR_ANOMALY&#039;: f&#039;Server error (status {features.status_code}) detected with unusual pattern.&#039;,<br \/>\n            &#039;EXTREME_LATENCY&#039;: f&#039;Extreme response time: {features.response_time_ms:.0f}ms&#039;,<br \/>\n            &#039;HIGH_LATENCY&#039;: f&#039;High response time: {features.response_time_ms:.0f}ms&#039;,<br \/>\n            &#039;HIGH_REQUEST_RATE&#039;: f&#039;High client request rate: {features.client_request_rate:.1f} req\/s&#039;,<br \/>\n            &#039;OUTLIER_PATTERN&#039;: &#039;Request pattern does not match any known clusters.&#039;,<br \/>\n            &#039;STRONG_ANOMALY&#039;: &#039;Strong anomaly detected across multiple features.&#039;,<br \/>\n            &#039;MODERATE_ANOMALY&#039;: &#039;Moderate anomaly detected.&#039;,<br \/>\n            &#039;UNKNOWN_ANOMALY&#039;: &#039;Anomaly detected but type unknown.&#039;<br \/>\n        }<\/p>\n<p>        return explanations.get(anomaly_type, &#039;No explanation available.&#039;)<\/p>\n<p>    def batch_analyze(self, features_list: List[MLFeatures]) -&gt; pd.DataFrame:<br \/>\n        &#034;&#034;&#034;\u6279\u91cf\u5206\u6790&#034;&#034;&#034;<br \/>\n        if not features_list:<br \/>\n            return pd.DataFrame()<\/p>\n<p>        # \u8f6c\u6362\u4e3a\u7279\u5f81\u77e9\u9635<br \/>\n        X &#061; np.array([f.to_array() for f in features_list])<br \/>\n        X_scaled &#061; self.scaler.transform(X)<\/p>\n<p>        # \u9884\u6d4b<br \/>\n        predictions &#061; self.isolation_forest.predict(X_scaled)<br \/>\n        scores &#061; self.isolation_forest.decision_function(X_scaled)<\/p>\n<p>        # \u521b\u5efa\u7ed3\u679cDataFrame<br \/>\n        results &#061; []<br \/>\n        for i, features in enumerate(features_list):<br \/>\n            result &#061; self.detect_anomalies(features)<br \/>\n            results.append({<br \/>\n                &#039;is_anomaly&#039;: result[&#039;is_anomaly&#039;],<br \/>\n                &#039;anomaly_score&#039;: result[&#039;anomaly_score&#039;],<br \/>\n                &#039;anomaly_type&#039;: result[&#039;anomaly_type&#039;],<br \/>\n                &#039;status_code&#039;: features.status_code,<br \/>\n                &#039;response_time_ms&#039;: features.response_time_ms,<br \/>\n                &#039;client_request_rate&#039;: features.client_request_rate<br \/>\n            })<\/p>\n<p>        return pd.DataFrame(results)<\/p>\n<p>    def generate_cluster_report(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u805a\u7c7b\u62a5\u544a&#034;&#034;&#034;<br \/>\n        if not self.is_trained or len(self.feature_history) &lt; 100:<br \/>\n            return {}<\/p>\n<p>        X &#061; np.array(self.feature_history)<\/p>\n<p>        # \u91cd\u65b0\u805a\u7c7b&#xff08;\u4f7f\u7528\u6700\u65b0\u6570\u636e&#xff09;<br \/>\n        labels &#061; self.dbscan.fit_predict(X)<\/p>\n<p>        # \u5206\u6790\u6bcf\u4e2a\u805a\u7c7b<br \/>\n        unique_labels &#061; set(labels)<br \/>\n        cluster_report &#061; {}<\/p>\n<p>        for label in unique_labels:<br \/>\n            if label &#061;&#061; -1:  # \u566a\u58f0\u70b9<br \/>\n                continue<\/p>\n<p>            # \u83b7\u53d6\u805a\u7c7b\u4e2d\u7684\u6570\u636e\u70b9<br \/>\n            cluster_points &#061; X[labels &#061;&#061; label]<\/p>\n<p>            # \u8ba1\u7b97\u805a\u7c7b\u7edf\u8ba1<br \/>\n            cluster_report[f&#039;cluster_{label}&#039;] &#061; {<br \/>\n                &#039;size&#039;: len(cluster_points),<br \/>\n                &#039;mean_features&#039;: np.mean(cluster_points, axis&#061;0).tolist(),<br \/>\n                &#039;std_features&#039;: np.std(cluster_points, axis&#061;0).tolist(),<br \/>\n                &#039;representative_pattern&#039;: self._describe_cluster_pattern(cluster_points)<br \/>\n            }<\/p>\n<p>        # \u566a\u58f0\u70b9\u5206\u6790<br \/>\n        noise_points &#061; X[labels &#061;&#061; -1]<br \/>\n        if len(noise_points) &gt; 0:<br \/>\n            cluster_report[&#039;noise&#039;] &#061; {<br \/>\n                &#039;size&#039;: len(noise_points),<br \/>\n                &#039;description&#039;: &#039;Outliers and anomalies&#039;,<br \/>\n                &#039;percentage&#039;: len(noise_points) \/ len(X)<br \/>\n            }<\/p>\n<p>        return cluster_report<\/p>\n<p>    def _describe_cluster_pattern(self, cluster_points: np.ndarray) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u63cf\u8ff0\u805a\u7c7b\u6a21\u5f0f&#034;&#034;&#034;<br \/>\n        if len(cluster_points) &#061;&#061; 0:<br \/>\n            return &#034;Empty cluster&#034;<\/p>\n<p>        # \u8ba1\u7b97\u6bcf\u4e2a\u7279\u5f81\u7684\u5747\u503c<br \/>\n        means &#061; np.mean(cluster_points, axis&#061;0)<\/p>\n<p>        patterns &#061; []<\/p>\n<p>        # \u72b6\u6001\u7801\u6a21\u5f0f<br \/>\n        status_mean &#061; means[0]<br \/>\n        if status_mean &lt; 300:<br \/>\n            patterns.append(&#034;Mostly successful requests&#034;)<br \/>\n        elif status_mean &lt; 500:<br \/>\n            patterns.append(&#034;Mostly client errors&#034;)<br \/>\n        else:<br \/>\n            patterns.append(&#034;Mostly server errors&#034;)<\/p>\n<p>        # \u54cd\u5e94\u65f6\u95f4\u6a21\u5f0f<br \/>\n        response_time_mean &#061; means[1]<br \/>\n        if response_time_mean &gt; 2:  # \u6807\u51c6\u5316\u540e\u7684\u503c<br \/>\n            patterns.append(&#034;Slow responses&#034;)<br \/>\n        else:<br \/>\n            patterns.append(&#034;Fast responses&#034;)<\/p>\n<p>        # \u65f6\u95f4\u6a21\u5f0f<br \/>\n        hour_mean &#061; means[4]<br \/>\n        if 9 &lt;&#061; hour_mean &lt;&#061; 17:<br \/>\n            patterns.append(&#034;Business hours&#034;)<br \/>\n        else:<br \/>\n            patterns.append(&#034;Off-hours&#034;)<\/p>\n<p>        return &#034;; &#034;.join(patterns)<\/p>\n<p># \u96c6\u6210\u5230\u65e5\u5fd7\u5206\u6790\u7cfb\u7edf<br \/>\nclass EnhancedLogAnalyzer(StatusCodeLogAnalyzer):<br \/>\n    &#034;&#034;&#034;\u589e\u5f3a\u7684\u65e5\u5fd7\u5206\u6790\u5668&#xff08;\u5e26ML&#xff09;&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        super().__init__()<br \/>\n        self.ml_detector &#061; MLAnomalyDetector()<br \/>\n        self.training_mode &#061; True<br \/>\n        self.training_samples: List[MLFeatures] &#061; []<br \/>\n        self.min_training_samples &#061; 1000<\/p>\n<p>    def analyze_log_entry(self, entry: LogEntry):<br \/>\n        &#034;&#034;&#034;\u5206\u6790\u65e5\u5fd7\u6761\u76ee&#xff08;ML\u589e\u5f3a&#xff09;&#034;&#034;&#034;<br \/>\n        # \u9996\u5148\u8fdb\u884c\u57fa\u672c\u5206\u6790<br \/>\n        super().analyze_log_entry(entry)<\/p>\n<p>        # \u63d0\u53d6ML\u7279\u5f81<br \/>\n        context &#061; self._extract_context(entry)<br \/>\n        features &#061; self.ml_detector.extract_features(entry, context)<\/p>\n<p>        if self.training_mode:<br \/>\n            # \u6536\u96c6\u8bad\u7ec3\u6837\u672c<br \/>\n            self.training_samples.append(features)<\/p>\n<p>            # \u5f53\u6709\u8db3\u591f\u6837\u672c\u65f6\u8bad\u7ec3\u6a21\u578b<br \/>\n            if len(self.training_samples) &gt;&#061; self.min_training_samples:<br \/>\n                print(f&#034;Training ML model with {len(self.training_samples)} samples&#8230;&#034;)<br \/>\n                self.ml_detector.train(self.training_samples)<br \/>\n                self.training_mode &#061; False<br \/>\n                print(&#034;ML model training completed&#034;)<\/p>\n<p>        else:<br \/>\n            # \u4f7f\u7528ML\u6a21\u578b\u68c0\u6d4b\u5f02\u5e38<br \/>\n            ml_result &#061; self.ml_detector.detect_anomalies(features)<\/p>\n<p>            if ml_result[&#039;is_anomaly&#039;]:<br \/>\n                # \u8bb0\u5f55ML\u68c0\u6d4b\u5230\u7684\u5f02\u5e38<br \/>\n                self._record_ml_anomaly(entry, ml_result)<\/p>\n<p>    def _extract_context(self, entry: LogEntry) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u63d0\u53d6\u4e0a\u4e0b\u6587\u4fe1\u606f&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u4ece\u5404\u79cd\u6765\u6e90\u83b7\u53d6\u4e0a\u4e0b\u6587<\/p>\n<p>        return {<br \/>\n            &#039;request_size&#039;: 0,  # \u4ece\u5176\u4ed6\u5730\u65b9\u83b7\u53d6<br \/>\n            &#039;response_size&#039;: 0,  # \u4ece\u5176\u4ed6\u5730\u65b9\u83b7\u53d6<br \/>\n            &#039;client_request_rate&#039;: self._calculate_client_rate(entry.client_ip)<br \/>\n        }<\/p>\n<p>    def _calculate_client_rate(self, client_ip: str) -&gt; float:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u5ba2\u6237\u7aef\u8bf7\u6c42\u7387&#034;&#034;&#034;<br \/>\n        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        return 0.0<\/p>\n<p>    def _record_ml_anomaly(self, entry: LogEntry, ml_result: Dict):<br \/>\n        &#034;&#034;&#034;\u8bb0\u5f55ML\u68c0\u6d4b\u5230\u7684\u5f02\u5e38&#034;&#034;&#034;<br \/>\n        anomaly_record &#061; {<br \/>\n            &#039;timestamp&#039;: datetime.now(),<br \/>\n            &#039;log_entry&#039;: entry.to_dict(),<br \/>\n            &#039;ml_result&#039;: ml_result,<br \/>\n            &#039;detector&#039;: &#039;ML_Anomaly_Detector&#039;<br \/>\n        }<\/p>\n<p>        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u8bb0\u5f55\u5230\u4e13\u95e8\u7684ML\u5f02\u5e38\u65e5\u5fd7<br \/>\n        logging.info(f&#034;ML anomaly detected: {anomaly_record}&#034;)<\/p>\n<p>        # \u89e6\u53d1\u544a\u8b66&#xff08;\u5982\u679c\u4e25\u91cd&#xff09;<br \/>\n        if ml_result[&#039;anomaly_score&#039;] &lt; -0.5:<br \/>\n            self._send_ml_alert(anomaly_record)<\/p>\n<p>    def _send_ml_alert(self, anomaly_record: Dict):<br \/>\n        &#034;&#034;&#034;\u53d1\u9001ML\u544a\u8b66&#034;&#034;&#034;<br \/>\n        alert &#061; {<br \/>\n            &#039;type&#039;: &#039;ML_ANOMALY_DETECTED&#039;,<br \/>\n            &#039;severity&#039;: &#039;HIGH&#039;,<br \/>\n            &#039;anomaly&#039;: anomaly_record[&#039;ml_result&#039;],<br \/>\n            &#039;log_entry&#039;: anomaly_record[&#039;log_entry&#039;],<br \/>\n            &#039;timestamp&#039;: anomaly_record[&#039;timestamp&#039;]<br \/>\n        }<\/p>\n<p>        self._send_alert(alert)<\/p>\n<p>    def generate_ml_report(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u751f\u6210ML\u62a5\u544a&#034;&#034;&#034;<br \/>\n        if self.training_mode:<br \/>\n            return {<br \/>\n                &#039;status&#039;: &#039;TRAINING&#039;,<br \/>\n                &#039;samples_collected&#039;: len(self.training_samples),<br \/>\n                &#039;samples_required&#039;: self.min_training_samples<br \/>\n            }<\/p>\n<p>        report &#061; {<br \/>\n            &#039;status&#039;: &#039;ACTIVE&#039;,<br \/>\n            &#039;model_info&#039;: {<br \/>\n                &#039;type&#039;: &#039;IsolationForest &#043; DBSCAN&#039;,<br \/>\n                &#039;features_used&#039;: 10,<br \/>\n                &#039;history_size&#039;: len(self.ml_detector.feature_history)<br \/>\n            },<br \/>\n            &#039;cluster_report&#039;: self.ml_detector.generate_cluster_report(),<br \/>\n            &#039;recent_anomalies&#039;: self._get_recent_ml_anomalies()<br \/>\n        }<\/p>\n<p>        return report<\/p>\n<p>    def _get_recent_ml_anomalies(self) -&gt; List[Dict]:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u6700\u8fd1\u7684ML\u5f02\u5e38&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u4ece\u5b58\u50a8\u4e2d\u83b7\u53d6<br \/>\n        return []<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nenhanced_analyzer &#061; EnhancedLogAnalyzer()<\/p>\n<p># \u5904\u7406\u65e5\u5fd7&#xff08;\u6a21\u62df&#xff09;<br \/>\nfor i in range(1500):<br \/>\n    entry &#061; LogEntry(<br \/>\n        timestamp&#061;datetime.now(),<br \/>\n        level&#061;&#034;INFO&#034;,<br \/>\n        message&#061;f&#034;Request {i}&#034;,<br \/>\n        status_code&#061;200 if i % 100 !&#061; 0 else 500,<br \/>\n        endpoint&#061;f&#034;\/api\/resource\/{i % 10}&#034;,<br \/>\n        method&#061;&#034;GET&#034;,<br \/>\n        client_ip&#061;f&#034;192.168.1.{i % 255}&#034;,<br \/>\n        response_time_ms&#061;np.random.exponential(100)<br \/>\n    )<\/p>\n<p>    enhanced_analyzer.analyze_log_entry(entry)<\/p>\n<p>    # \u6bcf100\u6761\u65e5\u5fd7\u663e\u793a\u8fdb\u5ea6<br \/>\n    if i % 100 &#061;&#061; 0:<br \/>\n        print(f&#034;Processed {i} logs&#034;)<\/p>\n<p># \u751f\u6210\u62a5\u544a<br \/>\nbasic_report &#061; enhanced_analyzer.generate_report(<br \/>\n    start_time&#061;datetime.now() &#8211; timedelta(hours&#061;1),<br \/>\n    end_time&#061;datetime.now()<br \/>\n)<\/p>\n<p>ml_report &#061; enhanced_analyzer.generate_ml_report()<\/p>\n<p>print(&#034;\\\\n&#061;&#061;&#061; Basic Report &#061;&#061;&#061;&#034;)<br \/>\nprint(f&#034;Total logs: {basic_report[&#039;summary&#039;][&#039;total_logs&#039;]}&#034;)<br \/>\nprint(f&#034;Error rate: {basic_report[&#039;summary&#039;][&#039;error_rate&#039;]:.2%}&#034;)<\/p>\n<p>print(&#034;\\\\n&#061;&#061;&#061; ML Report &#061;&#061;&#061;&#034;)<br \/>\nprint(f&#034;Status: {ml_report[&#039;status&#039;]}&#034;)<br \/>\nif &#039;cluster_report&#039; in ml_report:<br \/>\n    print(f&#034;Clusters found: {len(ml_report[&#039;cluster_report&#039;])}&#034;)<\/p>\n<h4>38.3 \u53ef\u89c6\u5316\u4e0e\u4eea\u8868\u677f<\/h4>\n<h5>38.3.1 \u5b9e\u65f6\u76d1\u63a7\u4eea\u8868\u677f<\/h5>\n<p>python<\/p>\n<p># \u72b6\u6001\u7801\u76d1\u63a7\u4eea\u8868\u677f<br \/>\nfrom typing import Dict, List<br \/>\nimport json<br \/>\nfrom datetime import datetime, timedelta<br \/>\nimport dash<br \/>\nfrom dash import dcc, html<br \/>\nfrom dash.dependencies import Input, Output<br \/>\nimport plotly.graph_objs as go<br \/>\nimport plotly.express as px<br \/>\nimport pandas as pd<\/p>\n<p>class StatusCodeDashboard:<br \/>\n    &#034;&#034;&#034;\u72b6\u6001\u7801\u76d1\u63a7\u4eea\u8868\u677f&#034;&#034;&#034;<\/p>\n<p>    def __init__(self, analyzer: StatusCodeLogAnalyzer):<br \/>\n        self.analyzer &#061; analyzer<br \/>\n        self.app &#061; dash.Dash(__name__)<br \/>\n        self._setup_layout()<br \/>\n        self._setup_callbacks()<\/p>\n<p>    def _setup_layout(self):<br \/>\n        &#034;&#034;&#034;\u8bbe\u7f6e\u5e03\u5c40&#034;&#034;&#034;<br \/>\n        self.app.layout &#061; html.Div([<br \/>\n            # \u6807\u9898<br \/>\n            html.H1(&#034;HTTP Status Code Monitoring Dashboard&#034;,<br \/>\n                   style&#061;{&#039;textAlign&#039;: &#039;center&#039;, &#039;color&#039;: &#039;#2c3e50&#039;}),<\/p>\n<p>            # \u63a7\u5236\u9762\u677f<br \/>\n            html.Div([<br \/>\n                html.Label(&#034;Time Range:&#034;),<br \/>\n                dcc.Dropdown(<br \/>\n                    id&#061;&#039;time-range&#039;,<br \/>\n                    options&#061;[<br \/>\n                        {&#039;label&#039;: &#039;Last 1 hour&#039;, &#039;value&#039;: &#039;1h&#039;},<br \/>\n                        {&#039;label&#039;: &#039;Last 6 hours&#039;, &#039;value&#039;: &#039;6h&#039;},<br \/>\n                        {&#039;label&#039;: &#039;Last 24 hours&#039;, &#039;value&#039;: &#039;24h&#039;},<br \/>\n                        {&#039;label&#039;: &#039;Last 7 days&#039;, &#039;value&#039;: &#039;7d&#039;}<br \/>\n                    ],<br \/>\n                    value&#061;&#039;1h&#039;,<br \/>\n                    style&#061;{&#039;width&#039;: &#039;200px&#039;}<br \/>\n                ),<\/p>\n<p>                html.Label(&#034;Refresh Interval (seconds):&#034;),<br \/>\n                dcc.Input(<br \/>\n                    id&#061;&#039;refresh-interval&#039;,<br \/>\n                    type&#061;&#039;number&#039;,<br \/>\n                    value&#061;30,<br \/>\n                    min&#061;5,<br \/>\n                    max&#061;300,<br \/>\n                    style&#061;{&#039;width&#039;: &#039;100px&#039;}<br \/>\n                ),<\/p>\n<p>                dcc.Interval(<br \/>\n                    id&#061;&#039;interval-component&#039;,<br \/>\n                    interval&#061;30*1000,  # 30\u79d2<br \/>\n                    n_intervals&#061;0<br \/>\n                )<br \/>\n            ], style&#061;{&#039;padding&#039;: &#039;20px&#039;, &#039;backgroundColor&#039;: &#039;#f8f9fa&#039;}),<\/p>\n<p>            # KPI\u5361\u7247<br \/>\n            html.Div(id&#061;&#039;kpi-cards&#039;, className&#061;&#039;row&#039;),<\/p>\n<p>            # \u56fe\u8868\u533a\u57df<br \/>\n            html.Div([<br \/>\n                # \u72b6\u6001\u7801\u5206\u5e03<br \/>\n                html.Div([<br \/>\n                    html.H3(&#034;Status Code Distribution&#034;),<br \/>\n                    dcc.Graph(id&#061;&#039;status-code-distribution&#039;)<br \/>\n                ], className&#061;&#039;six columns&#039;),<\/p>\n<p>                # \u65f6\u95f4\u5e8f\u5217<br \/>\n                html.Div([<br \/>\n                    html.H3(&#034;Requests Over Time&#034;),<br \/>\n                    dcc.Graph(id&#061;&#039;requests-over-time&#039;)<br \/>\n                ], className&#061;&#039;six columns&#039;),<br \/>\n            ], className&#061;&#039;row&#039;),<\/p>\n<p>            # \u9519\u8bef\u5206\u6790<br \/>\n            html.Div([<br \/>\n                html.H3(&#034;Error Analysis&#034;),<br \/>\n                html.Div([<br \/>\n                    dcc.Graph(id&#061;&#039;error-breakdown&#039;),<br \/>\n                    dcc.Graph(id&#061;&#039;endpoint-errors&#039;)<br \/>\n                ], className&#061;&#039;row&#039;)<br \/>\n            ]),<\/p>\n<p>            # \u6027\u80fd\u5206\u6790<br \/>\n            html.Div([<br \/>\n                html.H3(&#034;Performance Analysis&#034;),<br \/>\n                dcc.Graph(id&#061;&#039;response-time-distribution&#039;)<br \/>\n            ]),<\/p>\n<p>            # \u8be6\u7ec6\u4fe1\u606f\u8868\u683c<br \/>\n            html.Div([<br \/>\n                html.H3(&#034;Detailed Logs&#034;),<br \/>\n                html.Div(id&#061;&#039;log-table&#039;)<br \/>\n            ])<br \/>\n        ])<\/p>\n<p>    def _setup_callbacks(self):<br \/>\n        &#034;&#034;&#034;\u8bbe\u7f6e\u56de\u8c03&#034;&#034;&#034;<\/p>\n<p>        &#064;self.app.callback(<br \/>\n            [Output(&#039;kpi-cards&#039;, &#039;children&#039;),<br \/>\n             Output(&#039;status-code-distribution&#039;, &#039;figure&#039;),<br \/>\n             Output(&#039;requests-over-time&#039;, &#039;figure&#039;),<br \/>\n             Output(&#039;error-breakdown&#039;, &#039;figure&#039;),<br \/>\n             Output(&#039;endpoint-errors&#039;, &#039;figure&#039;),<br \/>\n             Output(&#039;response-time-distribution&#039;, &#039;figure&#039;),<br \/>\n             Output(&#039;log-table&#039;, &#039;children&#039;)],<br \/>\n            [Input(&#039;interval-component&#039;, &#039;n_intervals&#039;),<br \/>\n             Input(&#039;time-range&#039;, &#039;value&#039;)]<br \/>\n        )<br \/>\n        def update_dashboard(n_intervals, time_range):<br \/>\n            &#034;&#034;&#034;\u66f4\u65b0\u4eea\u8868\u677f&#034;&#034;&#034;<br \/>\n            # \u8ba1\u7b97\u65f6\u95f4\u8303\u56f4<br \/>\n            end_time &#061; datetime.now()<br \/>\n            start_time &#061; self._calculate_start_time(end_time, time_range)<\/p>\n<p>            # \u83b7\u53d6\u5206\u6790\u62a5\u544a<br \/>\n            report &#061; self.analyzer.generate_report(start_time, end_time)<\/p>\n<p>            # \u66f4\u65b0\u5404\u4e2a\u7ec4\u4ef6<br \/>\n            kpi_cards &#061; self._create_kpi_cards(report[&#039;summary&#039;])<br \/>\n            status_chart &#061; self._create_status_distribution_chart(report[&#039;status_code_analysis&#039;])<br \/>\n            time_chart &#061; self._create_time_series_chart()<br \/>\n            error_chart &#061; self._create_error_breakdown_chart(report[&#039;status_code_analysis&#039;])<br \/>\n            endpoint_chart &#061; self._create_endpoint_error_chart(report[&#039;endpoint_analysis&#039;])<br \/>\n            performance_chart &#061; self._create_performance_chart(report[&#039;performance_analysis&#039;])<br \/>\n            log_table &#061; self._create_log_table()<\/p>\n<p>            return (kpi_cards, status_chart, time_chart, error_chart,<br \/>\n                   endpoint_chart, performance_chart, log_table)<\/p>\n<p>    def _calculate_start_time(self, end_time: datetime, time_range: str) -&gt; datetime:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u5f00\u59cb\u65f6\u95f4&#034;&#034;&#034;<br \/>\n        if time_range &#061;&#061; &#039;1h&#039;:<br \/>\n            return end_time &#8211; timedelta(hours&#061;1)<br \/>\n        elif time_range &#061;&#061; &#039;6h&#039;:<br \/>\n            return end_time &#8211; timedelta(hours&#061;6)<br \/>\n        elif time_range &#061;&#061; &#039;24h&#039;:<br \/>\n            return end_time &#8211; timedelta(days&#061;1)<br \/>\n        elif time_range &#061;&#061; &#039;7d&#039;:<br \/>\n            return end_time &#8211; timedelta(days&#061;7)<br \/>\n        else:<br \/>\n            return end_time &#8211; timedelta(hours&#061;1)<\/p>\n<p>    def _create_kpi_cards(self, summary: Dict) -&gt; List[html.Div]:<br \/>\n        &#034;&#034;&#034;\u521b\u5efaKPI\u5361\u7247&#034;&#034;&#034;<br \/>\n        cards &#061; []<\/p>\n<p>        kpis &#061; [<br \/>\n            {<br \/>\n                &#039;title&#039;: &#039;Total Requests&#039;,<br \/>\n                &#039;value&#039;: summary.get(&#039;total_logs&#039;, 0),<br \/>\n                &#039;color&#039;: &#039;#3498db&#039;<br \/>\n            },<br \/>\n            {<br \/>\n                &#039;title&#039;: &#039;Success Rate&#039;,<br \/>\n                &#039;value&#039;: f&#034;{summary.get(&#039;success_rate&#039;, 0):.2%}&#034;,<br \/>\n                &#039;color&#039;: &#039;#2ecc71&#039;<br \/>\n            },<br \/>\n            {<br \/>\n                &#039;title&#039;: &#039;Error Rate&#039;,<br \/>\n                &#039;value&#039;: f&#034;{summary.get(&#039;error_rate&#039;, 0):.2%}&#034;,<br \/>\n                &#039;color&#039;: &#039;#e74c3c&#039;<br \/>\n            },<br \/>\n            {<br \/>\n                &#039;title&#039;: &#039;Avg Response Time&#039;,<br \/>\n                &#039;value&#039;: f&#034;{summary.get(&#039;avg_response_time&#039;, 0):.0f}ms&#034;,<br \/>\n                &#039;color&#039;: &#039;#f39c12&#039;<br \/>\n            },<br \/>\n            {<br \/>\n                &#039;title&#039;: &#039;Unique Clients&#039;,<br \/>\n                &#039;value&#039;: summary.get(&#039;unique_clients&#039;, 0),<br \/>\n                &#039;color&#039;: &#039;#9b59b6&#039;<br \/>\n            },<br \/>\n            {<br \/>\n                &#039;title&#039;: &#039;Patterns Detected&#039;,<br \/>\n                &#039;value&#039;: summary.get(&#039;patterns_detected&#039;, 0),<br \/>\n                &#039;color&#039;: &#039;#1abc9c&#039;<br \/>\n            }<br \/>\n        ]<\/p>\n<p>        for kpi in kpis:<br \/>\n            card &#061; html.Div([<br \/>\n                html.H4(kpi[&#039;title&#039;], style&#061;{&#039;margin&#039;: &#039;0&#039;}),<br \/>\n                html.H2(kpi[&#039;value&#039;], style&#061;{&#039;margin&#039;: &#039;10px 0&#039;, &#039;color&#039;: kpi[&#039;color&#039;]})<br \/>\n            ], style&#061;{<br \/>\n                &#039;padding&#039;: &#039;20px&#039;,<br \/>\n                &#039;margin&#039;: &#039;10px&#039;,<br \/>\n                &#039;backgroundColor&#039;: &#039;white&#039;,<br \/>\n                &#039;borderRadius&#039;: &#039;5px&#039;,<br \/>\n                &#039;boxShadow&#039;: &#039;0 2px 5px rgba(0,0,0,0.1)&#039;,<br \/>\n                &#039;textAlign&#039;: &#039;center&#039;,<br \/>\n                &#039;flex&#039;: &#039;1&#039;,<br \/>\n                &#039;minWidth&#039;: &#039;150px&#039;<br \/>\n            })<\/p>\n<p>            cards.append(card)<\/p>\n<p>        return html.Div(cards, style&#061;{&#039;display&#039;: &#039;flex&#039;, &#039;flexWrap&#039;: &#039;wrap&#039;})<\/p>\n<p>    def _create_status_distribution_chart(self, analysis: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u521b\u5efa\u72b6\u6001\u7801\u5206\u5e03\u56fe\u8868&#034;&#034;&#034;<br \/>\n        distribution &#061; analysis.get(&#039;distribution&#039;, {})<\/p>\n<p>        if not distribution:<br \/>\n            return {&#039;data&#039;: [], &#039;layout&#039;: {}}<\/p>\n<p>        # \u51c6\u5907\u6570\u636e<br \/>\n        codes &#061; list(distribution.keys())<br \/>\n        counts &#061; list(distribution.values())<\/p>\n<p>        # \u6309\u72b6\u6001\u7801\u7c7b\u522b\u7740\u8272<br \/>\n        colors &#061; []<br \/>\n        for code in codes:<br \/>\n            if 100 &lt;&#061; code &lt; 200:<br \/>\n                colors.append(&#039;#3498db&#039;)  # \u84dd\u8272 &#8211; \u4fe1\u606f<br \/>\n            elif 200 &lt;&#061; code &lt; 300:<br \/>\n                colors.append(&#039;#2ecc71&#039;)  # \u7eff\u8272 &#8211; \u6210\u529f<br \/>\n            elif 300 &lt;&#061; code &lt; 400:<br \/>\n                colors.append(&#039;#f1c40f&#039;)  # \u9ec4\u8272 &#8211; \u91cd\u5b9a\u5411<br \/>\n            elif 400 &lt;&#061; code &lt; 500:<br \/>\n                colors.append(&#039;#e67e22&#039;)  # \u6a59\u8272 &#8211; \u5ba2\u6237\u7aef\u9519\u8bef<br \/>\n            else:<br \/>\n                colors.append(&#039;#e74c3c&#039;)  # \u7ea2\u8272 &#8211; \u670d\u52a1\u5668\u9519\u8bef<\/p>\n<p>        fig &#061; go.Figure(data&#061;[<br \/>\n            go.Bar(<br \/>\n                x&#061;codes,<br \/>\n                y&#061;counts,<br \/>\n                marker_color&#061;colors,<br \/>\n                text&#061;counts,<br \/>\n                textposition&#061;&#039;auto&#039;,<br \/>\n                hovertemplate&#061;&#039;Status %{x}: %{y} requests&lt;extra&gt;&lt;\/extra&gt;&#039;<br \/>\n            )<br \/>\n        ])<\/p>\n<p>        fig.update_layout(<br \/>\n            title&#061;&#039;Status Code Distribution&#039;,<br \/>\n            xaxis_title&#061;&#039;Status Code&#039;,<br \/>\n            yaxis_title&#061;&#039;Number of Requests&#039;,<br \/>\n            showlegend&#061;False,<br \/>\n            plot_bgcolor&#061;&#039;white&#039;<br \/>\n        )<\/p>\n<p>        return fig<\/p>\n<p>    def _create_time_series_chart(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u521b\u5efa\u65f6\u95f4\u5e8f\u5217\u56fe\u8868&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u67e5\u8be2\u65f6\u95f4\u5e8f\u5217\u6570\u636e<br \/>\n        # \u7b80\u5316\u5b9e\u73b0<br \/>\n        fig &#061; go.Figure()<\/p>\n<p>        fig.update_layout(<br \/>\n            title&#061;&#039;Requests Over Time&#039;,<br \/>\n            xaxis_title&#061;&#039;Time&#039;,<br \/>\n            yaxis_title&#061;&#039;Requests per Minute&#039;,<br \/>\n            plot_bgcolor&#061;&#039;white&#039;<br \/>\n        )<\/p>\n<p>        return fig<\/p>\n<p>    def _create_error_breakdown_chart(self, analysis: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u521b\u5efa\u9519\u8bef\u5206\u89e3\u56fe\u8868&#034;&#034;&#034;<br \/>\n        top_errors &#061; analysis.get(&#039;top_error_codes&#039;, [])<\/p>\n<p>        if not top_errors:<br \/>\n            return {&#039;data&#039;: [], &#039;layout&#039;: {}}<\/p>\n<p>        codes &#061; [str(code) for code, count in top_errors]<br \/>\n        counts &#061; [count for code, count in top_errors]<\/p>\n<p>        fig &#061; go.Figure(data&#061;[<br \/>\n            go.Pie(<br \/>\n                labels&#061;codes,<br \/>\n                values&#061;counts,<br \/>\n                hole&#061;.3,<br \/>\n                hovertemplate&#061;&#039;Status %{label}: %{value} requests (%{percent})&lt;extra&gt;&lt;\/extra&gt;&#039;<br \/>\n            )<br \/>\n        ])<\/p>\n<p>        fig.update_layout(<br \/>\n            title&#061;&#039;Top Error Codes&#039;,<br \/>\n            showlegend&#061;True,<br \/>\n            plot_bgcolor&#061;&#039;white&#039;<br \/>\n        )<\/p>\n<p>        return fig<\/p>\n<p>    def _create_endpoint_error_chart(self, analysis: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u521b\u5efa\u7aef\u70b9\u9519\u8bef\u56fe\u8868&#034;&#034;&#034;<br \/>\n        high_error_endpoints &#061; analysis.get(&#039;high_error_endpoints&#039;, [])<\/p>\n<p>        if not high_error_endpoints:<br \/>\n            return {&#039;data&#039;: [], &#039;layout&#039;: {}}<\/p>\n<p>        endpoints &#061; [ep[&#039;endpoint&#039;] for ep in high_error_endpoints]<br \/>\n        error_rates &#061; [ep[&#039;error_rate&#039;] for ep in high_error_endpoints]<\/p>\n<p>        fig &#061; go.Figure(data&#061;[<br \/>\n            go.Bar(<br \/>\n                x&#061;endpoints,<br \/>\n                y&#061;error_rates,<br \/>\n                marker_color&#061;&#039;#e74c3c&#039;,<br \/>\n                text&#061;[f&#039;{rate:.2%}&#039; for rate in error_rates],<br \/>\n                textposition&#061;&#039;auto&#039;,<br \/>\n                hovertemplate&#061;&#039;%{x}&lt;br&gt;Error Rate: %{y:.2%}&lt;extra&gt;&lt;\/extra&gt;&#039;<br \/>\n            )<br \/>\n        ])<\/p>\n<p>        fig.update_layout(<br \/>\n            title&#061;&#039;Endpoints with High Error Rates (&gt;10%)&#039;,<br \/>\n            xaxis_title&#061;&#039;Endpoint&#039;,<br \/>\n            yaxis_title&#061;&#039;Error Rate&#039;,<br \/>\n            yaxis_tickformat&#061;&#039;.0%&#039;,<br \/>\n            plot_bgcolor&#061;&#039;white&#039;<br \/>\n        )<\/p>\n<p>        return fig<\/p>\n<p>    def _create_performance_chart(self, analysis: Dict) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u521b\u5efa\u6027\u80fd\u56fe\u8868&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u6709\u66f4\u591a\u6027\u80fd\u6570\u636e<br \/>\n        fig &#061; go.Figure()<\/p>\n<p>        # \u6dfb\u52a0\u54cd\u5e94\u65f6\u95f4\u5206\u5e03<br \/>\n        if &#039;response_time_stats&#039; in analysis:<br \/>\n            stats &#061; analysis[&#039;response_time_stats&#039;]<\/p>\n<p>            metrics &#061; [&#039;Mean&#039;, &#039;P90&#039;, &#039;P95&#039;, &#039;P99&#039;]<br \/>\n            values &#061; [<br \/>\n                stats.get(&#039;mean&#039;, 0),<br \/>\n                stats.get(&#039;p90&#039;, 0),<br \/>\n                stats.get(&#039;p95&#039;, 0),<br \/>\n                stats.get(&#039;p99&#039;, 0)<br \/>\n            ]<\/p>\n<p>            fig.add_trace(go.Bar(<br \/>\n                x&#061;metrics,<br \/>\n                y&#061;values,<br \/>\n                marker_color&#061;[&#039;#3498db&#039;, &#039;#2ecc71&#039;, &#039;#f39c12&#039;, &#039;#e74c3c&#039;],<br \/>\n                text&#061;[f&#039;{v:.0f}ms&#039; for v in values],<br \/>\n                textposition&#061;&#039;auto&#039;,<br \/>\n                hovertemplate&#061;&#039;%{x}: %{y:.0f}ms&lt;extra&gt;&lt;\/extra&gt;&#039;<br \/>\n            ))<\/p>\n<p>        fig.update_layout(<br \/>\n            title&#061;&#039;Response Time Statistics&#039;,<br \/>\n            xaxis_title&#061;&#039;Metric&#039;,<br \/>\n            yaxis_title&#061;&#039;Response Time (ms)&#039;,<br \/>\n            plot_bgcolor&#061;&#039;white&#039;<br \/>\n        )<\/p>\n<p>        return fig<\/p>\n<p>    def _create_log_table(self) -&gt; html.Table:<br \/>\n        &#034;&#034;&#034;\u521b\u5efa\u65e5\u5fd7\u8868\u683c&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u663e\u793a\u6700\u8fd1\u7684\u65e5\u5fd7<\/p>\n<p>        # \u521b\u5efa\u8868\u5934<br \/>\n        header &#061; html.Tr([<br \/>\n            html.Th(&#039;Timestamp&#039;),<br \/>\n            html.Th(&#039;Status&#039;),<br \/>\n            html.Th(&#039;Endpoint&#039;),<br \/>\n            html.Th(&#039;Method&#039;),<br \/>\n            html.Th(&#039;Response Time&#039;),<br \/>\n            html.Th(&#039;Client IP&#039;)<br \/>\n        ])<\/p>\n<p>        # \u521b\u5efa\u8868\u683c\u884c&#xff08;\u793a\u4f8b\u6570\u636e&#xff09;<br \/>\n        rows &#061; []<br \/>\n        for i in range(10):<br \/>\n            row &#061; html.Tr([<br \/>\n                html.Td(&#039;2023-10-01 10:00:00&#039;),<br \/>\n                html.Td(&#039;200&#039;, style&#061;{&#039;color&#039;: &#039;#2ecc71&#039;}),<br \/>\n                html.Td(&#039;\/api\/users&#039;),<br \/>\n                html.Td(&#039;GET&#039;),<br \/>\n                html.Td(&#039;150ms&#039;),<br \/>\n                html.Td(&#039;192.168.1.1&#039;)<br \/>\n            ])<br \/>\n            rows.append(row)<\/p>\n<p>        table &#061; html.Table(<br \/>\n            [header] &#043; rows,<br \/>\n            style&#061;{&#039;width&#039;: &#039;100%&#039;, &#039;borderCollapse&#039;: &#039;collapse&#039;}<br \/>\n        )<\/p>\n<p>        return table<\/p>\n<p>    def run(self, debug: bool &#061; True, port: int &#061; 8050):<br \/>\n        &#034;&#034;&#034;\u8fd0\u884c\u4eea\u8868\u677f&#034;&#034;&#034;<br \/>\n        self.app.run_server(debug&#061;debug, port&#061;port)<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nif __name__ &#061;&#061; &#039;__main__&#039;:<br \/>\n    # \u521b\u5efa\u5206\u6790\u5668<br \/>\n    analyzer &#061; StatusCodeLogAnalyzer()<\/p>\n<p>    # \u521b\u5efa\u4eea\u8868\u677f<br \/>\n    dashboard &#061; StatusCodeDashboard(analyzer)<\/p>\n<p>    # \u8fd0\u884c\u4eea\u8868\u677f<br \/>\n    # dashboard.run()<\/p>\n<h5>38.3.2 \u544a\u8b66\u4e0e\u901a\u77e5\u7cfb\u7edf<\/h5>\n<p>python<\/p>\n<p># \u544a\u8b66\u4e0e\u901a\u77e5\u7cfb\u7edf<br \/>\nfrom typing import Dict, List, Optional<br \/>\nfrom enum import Enum<br \/>\nfrom dataclasses import dataclass<br \/>\nfrom datetime import datetime, timedelta<br \/>\nimport asyncio<br \/>\nimport smtplib<br \/>\nfrom email.mime.text import MIMEText<br \/>\nfrom email.mime.multipart import MIMEMultipart<\/p>\n<p>class AlertSeverity(Enum):<br \/>\n    &#034;&#034;&#034;\u544a\u8b66\u4e25\u91cd\u7a0b\u5ea6&#034;&#034;&#034;<br \/>\n    INFO &#061; &#034;INFO&#034;<br \/>\n    WARNING &#061; &#034;WARNING&#034;<br \/>\n    ERROR &#061; &#034;ERROR&#034;<br \/>\n    CRITICAL &#061; &#034;CRITICAL&#034;<\/p>\n<p>class AlertChannel(Enum):<br \/>\n    &#034;&#034;&#034;\u544a\u8b66\u6e20\u9053&#034;&#034;&#034;<br \/>\n    EMAIL &#061; &#034;EMAIL&#034;<br \/>\n    SLACK &#061; &#034;SLACK&#034;<br \/>\n    SMS &#061; &#034;SMS&#034;<br \/>\n    WEBHOOK &#061; &#034;WEBHOOK&#034;<br \/>\n    PAGERDUTY &#061; &#034;PAGERDUTY&#034;<\/p>\n<p>&#064;dataclass<br \/>\nclass AlertRule:<br \/>\n    &#034;&#034;&#034;\u544a\u8b66\u89c4\u5219&#034;&#034;&#034;<br \/>\n    name: str<br \/>\n    condition: Dict<br \/>\n    severity: AlertSeverity<br \/>\n    channels: List[AlertChannel]<br \/>\n    cooldown_minutes: int &#061; 5<br \/>\n    enabled: bool &#061; True<\/p>\n<p>    def get_condition_type(self) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u6761\u4ef6\u7c7b\u578b&#034;&#034;&#034;<br \/>\n        return self.condition.get(&#039;type&#039;, &#039;unknown&#039;)<\/p>\n<p>    def check_condition(self, metrics: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u6761\u4ef6&#034;&#034;&#034;<br \/>\n        condition_type &#061; self.get_condition_type()<\/p>\n<p>        if condition_type &#061;&#061; &#039;error_rate&#039;:<br \/>\n            return self._check_error_rate(metrics)<br \/>\n        elif condition_type &#061;&#061; &#039;status_code&#039;:<br \/>\n            return self._check_status_code(metrics)<br \/>\n        elif condition_type &#061;&#061; &#039;response_time&#039;:<br \/>\n            return self._check_response_time(metrics)<br \/>\n        elif condition_type &#061;&#061; &#039;custom_code&#039;:<br \/>\n            return self._check_custom_code(metrics)<\/p>\n<p>        return False<\/p>\n<p>    def _check_error_rate(self, metrics: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u9519\u8bef\u7387&#034;&#034;&#034;<br \/>\n        threshold &#061; self.condition.get(&#039;threshold&#039;, 0.0)<br \/>\n        error_rate &#061; metrics.get(&#039;error_rate&#039;, 0.0)<\/p>\n<p>        operator &#061; self.condition.get(&#039;operator&#039;, &#039;&gt;&#039;)<\/p>\n<p>        if operator &#061;&#061; &#039;&gt;&#039;:<br \/>\n            return error_rate &gt; threshold<br \/>\n        elif operator &#061;&#061; &#039;&gt;&#061;&#039;:<br \/>\n            return error_rate &gt;&#061; threshold<br \/>\n        elif operator &#061;&#061; &#039;&#061;&#061;&#039;:<br \/>\n            return abs(error_rate &#8211; threshold) &lt; 0.001<br \/>\n        elif operator &#061;&#061; &#039;&lt;&#039;:<br \/>\n            return error_rate &lt; threshold<br \/>\n        elif operator &#061;&#061; &#039;&lt;&#061;&#039;:<br \/>\n            return error_rate &lt;&#061; threshold<\/p>\n<p>        return False<\/p>\n<p>    def _check_status_code(self, metrics: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        target_codes &#061; self.condition.get(&#039;codes&#039;, [])<br \/>\n        count_threshold &#061; self.condition.get(&#039;count_threshold&#039;, 0)<\/p>\n<p>        status_counts &#061; metrics.get(&#039;status_code_counts&#039;, {})<\/p>\n<p>        total_count &#061; 0<br \/>\n        for code in target_codes:<br \/>\n            total_count &#043;&#061; status_counts.get(code, 0)<\/p>\n<p>        return total_count &gt;&#061; count_threshold<\/p>\n<p>    def _check_response_time(self, metrics: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u54cd\u5e94\u65f6\u95f4&#034;&#034;&#034;<br \/>\n        threshold_ms &#061; self.condition.get(&#039;threshold_ms&#039;, 0)<br \/>\n        percentile &#061; self.condition.get(&#039;percentile&#039;, 95)<\/p>\n<p>        response_stats &#061; metrics.get(&#039;response_time_stats&#039;, {})<br \/>\n        p_value &#061; response_stats.get(f&#039;p{percentile}&#039;, 0)<\/p>\n<p>        return p_value &gt; threshold_ms<\/p>\n<p>    def _check_custom_code(self, metrics: Dict) -&gt; bool:<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u81ea\u5b9a\u4e49\u72b6\u6001\u7801&#034;&#034;&#034;<br \/>\n        code &#061; self.condition.get(&#039;code&#039;)<br \/>\n        threshold &#061; self.condition.get(&#039;threshold&#039;, 0)<\/p>\n<p>        custom_codes &#061; metrics.get(&#039;custom_codes&#039;, {})<br \/>\n        count &#061; custom_codes.get(code, 0)<\/p>\n<p>        return count &gt;&#061; threshold<\/p>\n<p>&#064;dataclass<br \/>\nclass Alert:<br \/>\n    &#034;&#034;&#034;\u544a\u8b66&#034;&#034;&#034;<br \/>\n    id: str<br \/>\n    rule_name: str<br \/>\n    severity: AlertSeverity<br \/>\n    message: str<br \/>\n    details: Dict<br \/>\n    timestamp: datetime<br \/>\n    acknowledged: bool &#061; False<br \/>\n    resolved: bool &#061; False<\/p>\n<p>    def to_dict(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u8f6c\u6362\u4e3a\u5b57\u5178&#034;&#034;&#034;<br \/>\n        return {<br \/>\n            &#039;id&#039;: self.id,<br \/>\n            &#039;rule_name&#039;: self.rule_name,<br \/>\n            &#039;severity&#039;: self.severity.value,<br \/>\n            &#039;message&#039;: self.message,<br \/>\n            &#039;details&#039;: self.details,<br \/>\n            &#039;timestamp&#039;: self.timestamp.isoformat(),<br \/>\n            &#039;acknowledged&#039;: self.acknowledged,<br \/>\n            &#039;resolved&#039;: self.resolved<br \/>\n        }<\/p>\n<p>class AlertManager:<br \/>\n    &#034;&#034;&#034;\u544a\u8b66\u7ba1\u7406\u5668&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.rules: List[AlertRule] &#061; []<br \/>\n        self.active_alerts: Dict[str, Alert] &#061; {}<br \/>\n        self.alert_history: List[Alert] &#061; []<br \/>\n        self.last_triggered: Dict[str, datetime] &#061; {}<br \/>\n        self.notification_channels &#061; self._initialize_channels()<\/p>\n<p>    def _initialize_channels(self) -&gt; Dict[AlertChannel, any]:<br \/>\n        &#034;&#034;&#034;\u521d\u59cb\u5316\u901a\u77e5\u6e20\u9053&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u521d\u59cb\u5316\u5404\u4e2a\u6e20\u9053\u7684\u5ba2\u6237\u7aef<\/p>\n<p>        return {<br \/>\n            AlertChannel.EMAIL: None,<br \/>\n            AlertChannel.SLACK: None,<br \/>\n            AlertChannel.SMS: None,<br \/>\n            AlertChannel.WEBHOOK: None,<br \/>\n            AlertChannel.PAGERDUTY: None<br \/>\n        }<\/p>\n<p>    def add_rule(self, rule: AlertRule):<br \/>\n        &#034;&#034;&#034;\u6dfb\u52a0\u544a\u8b66\u89c4\u5219&#034;&#034;&#034;<br \/>\n        self.rules.append(rule)<\/p>\n<p>    def check_metrics(self, metrics: Dict):<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u6307\u6807\u5e76\u89e6\u53d1\u544a\u8b66&#034;&#034;&#034;<br \/>\n        current_time &#061; datetime.now()<\/p>\n<p>        for rule in self.rules:<br \/>\n            if not rule.enabled:<br \/>\n                continue<\/p>\n<p>            # \u68c0\u67e5\u51b7\u5374\u671f<br \/>\n            last_trigger &#061; self.last_triggered.get(rule.name)<br \/>\n            if last_trigger:<br \/>\n                cooldown_end &#061; last_trigger &#043; timedelta(minutes&#061;rule.cooldown_minutes)<br \/>\n                if current_time &lt; cooldown_end:<br \/>\n                    continue<\/p>\n<p>            # \u68c0\u67e5\u6761\u4ef6<br \/>\n            if rule.check_condition(metrics):<br \/>\n                # \u89e6\u53d1\u544a\u8b66<br \/>\n                alert &#061; self._create_alert(rule, metrics)<\/p>\n<p>                # \u5b58\u50a8\u544a\u8b66<br \/>\n                self.active_alerts[alert.id] &#061; alert<br \/>\n                self.alert_history.append(alert)<\/p>\n<p>                # \u66f4\u65b0\u6700\u540e\u89e6\u53d1\u65f6\u95f4<br \/>\n                self.last_triggered[rule.name] &#061; current_time<\/p>\n<p>                # \u53d1\u9001\u901a\u77e5<br \/>\n                self._send_notifications(alert)<\/p>\n<p>    def _create_alert(self, rule: AlertRule, metrics: Dict) -&gt; Alert:<br \/>\n        &#034;&#034;&#034;\u521b\u5efa\u544a\u8b66&#034;&#034;&#034;<br \/>\n        import uuid<br \/>\n        from datetime import datetime<\/p>\n<p>        alert_id &#061; str(uuid.uuid4())<\/p>\n<p>        # \u6839\u636e\u89c4\u5219\u7c7b\u578b\u751f\u6210\u6d88\u606f<br \/>\n        message &#061; self._generate_alert_message(rule, metrics)<\/p>\n<p>        # \u521b\u5efa\u8be6\u60c5<br \/>\n        details &#061; {<br \/>\n            &#039;rule_condition&#039;: rule.condition,<br \/>\n            &#039;metrics_snapshot&#039;: metrics,<br \/>\n            &#039;trigger_time&#039;: datetime.now().isoformat()<br \/>\n        }<\/p>\n<p>        return Alert(<br \/>\n            id&#061;alert_id,<br \/>\n            rule_name&#061;rule.name,<br \/>\n            severity&#061;rule.severity,<br \/>\n            message&#061;message,<br \/>\n            details&#061;details,<br \/>\n            timestamp&#061;datetime.now()<br \/>\n        )<\/p>\n<p>    def _generate_alert_message(self, rule: AlertRule, metrics: Dict) -&gt; str:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u544a\u8b66\u6d88\u606f&#034;&#034;&#034;<br \/>\n        condition_type &#061; rule.get_condition_type()<\/p>\n<p>        if condition_type &#061;&#061; &#039;error_rate&#039;:<br \/>\n            error_rate &#061; metrics.get(&#039;error_rate&#039;, 0)<br \/>\n            threshold &#061; rule.condition.get(&#039;threshold&#039;, 0)<br \/>\n            return f&#034;Error rate {error_rate:.2%} exceeds threshold {threshold:.2%}&#034;<\/p>\n<p>        elif condition_type &#061;&#061; &#039;status_code&#039;:<br \/>\n            codes &#061; rule.condition.get(&#039;codes&#039;, [])<br \/>\n            threshold &#061; rule.condition.get(&#039;count_threshold&#039;, 0)<br \/>\n            return f&#034;Status codes {codes} count exceeds threshold {threshold}&#034;<\/p>\n<p>        elif condition_type &#061;&#061; &#039;response_time&#039;:<br \/>\n            percentile &#061; rule.condition.get(&#039;percentile&#039;, 95)<br \/>\n            threshold &#061; rule.condition.get(&#039;threshold_ms&#039;, 0)<\/p>\n<p>            response_stats &#061; metrics.get(&#039;response_time_stats&#039;, {})<br \/>\n            p_value &#061; response_stats.get(f&#039;p{percentile}&#039;, 0)<\/p>\n<p>            return f&#034;P{percentile} response time {p_value:.0f}ms exceeds threshold {threshold}ms&#034;<\/p>\n<p>        elif condition_type &#061;&#061; &#039;custom_code&#039;:<br \/>\n            code &#061; rule.condition.get(&#039;code&#039;)<br \/>\n            threshold &#061; rule.condition.get(&#039;threshold&#039;, 0)<\/p>\n<p>            custom_codes &#061; metrics.get(&#039;custom_codes&#039;, {})<br \/>\n            count &#061; custom_codes.get(code, 0)<\/p>\n<p>            return f&#034;Custom status code {code} count {count} exceeds threshold {threshold}&#034;<\/p>\n<p>        return f&#034;Alert triggered by rule: {rule.name}&#034;<\/p>\n<p>    def _send_notifications(self, alert: Alert):<br \/>\n        &#034;&#034;&#034;\u53d1\u9001\u901a\u77e5&#034;&#034;&#034;<br \/>\n        # \u627e\u5230\u89c4\u5219<br \/>\n        rule &#061; next((r for r in self.rules if r.name &#061;&#061; alert.rule_name), None)<br \/>\n        if not rule:<br \/>\n            return<\/p>\n<p>        # \u6839\u636e\u4e25\u91cd\u7a0b\u5ea6\u548c\u6e20\u9053\u53d1\u9001\u901a\u77e5<br \/>\n        for channel in rule.channels:<br \/>\n            try:<br \/>\n                if channel &#061;&#061; AlertChannel.EMAIL:<br \/>\n                    self._send_email_alert(alert, rule)<br \/>\n                elif channel &#061;&#061; AlertChannel.SLACK:<br \/>\n                    self._send_slack_alert(alert, rule)<br \/>\n                elif channel &#061;&#061; AlertChannel.SMS:<br \/>\n                    self._send_sms_alert(alert, rule)<br \/>\n                elif channel &#061;&#061; AlertChannel.WEBHOOK:<br \/>\n                    self._send_webhook_alert(alert, rule)<br \/>\n                elif channel &#061;&#061; AlertChannel.PAGERDUTY:<br \/>\n                    self._send_pagerduty_alert(alert, rule)<br \/>\n            except Exception as e:<br \/>\n                print(f&#034;Failed to send {channel.value} alert: {e}&#034;)<\/p>\n<p>    def _send_email_alert(self, alert: Alert, rule: AlertRule):<br \/>\n        &#034;&#034;&#034;\u53d1\u9001\u90ae\u4ef6\u544a\u8b66&#034;&#034;&#034;<br \/>\n        # \u914d\u7f6e\u90ae\u4ef6<br \/>\n        smtp_server &#061; &#034;smtp.example.com&#034;<br \/>\n        smtp_port &#061; 587<br \/>\n        sender_email &#061; &#034;alerts&#064;example.com&#034;<br \/>\n        receiver_emails &#061; [&#034;ops&#064;example.com&#034;, &#034;dev&#064;example.com&#034;]<\/p>\n<p>        # \u521b\u5efa\u90ae\u4ef6<br \/>\n        msg &#061; MIMEMultipart()<br \/>\n        msg[&#039;From&#039;] &#061; sender_email<br \/>\n        msg[&#039;To&#039;] &#061; &#034;, &#034;.join(receiver_emails)<br \/>\n        msg[&#039;Subject&#039;] &#061; f&#034;[{alert.severity.value}] {alert.message}&#034;<\/p>\n<p>        # \u90ae\u4ef6\u6b63\u6587<br \/>\n        body &#061; f&#034;&#034;&#034;<br \/>\n        Alert Details:<br \/>\n        &#8212;&#8212;&#8212;&#8212;&#8211;<br \/>\n        Rule: {alert.rule_name}<br \/>\n        Severity: {alert.severity.value}<br \/>\n        Message: {alert.message}<br \/>\n        Time: {alert.timestamp}<\/p>\n<p>        Details:<br \/>\n        {json.dumps(alert.details, indent&#061;2, default&#061;str)}<\/p>\n<p>        Active Alerts: {len(self.active_alerts)}<\/p>\n<p>        To acknowledge or resolve this alert, visit the dashboard.<br \/>\n        &#034;&#034;&#034;<\/p>\n<p>        msg.attach(MIMEText(body, &#039;plain&#039;))<\/p>\n<p>        # \u53d1\u9001\u90ae\u4ef6<br \/>\n        with smtplib.SMTP(smtp_server, smtp_port) as server:<br \/>\n            server.starttls()<br \/>\n            # server.login(sender_email, password)  # \u5982\u679c\u9700\u8981\u8ba4\u8bc1<br \/>\n            server.send_message(msg)<\/p>\n<p>    def _send_slack_alert(self, alert: Alert, rule: AlertRule):<br \/>\n        &#034;&#034;&#034;\u53d1\u9001Slack\u544a\u8b66&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u4f7f\u7528Slack API<br \/>\n        import requests<\/p>\n<p>        webhook_url &#061; &#034;https:\/\/hooks.slack.com\/services\/&#8230;&#034;<\/p>\n<p>        # \u6839\u636e\u4e25\u91cd\u7a0b\u5ea6\u8bbe\u7f6e\u989c\u8272<br \/>\n        color_map &#061; {<br \/>\n            AlertSeverity.INFO: &#034;#3498db&#034;,<br \/>\n            AlertSeverity.WARNING: &#034;#f39c12&#034;,<br \/>\n            AlertSeverity.ERROR: &#034;#e74c3c&#034;,<br \/>\n            AlertSeverity.CRITICAL: &#034;#8b0000&#034;<br \/>\n        }<\/p>\n<p>        payload &#061; {<br \/>\n            &#034;attachments&#034;: [<br \/>\n                {<br \/>\n                    &#034;color&#034;: color_map.get(alert.severity, &#034;#cccccc&#034;),<br \/>\n                    &#034;title&#034;: f&#034;Alert: {alert.rule_name}&#034;,<br \/>\n                    &#034;text&#034;: alert.message,<br \/>\n                    &#034;fields&#034;: [<br \/>\n                        {<br \/>\n                            &#034;title&#034;: &#034;Severity&#034;,<br \/>\n                            &#034;value&#034;: alert.severity.value,<br \/>\n                            &#034;short&#034;: True<br \/>\n                        },<br \/>\n                        {<br \/>\n                            &#034;title&#034;: &#034;Time&#034;,<br \/>\n                            &#034;value&#034;: alert.timestamp.strftime(&#034;%Y-%m-%d %H:%M:%S&#034;),<br \/>\n                            &#034;short&#034;: True<br \/>\n                        }<br \/>\n                    ],<br \/>\n                    &#034;footer&#034;: &#034;Status Code Monitoring&#034;,<br \/>\n                    &#034;ts&#034;: alert.timestamp.timestamp()<br \/>\n                }<br \/>\n            ]<br \/>\n        }<\/p>\n<p>        try:<br \/>\n            response &#061; requests.post(webhook_url, json&#061;payload)<br \/>\n            response.raise_for_status()<br \/>\n        except Exception as e:<br \/>\n            print(f&#034;Failed to send Slack alert: {e}&#034;)<\/p>\n<p>    def _send_sms_alert(self, alert: Alert, rule: AlertRule):<br \/>\n        &#034;&#034;&#034;\u53d1\u9001\u77ed\u4fe1\u544a\u8b66&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u4f7f\u7528\u77ed\u4fe1\u670d\u52a1API<br \/>\n        print(f&#034;SMS Alert: {alert.message}&#034;)<\/p>\n<p>    def _send_webhook_alert(self, alert: Alert, rule: AlertRule):<br \/>\n        &#034;&#034;&#034;\u53d1\u9001Webhook\u544a\u8b66&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u53d1\u9001\u5230\u914d\u7f6e\u7684webhook<br \/>\n        import requests<\/p>\n<p>        webhook_urls &#061; rule.condition.get(&#039;webhook_urls&#039;, [])<\/p>\n<p>        for url in webhook_urls:<br \/>\n            try:<br \/>\n                response &#061; requests.post(url, json&#061;alert.to_dict())<br \/>\n                response.raise_for_status()<br \/>\n            except Exception as e:<br \/>\n                print(f&#034;Failed to send webhook to {url}: {e}&#034;)<\/p>\n<p>    def _send_pagerduty_alert(self, alert: Alert, rule: AlertRule):<br \/>\n        &#034;&#034;&#034;\u53d1\u9001PagerDuty\u544a\u8b66&#034;&#034;&#034;<br \/>\n        # \u5728\u5b9e\u9645\u5b9e\u73b0\u4e2d&#xff0c;\u8fd9\u91cc\u4f1a\u4f7f\u7528PagerDuty API<br \/>\n        print(f&#034;PagerDuty Alert: {alert.message}&#034;)<\/p>\n<p>    def acknowledge_alert(self, alert_id: str, user: str):<br \/>\n        &#034;&#034;&#034;\u786e\u8ba4\u544a\u8b66&#034;&#034;&#034;<br \/>\n        if alert_id in self.active_alerts:<br \/>\n            alert &#061; self.active_alerts[alert_id]<br \/>\n            alert.acknowledged &#061; True<br \/>\n            alert.details[&#039;acknowledged_by&#039;] &#061; user<br \/>\n            alert.details[&#039;acknowledged_at&#039;] &#061; datetime.now().isoformat()<\/p>\n<p>    def resolve_alert(self, alert_id: str, user: str):<br \/>\n        &#034;&#034;&#034;\u89e3\u51b3\u544a\u8b66&#034;&#034;&#034;<br \/>\n        if alert_id in self.active_alerts:<br \/>\n            alert &#061; self.active_alerts[alert_id]<br \/>\n            alert.resolved &#061; True<br \/>\n            alert.details[&#039;resolved_by&#039;] &#061; user<br \/>\n            alert.details[&#039;resolved_at&#039;] &#061; datetime.now().isoformat()<\/p>\n<p>            # \u4ece\u6d3b\u52a8\u544a\u8b66\u4e2d\u79fb\u9664<br \/>\n            del self.active_alerts[alert_id]<\/p>\n<p>    def get_active_alerts(self) -&gt; List[Alert]:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u6d3b\u52a8\u544a\u8b66&#034;&#034;&#034;<br \/>\n        return list(self.active_alerts.values())<\/p>\n<p>    def get_alert_history(self,<br \/>\n                         start_time: Optional[datetime] &#061; None,<br \/>\n                         end_time: Optional[datetime] &#061; None) -&gt; List[Alert]:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u544a\u8b66\u5386\u53f2&#034;&#034;&#034;<br \/>\n        filtered &#061; self.alert_history<\/p>\n<p>        if start_time:<br \/>\n            filtered &#061; [a for a in filtered if a.timestamp &gt;&#061; start_time]<\/p>\n<p>        if end_time:<br \/>\n            filtered &#061; [a for a in filtered if a.timestamp &lt;&#061; end_time]<\/p>\n<p>        return filtered<\/p>\n<p>    def generate_alert_report(self,<br \/>\n                             start_time: datetime,<br \/>\n                             end_time: datetime) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u544a\u8b66\u62a5\u544a&#034;&#034;&#034;<br \/>\n        alerts_in_period &#061; self.get_alert_history(start_time, end_time)<\/p>\n<p>        # \u6309\u89c4\u5219\u5206\u7ec4<br \/>\n        rule_stats &#061; {}<br \/>\n        for alert in alerts_in_period:<br \/>\n            rule_name &#061; alert.rule_name<br \/>\n            if rule_name not in rule_stats:<br \/>\n                rule_stats[rule_name] &#061; {<br \/>\n                    &#039;total&#039;: 0,<br \/>\n                    &#039;by_severity&#039;: defaultdict(int),<br \/>\n                    &#039;avg_resolution_time&#039;: None,<br \/>\n                    &#039;last_triggered&#039;: alert.timestamp<br \/>\n                }<\/p>\n<p>            stats &#061; rule_stats[rule_name]<br \/>\n            stats[&#039;total&#039;] &#043;&#061; 1<br \/>\n            stats[&#039;by_severity&#039;][alert.severity.value] &#043;&#061; 1<\/p>\n<p>            if alert.resolved and &#039;triggered_at&#039; in alert.details:<br \/>\n                triggered &#061; datetime.fromisoformat(alert.details[&#039;triggered_at&#039;])<br \/>\n                resolved &#061; datetime.fromisoformat(alert.details[&#039;resolved_at&#039;])<br \/>\n                resolution_time &#061; (resolved &#8211; triggered).total_seconds()<\/p>\n<p>                if stats[&#039;avg_resolution_time&#039;] is None:<br \/>\n                    stats[&#039;avg_resolution_time&#039;] &#061; resolution_time<br \/>\n                else:<br \/>\n                    # \u79fb\u52a8\u5e73\u5747<br \/>\n                    stats[&#039;avg_resolution_time&#039;] &#061; (<br \/>\n                        stats[&#039;avg_resolution_time&#039;] * 0.7 &#043; resolution_time * 0.3<br \/>\n                    )<\/p>\n<p>        report &#061; {<br \/>\n            &#039;time_range&#039;: {<br \/>\n                &#039;start&#039;: start_time,<br \/>\n                &#039;end&#039;: end_time<br \/>\n            },<br \/>\n            &#039;total_alerts&#039;: len(alerts_in_period),<br \/>\n            &#039;rule_statistics&#039;: rule_stats,<br \/>\n            &#039;severity_distribution&#039;: self._calculate_severity_distribution(alerts_in_period),<br \/>\n            &#039;trends&#039;: self._calculate_alert_trends(start_time, end_time),<br \/>\n            &#039;recommendations&#039;: self._generate_alert_recommendations(rule_stats)<br \/>\n        }<\/p>\n<p>        return report<\/p>\n<p>    def _calculate_severity_distribution(self, alerts: List[Alert]) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u4e25\u91cd\u7a0b\u5ea6\u5206\u5e03&#034;&#034;&#034;<br \/>\n        distribution &#061; defaultdict(int)<\/p>\n<p>        for alert in alerts:<br \/>\n            distribution[alert.severity.value] &#043;&#061; 1<\/p>\n<p>        total &#061; len(alerts)<br \/>\n        if total &gt; 0:<br \/>\n            for severity in distribution:<br \/>\n                distribution[severity] &#061; distribution[severity] \/ total<\/p>\n<p>        return dict(distribution)<\/p>\n<p>    def _calculate_alert_trends(self,<br \/>\n                               start_time: datetime,<br \/>\n                               end_time: datetime) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u8ba1\u7b97\u544a\u8b66\u8d8b\u52bf&#034;&#034;&#034;<br \/>\n        # \u6309\u5c0f\u65f6\u5206\u7ec4<br \/>\n        hourly_alerts &#061; defaultdict(int)<\/p>\n<p>        current &#061; start_time<br \/>\n        while current &lt;&#061; end_time:<br \/>\n            hourly_alerts[current.strftime(&#034;%Y-%m-%d %H:00&#034;)] &#061; 0<br \/>\n            current &#043;&#061; timedelta(hours&#061;1)<\/p>\n<p>        for alert in self.alert_history:<br \/>\n            if start_time &lt;&#061; alert.timestamp &lt;&#061; end_time:<br \/>\n                hour_key &#061; alert.timestamp.strftime(&#034;%Y-%m-%d %H:00&#034;)<br \/>\n                if hour_key in hourly_alerts:<br \/>\n                    hourly_alerts[hour_key] &#043;&#061; 1<\/p>\n<p>        return {<br \/>\n            &#039;hourly_distribution&#039;: dict(hourly_alerts),<br \/>\n            &#039;peak_hour&#039;: max(hourly_alerts.items(), key&#061;lambda x: x[1]) if hourly_alerts else None,<br \/>\n            &#039;alert_rate_per_hour&#039;: len([a for a in self.alert_history<br \/>\n                                       if start_time &lt;&#061; a.timestamp &lt;&#061; end_time]) \/<br \/>\n                                 ((end_time &#8211; start_time).total_seconds() \/ 3600)<br \/>\n        }<\/p>\n<p>    def _generate_alert_recommendations(self, rule_stats: Dict) -&gt; List[str]:<br \/>\n        &#034;&#034;&#034;\u751f\u6210\u544a\u8b66\u5efa\u8bae&#034;&#034;&#034;<br \/>\n        recommendations &#061; []<\/p>\n<p>        for rule_name, stats in rule_stats.items():<br \/>\n            # \u9ad8\u9891\u544a\u8b66\u89c4\u5219<br \/>\n            if stats[&#039;total&#039;] &gt; 100:<br \/>\n                recommendations.append(<br \/>\n                    f&#034;Rule &#039;{rule_name}&#039; triggered {stats[&#039;total&#039;]} times. &#034;<br \/>\n                    f&#034;Consider adjusting thresholds or investigating root cause.&#034;<br \/>\n                )<\/p>\n<p>            # \u9ad8\u4e25\u91cd\u7a0b\u5ea6\u544a\u8b66<br \/>\n            if stats[&#039;by_severity&#039;].get(&#039;CRITICAL&#039;, 0) &gt; 10:<br \/>\n                recommendations.append(<br \/>\n                    f&#034;Rule &#039;{rule_name}&#039; has {stats[&#039;by_severity&#039;][&#039;CRITICAL&#039;]} critical alerts. &#034;<br \/>\n                    f&#034;Immediate attention required.&#034;<br \/>\n                )<\/p>\n<p>            # \u957f\u89e3\u51b3\u65f6\u95f4<br \/>\n            if stats[&#039;avg_resolution_time&#039;] and stats[&#039;avg_resolution_time&#039;] &gt; 3600:<br \/>\n                recommendations.append(<br \/>\n                    f&#034;Rule &#039;{rule_name}&#039; has average resolution time of &#034;<br \/>\n                    f&#034;{stats[&#039;avg_resolution_time&#039;]\/3600:.1f} hours. &#034;<br \/>\n                    f&#034;Consider improving response procedures.&#034;<br \/>\n                )<\/p>\n<p>        return recommendations<\/p>\n<p># \u96c6\u6210\u793a\u4f8b<br \/>\nclass MonitoringSystem:<br \/>\n    &#034;&#034;&#034;\u5b8c\u6574\u7684\u76d1\u63a7\u7cfb\u7edf&#034;&#034;&#034;<\/p>\n<p>    def __init__(self):<br \/>\n        self.log_analyzer &#061; EnhancedLogAnalyzer()<br \/>\n        self.alert_manager &#061; AlertManager()<br \/>\n        self._setup_alert_rules()<\/p>\n<p>    def _setup_alert_rules(self):<br \/>\n        &#034;&#034;&#034;\u8bbe\u7f6e\u544a\u8b66\u89c4\u5219&#034;&#034;&#034;<br \/>\n        # \u9519\u8bef\u7387\u544a\u8b66<br \/>\n        self.alert_manager.add_rule(AlertRule(<br \/>\n            name&#061;&#034;High Error Rate&#034;,<br \/>\n            condition&#061;{<br \/>\n                &#039;type&#039;: &#039;error_rate&#039;,<br \/>\n                &#039;threshold&#039;: 0.05,  # 5%<br \/>\n                &#039;operator&#039;: &#039;&gt;&#039;<br \/>\n            },<br \/>\n            severity&#061;AlertSeverity.ERROR,<br \/>\n            channels&#061;[AlertChannel.SLACK, AlertChannel.EMAIL],<br \/>\n            cooldown_minutes&#061;10<br \/>\n        ))<\/p>\n<p>        # 5xx\u9519\u8bef\u544a\u8b66<br \/>\n        self.alert_manager.add_rule(AlertRule(<br \/>\n            name&#061;&#034;High 5xx Errors&#034;,<br \/>\n            condition&#061;{<br \/>\n                &#039;type&#039;: &#039;status_code&#039;,<br \/>\n                &#039;codes&#039;: [500, 502, 503, 504],<br \/>\n                &#039;count_threshold&#039;: 10<br \/>\n            },<br \/>\n            severity&#061;AlertSeverity.CRITICAL,<br \/>\n            channels&#061;[AlertChannel.SLACK, AlertChannel.EMAIL, AlertChannel.PAGERDUTY],<br \/>\n            cooldown_minutes&#061;5<br \/>\n        ))<\/p>\n<p>        # \u54cd\u5e94\u65f6\u95f4\u544a\u8b66<br \/>\n        self.alert_manager.add_rule(AlertRule(<br \/>\n            name&#061;&#034;Slow Response Time&#034;,<br \/>\n            condition&#061;{<br \/>\n                &#039;type&#039;: &#039;response_time&#039;,<br \/>\n                &#039;threshold_ms&#039;: 5000,  # 5\u79d2<br \/>\n                &#039;percentile&#039;: 95<br \/>\n            },<br \/>\n            severity&#061;AlertSeverity.WARNING,<br \/>\n            channels&#061;[AlertChannel.SLACK],<br \/>\n            cooldown_minutes&#061;15<br \/>\n        ))<\/p>\n<p>        # \u81ea\u5b9a\u4e49\u72b6\u6001\u7801\u544a\u8b66<br \/>\n        self.alert_manager.add_rule(AlertRule(<br \/>\n            name&#061;&#034;High Custom Code 460&#034;,<br \/>\n            condition&#061;{<br \/>\n                &#039;type&#039;: &#039;custom_code&#039;,<br \/>\n                &#039;code&#039;: 460,<br \/>\n                &#039;threshold&#039;: 50<br \/>\n            },<br \/>\n            severity&#061;AlertSeverity.INFO,<br \/>\n            channels&#061;[AlertChannel.SLACK],<br \/>\n            cooldown_minutes&#061;30<br \/>\n        ))<\/p>\n<p>    def process_log_entry(self, entry: LogEntry):<br \/>\n        &#034;&#034;&#034;\u5904\u7406\u65e5\u5fd7\u6761\u76ee&#034;&#034;&#034;<br \/>\n        # \u5206\u6790\u65e5\u5fd7<br \/>\n        self.log_analyzer.analyze_log_entry(entry)<\/p>\n<p>        # \u5b9a\u671f\u68c0\u67e5\u544a\u8b66&#xff08;\u4f8b\u5982\u6bcf\u5206\u949f&#xff09;<br \/>\n        current_time &#061; datetime.now()<br \/>\n        if not hasattr(self, &#039;_last_alert_check&#039;):<br \/>\n            self._last_alert_check &#061; current_time<\/p>\n<p>        if (current_time &#8211; self._last_alert_check).total_seconds() &gt;&#061; 60:<br \/>\n            self._check_alerts()<br \/>\n            self._last_alert_check &#061; current_time<\/p>\n<p>    def _check_alerts(self):<br \/>\n        &#034;&#034;&#034;\u68c0\u67e5\u544a\u8b66&#034;&#034;&#034;<br \/>\n        # \u83b7\u53d6\u6700\u65b0\u6307\u6807<br \/>\n        report &#061; self.log_analyzer.generate_report(<br \/>\n            start_time&#061;datetime.now() &#8211; timedelta(minutes&#061;5),<br \/>\n            end_time&#061;datetime.now()<br \/>\n        )<\/p>\n<p>        # \u8f6c\u6362\u4e3a\u544a\u8b66\u7ba1\u7406\u5668\u9700\u8981\u7684\u683c\u5f0f<br \/>\n        metrics &#061; {<br \/>\n            &#039;error_rate&#039;: report[&#039;summary&#039;][&#039;error_rate&#039;],<br \/>\n            &#039;status_code_counts&#039;: report[&#039;status_code_analysis&#039;][&#039;distribution&#039;],<br \/>\n            &#039;response_time_stats&#039;: report[&#039;performance_analysis&#039;],<br \/>\n            &#039;custom_codes&#039;: report[&#039;status_code_analysis&#039;].get(&#039;custom_codes&#039;, {})<br \/>\n        }<\/p>\n<p>        # \u68c0\u67e5\u544a\u8b66<br \/>\n        self.alert_manager.check_metrics(metrics)<\/p>\n<p>    def get_dashboard_data(self) -&gt; Dict:<br \/>\n        &#034;&#034;&#034;\u83b7\u53d6\u4eea\u8868\u677f\u6570\u636e&#034;&#034;&#034;<br \/>\n        report &#061; self.log_analyzer.generate_report(<br \/>\n            start_time&#061;datetime.now() &#8211; timedelta(hours&#061;1),<br \/>\n            end_time&#061;datetime.now()<br \/>\n        )<\/p>\n<p>        alert_report &#061; self.alert_manager.get_alert_history(<br \/>\n            start_time&#061;datetime.now() &#8211; timedelta(hours&#061;24),<br \/>\n            end_time&#061;datetime.now()<br \/>\n        )<\/p>\n<p>        ml_report &#061; self.log_analyzer.generate_ml_report()<\/p>\n<p>        return {<br \/>\n            &#039;timestamp&#039;: datetime.now(),<br \/>\n            &#039;summary&#039;: report[&#039;summary&#039;],<br \/>\n            &#039;active_alerts&#039;: [a.to_dict() for a in self.alert_manager.get_active_alerts()],<br \/>\n            &#039;recent_alerts&#039;: [a.to_dict() for a in alert_report[:10]],<br \/>\n            &#039;ml_status&#039;: ml_report,<br \/>\n            &#039;recommendations&#039;: report[&#039;recommendations&#039;]<br \/>\n        }<\/p>\n<p># \u4f7f\u7528\u793a\u4f8b<br \/>\nmonitoring_system &#061; MonitoringSystem()<\/p>\n<p># \u6a21\u62df\u5904\u7406\u65e5\u5fd7<br \/>\nfor i in range(100):<br \/>\n    entry &#061; LogEntry(<br \/>\n        timestamp&#061;datetime.now(),<br \/>\n        level&#061;&#034;INFO&#034;,<br \/>\n        message&#061;f&#034;Test request {i}&#034;,<br \/>\n        status_code&#061;200 if i % 20 !&#061; 0 else 500,<br \/>\n        endpoint&#061;&#034;\/api\/test&#034;,<br \/>\n        method&#061;&#034;GET&#034;,<br \/>\n        client_ip&#061;&#034;192.168.1.1&#034;,<br \/>\n        response_time_ms&#061;100 &#043; i % 1000<br \/>\n    )<\/p>\n<p>    monitoring_system.process_log_entry(entry)<\/p>\n<p># \u83b7\u53d6\u4eea\u8868\u677f\u6570\u636e<br \/>\ndashboard_data &#061; monitoring_system.get_dashboard_data()<br \/>\nprint(f&#034;Total requests: {dashboard_data[&#039;summary&#039;][&#039;total_logs&#039;]}&#034;)<br \/>\nprint(f&#034;Active alerts: {len(dashboard_data[&#039;active_alerts&#039;])}&#034;)<\/p>\n<h4>38.4 \u603b\u7ed3<\/h4>\n<p>\u72b6\u6001\u7801\u76d1\u63a7\u4e0e\u65e5\u5fd7\u5206\u6790\u662f\u73b0\u4ee3Web\u5e94\u7528\u8fd0\u7ef4\u7684\u91cd\u8981\u7ec4\u6210\u90e8\u5206&#xff1a;<\/p>\n<p>\u6838\u5fc3\u4ef7\u503c&#xff1a;<\/p>\n<li>\n<p>\u95ee\u9898\u68c0\u6d4b\u00a0&#8211; \u5feb\u901f\u53d1\u73b0\u548c\u8bca\u65ad\u95ee\u9898<\/p>\n<\/li>\n<li>\n<p>\u6027\u80fd\u4f18\u5316\u00a0&#8211; \u8bc6\u522b\u6027\u80fd\u74f6\u9888<\/p>\n<\/li>\n<li>\n<p>\u5b89\u5168\u9632\u62a4\u00a0&#8211; \u68c0\u6d4b\u653b\u51fb\u548c\u5f02\u5e38<\/p>\n<\/li>\n<li>\n<p>\u4e1a\u52a1\u6d1e\u5bdf\u00a0&#8211; \u7406\u89e3\u7528\u6237\u884c\u4e3a\u6a21\u5f0f<\/p>\n<\/li>\n<p>\u5173\u952e\u7ec4\u4ef6&#xff1a;<\/p>\n<li>\n<p>\u6570\u636e\u6536\u96c6\u00a0&#8211; \u7ed3\u6784\u5316\u65e5\u5fd7\u3001\u6307\u6807\u6536\u96c6<\/p>\n<\/li>\n<li>\n<p>\u5b9e\u65f6\u5904\u7406\u00a0&#8211; \u6d41\u5904\u7406\u3001\u5b9e\u65f6\u5206\u6790<\/p>\n<\/li>\n<li>\n<p>\u5b58\u50a8\u4e0e\u67e5\u8be2\u00a0&#8211; \u65f6\u5e8f\u6570\u636e\u5e93\u3001\u65e5\u5fd7\u7d22\u5f15<\/p>\n<\/li>\n<li>\n<p>\u5206\u6790\u4e0e\u68c0\u6d4b\u00a0&#8211; \u6a21\u5f0f\u8bc6\u522b\u3001\u5f02\u5e38\u68c0\u6d4b<\/p>\n<\/li>\n<li>\n<p>\u53ef\u89c6\u5316\u00a0&#8211; \u4eea\u8868\u677f\u3001\u62a5\u8868<\/p>\n<\/li>\n<li>\n<p>\u544a\u8b66\u4e0e\u901a\u77e5\u00a0&#8211; \u5b9e\u65f6\u544a\u8b66\u3001\u81ea\u52a8\u4fee\u590d<\/p>\n<\/li>\n<p>\u6700\u4f73\u5b9e\u8df5&#xff1a;<\/p>\n<li>\n<p>\u7ed3\u6784\u5316\u65e5\u5fd7\u00a0&#8211; \u4f7f\u7528\u4e00\u81f4\u7684\u65e5\u5fd7\u683c\u5f0f<\/p>\n<\/li>\n<li>\n<p>\u5168\u9762\u76d1\u63a7\u00a0&#8211; \u76d1\u63a7\u6240\u6709\u72b6\u6001\u7801&#xff0c;\u5305\u62ec\u81ea\u5b9a\u4e49\u4ee3\u7801<\/p>\n<\/li>\n<li>\n<p>\u667a\u80fd\u544a\u8b66\u00a0&#8211; \u907f\u514d\u544a\u8b66\u75b2\u52b3&#xff0c;\u4f7f\u7528\u673a\u5668\u5b66\u4e60<\/p>\n<\/li>\n<li>\n<p>\u6301\u7eed\u4f18\u5316\u00a0&#8211; \u5b9a\u671f\u5ba1\u67e5\u548c\u4f18\u5316\u76d1\u63a7\u89c4\u5219<\/p>\n<\/li>\n<li>\n<p>\u5b89\u5168\u8003\u8651\u00a0&#8211; \u4fdd\u62a4\u76d1\u63a7\u6570\u636e&#xff0c;\u9632\u6b62\u4fe1\u606f\u6cc4\u9732<\/p>\n<\/li>\n<p>\u672a\u6765\u8d8b\u52bf&#xff1a;<\/p>\n<li>\n<p>AI\/ML\u96c6\u6210\u00a0&#8211; \u66f4\u667a\u80fd\u7684\u5f02\u5e38\u68c0\u6d4b\u548c\u6839\u56e0\u5206\u6790<\/p>\n<\/li>\n<li>\n<p>\u81ea\u52a8\u5316\u4fee\u590d\u00a0&#8211; \u57fa\u4e8e\u76d1\u63a7\u7684\u81ea\u52a8\u6269\u7f29\u5bb9\u548c\u6545\u969c\u8f6c\u79fb<\/p>\n<\/li>\n<li>\n<p>\u9884\u6d4b\u5206\u6790\u00a0&#8211; \u9884\u6d4b\u95ee\u9898\u53d1\u751f&#xff0c;\u63d0\u524d\u9884\u9632<\/p>\n<\/li>\n<li>\n<p>\u8de8\u7cfb\u7edf\u96c6\u6210\u00a0&#8211; \u7edf\u4e00\u7684\u76d1\u63a7\u5e73\u53f0<\/p>\n<\/li>\n<p>\u901a\u8fc7\u6709\u6548\u7684\u72b6\u6001\u7801\u76d1\u63a7\u4e0e\u65e5\u5fd7\u5206\u6790&#xff0c;\u53ef\u4ee5\u663e\u8457\u63d0\u9ad8\u7cfb\u7edf\u7684\u53ef\u9760\u6027\u3001\u6027\u80fd\u548c\u5b89\u5168\u6027\u3002<\/p>\n<hr \/>\n<h3><\/h3>\n<p>      <span id=\"quality-guide-article-end\" aria-hidden=\"true\" style=\"display:block;height:1px;margin-bottom:-1px\"><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\/* MD \/ \u5bcc\u6587\u672c\u4e2d\u7684 .toc\uff08\u542b\u535a\u5ba2\u56ed\u642c\u5bb6\u7b49\u5d4c\u5957\u7ed3\u6784\uff09\uff1b.toc-box \u5728\u4fa7\u680f\uff0c\u4e0d\u53d7\u5f71\u54cd *\/#content_views .toc,\/* \u7f16\u8f91\u5668\u5e38\u5728\u76ee\u5f55\u524d\u540e\u63d2\u5165\u7a7a p\uff08:empty \u4ecd\u5360 20px\uff09\uff0c\u4e00\u5e76\u53bb\u6389\u907f\u514d\u9876\u7a7a\u9699 *\/#content_views.markdown_views &gt; p:empty:has(+ .toc),#content_views.markdown_views &gt; .toc + p:empty,\/* \u5bcc\u6587\u672c\u65e7\u7248\u76ee\u5f55\u6807\u8bb0 *\/#content<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[151,43,191],"topic":[],"class_list":["post-124718","post","type-post","status-publish","format-standard","hentry","category-server","tag-http","tag-43","tag-191"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.3 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>HTTP \u72b6\u6001\u7801\uff1a\u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668\u7684\u901a\u4fe1\u8bed\u8a00\u2014\u2014\u7b2c\u4e03\u90e8\u5206\uff1a\u9ad8\u7ea7\u4e3b\u9898\u4e0e\u672a\u6765\u5c55\u671b\uff08\u4e00\uff09 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.wsisp.com\/helps\/124718.html\" \/>\n<meta property=\"og:locale\" content=\"zh_CN\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"HTTP \u72b6\u6001\u7801\uff1a\u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668\u7684\u901a\u4fe1\u8bed\u8a00\u2014\u2014\u7b2c\u4e03\u90e8\u5206\uff1a\u9ad8\u7ea7\u4e3b\u9898\u4e0e\u672a\u6765\u5c55\u671b\uff08\u4e00\uff09 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\" \/>\n<meta property=\"og:description\" content=\"\/* MD \/ \u5bcc\u6587\u672c\u4e2d\u7684 .toc\uff08\u542b\u535a\u5ba2\u56ed\u642c\u5bb6\u7b49\u5d4c\u5957\u7ed3\u6784\uff09\uff1b.toc-box \u5728\u4fa7\u680f\uff0c\u4e0d\u53d7\u5f71\u54cd *\/#content_views .toc,\/* \u7f16\u8f91\u5668\u5e38\u5728\u76ee\u5f55\u524d\u540e\u63d2\u5165\u7a7a p\uff08:empty \u4ecd\u5360 20px\uff09\uff0c\u4e00\u5e76\u53bb\u6389\u907f\u514d\u9876\u7a7a\u9699 *\/#content_views.markdown_views &gt; p:empty:has(+ .toc),#content_views.markdown_views &gt; .toc + p:empty,\/* \u5bcc\u6587\u672c\u65e7\u7248\u76ee\u5f55\u6807\u8bb0 *\/#content\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.wsisp.com\/helps\/124718.html\" \/>\n<meta property=\"og:site_name\" content=\"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\" \/>\n<meta property=\"article:published_time\" content=\"2026-11-19T03:40:50+00:00\" \/>\n<meta name=\"author\" content=\"admin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"\u4f5c\u8005\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"\u9884\u8ba1\u9605\u8bfb\u65f6\u95f4\" \/>\n\t<meta name=\"twitter:data2\" content=\"96 \u5206\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/124718.html\",\"url\":\"https:\/\/www.wsisp.com\/helps\/124718.html\",\"name\":\"HTTP \u72b6\u6001\u7801\uff1a\u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668\u7684\u901a\u4fe1\u8bed\u8a00\u2014\u2014\u7b2c\u4e03\u90e8\u5206\uff1a\u9ad8\u7ea7\u4e3b\u9898\u4e0e\u672a\u6765\u5c55\u671b\uff08\u4e00\uff09 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\",\"isPartOf\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/#website\"},\"datePublished\":\"2026-11-19T03:40:50+00:00\",\"dateModified\":\"2026-11-19T03:40:50+00:00\",\"author\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41\"},\"breadcrumb\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/124718.html#breadcrumb\"},\"inLanguage\":\"zh-Hans\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.wsisp.com\/helps\/124718.html\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/124718.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\u9996\u9875\",\"item\":\"https:\/\/www.wsisp.com\/helps\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"HTTP \u72b6\u6001\u7801\uff1a\u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668\u7684\u901a\u4fe1\u8bed\u8a00\u2014\u2014\u7b2c\u4e03\u90e8\u5206\uff1a\u9ad8\u7ea7\u4e3b\u9898\u4e0e\u672a\u6765\u5c55\u671b\uff08\u4e00\uff09\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/#website\",\"url\":\"https:\/\/www.wsisp.com\/helps\/\",\"name\":\"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\",\"description\":\"\u9999\u6e2f\u670d\u52a1\u5668_\u9999\u6e2f\u4e91\u670d\u52a1\u5668\u8d44\u8baf_\u670d\u52a1\u5668\u5e2e\u52a9\u6587\u6863_\u670d\u52a1\u5668\u6559\u7a0b\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.wsisp.com\/helps\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"zh-Hans\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"zh-Hans\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery\",\"contentUrl\":\"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery\",\"caption\":\"admin\"},\"sameAs\":[\"http:\/\/wp.wsisp.com\"],\"url\":\"https:\/\/www.wsisp.com\/helps\/author\/admin\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"HTTP \u72b6\u6001\u7801\uff1a\u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668\u7684\u901a\u4fe1\u8bed\u8a00\u2014\u2014\u7b2c\u4e03\u90e8\u5206\uff1a\u9ad8\u7ea7\u4e3b\u9898\u4e0e\u672a\u6765\u5c55\u671b\uff08\u4e00\uff09 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.wsisp.com\/helps\/124718.html","og_locale":"zh_CN","og_type":"article","og_title":"HTTP \u72b6\u6001\u7801\uff1a\u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668\u7684\u901a\u4fe1\u8bed\u8a00\u2014\u2014\u7b2c\u4e03\u90e8\u5206\uff1a\u9ad8\u7ea7\u4e3b\u9898\u4e0e\u672a\u6765\u5c55\u671b\uff08\u4e00\uff09 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","og_description":"\/* MD \/ \u5bcc\u6587\u672c\u4e2d\u7684 .toc\uff08\u542b\u535a\u5ba2\u56ed\u642c\u5bb6\u7b49\u5d4c\u5957\u7ed3\u6784\uff09\uff1b.toc-box \u5728\u4fa7\u680f\uff0c\u4e0d\u53d7\u5f71\u54cd *\/#content_views .toc,\/* \u7f16\u8f91\u5668\u5e38\u5728\u76ee\u5f55\u524d\u540e\u63d2\u5165\u7a7a p\uff08:empty \u4ecd\u5360 20px\uff09\uff0c\u4e00\u5e76\u53bb\u6389\u907f\u514d\u9876\u7a7a\u9699 *\/#content_views.markdown_views &gt; p:empty:has(+ .toc),#content_views.markdown_views &gt; .toc + p:empty,\/* \u5bcc\u6587\u672c\u65e7\u7248\u76ee\u5f55\u6807\u8bb0 *\/#content","og_url":"https:\/\/www.wsisp.com\/helps\/124718.html","og_site_name":"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","article_published_time":"2026-11-19T03:40:50+00:00","author":"admin","twitter_card":"summary_large_image","twitter_misc":{"\u4f5c\u8005":"admin","\u9884\u8ba1\u9605\u8bfb\u65f6\u95f4":"96 \u5206"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.wsisp.com\/helps\/124718.html","url":"https:\/\/www.wsisp.com\/helps\/124718.html","name":"HTTP \u72b6\u6001\u7801\uff1a\u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668\u7684\u901a\u4fe1\u8bed\u8a00\u2014\u2014\u7b2c\u4e03\u90e8\u5206\uff1a\u9ad8\u7ea7\u4e3b\u9898\u4e0e\u672a\u6765\u5c55\u671b\uff08\u4e00\uff09 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","isPartOf":{"@id":"https:\/\/www.wsisp.com\/helps\/#website"},"datePublished":"2026-11-19T03:40:50+00:00","dateModified":"2026-11-19T03:40:50+00:00","author":{"@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41"},"breadcrumb":{"@id":"https:\/\/www.wsisp.com\/helps\/124718.html#breadcrumb"},"inLanguage":"zh-Hans","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.wsisp.com\/helps\/124718.html"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.wsisp.com\/helps\/124718.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\u9996\u9875","item":"https:\/\/www.wsisp.com\/helps"},{"@type":"ListItem","position":2,"name":"HTTP \u72b6\u6001\u7801\uff1a\u5ba2\u6237\u7aef\u4e0e\u670d\u52a1\u5668\u7684\u901a\u4fe1\u8bed\u8a00\u2014\u2014\u7b2c\u4e03\u90e8\u5206\uff1a\u9ad8\u7ea7\u4e3b\u9898\u4e0e\u672a\u6765\u5c55\u671b\uff08\u4e00\uff09"}]},{"@type":"WebSite","@id":"https:\/\/www.wsisp.com\/helps\/#website","url":"https:\/\/www.wsisp.com\/helps\/","name":"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","description":"\u9999\u6e2f\u670d\u52a1\u5668_\u9999\u6e2f\u4e91\u670d\u52a1\u5668\u8d44\u8baf_\u670d\u52a1\u5668\u5e2e\u52a9\u6587\u6863_\u670d\u52a1\u5668\u6559\u7a0b","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.wsisp.com\/helps\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"zh-Hans"},{"@type":"Person","@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41","name":"admin","image":{"@type":"ImageObject","inLanguage":"zh-Hans","@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/image\/","url":"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery","contentUrl":"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery","caption":"admin"},"sameAs":["http:\/\/wp.wsisp.com"],"url":"https:\/\/www.wsisp.com\/helps\/author\/admin"}]}},"_links":{"self":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts\/124718","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/comments?post=124718"}],"version-history":[{"count":0,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts\/124718\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/media?parent=124718"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/categories?post=124718"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/tags?post=124718"},{"taxonomy":"topic","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/topic?post=124718"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}