1+ package com .microsoft .graph .httpcore ;
2+
3+ import java .io .IOException ;
4+ import java .util .concurrent .ThreadLocalRandom ;
5+
6+ import com .microsoft .graph .httpcore .middlewareoption .MiddlewareType ;
7+ import com .microsoft .graph .httpcore .middlewareoption .TelemetryOptions ;
8+
9+ import okhttp3 .Interceptor ;
10+ import okhttp3 .MediaType ;
11+ import okhttp3 .Protocol ;
12+ import okhttp3 .Request ;
13+ import okhttp3 .Response ;
14+ import okhttp3 .ResponseBody ;
15+
16+ /**
17+ * DO NOT USE IN PRODUCTION
18+ * interceptor that randomly fails the responses for unit testing purposes
19+ */
20+ public class ChaosHttpHandler implements Interceptor {
21+ public final MiddlewareType MIDDLEWARE_TYPE = MiddlewareType .RETRY ;
22+ /*
23+ * constant string being used
24+ */
25+ private final String RETRY_AFTER = "Retry-After" ;
26+ /**
27+ * Denominator for the failure rate (i.e. 1/X)
28+ */
29+ private final Integer failureRate = 3 ;
30+ /**
31+ * default value to return on retry after
32+ */
33+ private final String retryAfterValue = "10" ;
34+ /**
35+ * body to respond on failed requests
36+ */
37+ private final String responseBody = "{\" error\" : {\" code\" : \" TooManyRequests\" ,\" innerError\" : {\" code\" : \" 429\" ,\" date\" : \" 2020-08-18T12:51:51\" ,\" message\" : \" Please retry after\" ,\" request-id\" : \" 94fb3b52-452a-4535-a601-69e0a90e3aa2\" ,\" status\" : \" 429\" },\" message\" : \" Please retry again later.\" }}" ;
38+ public static final int MSClientErrorCodeTooManyRequests = 429 ;
39+
40+ @ Override
41+ public Response intercept (Chain chain ) throws IOException {
42+ Request request = chain .request ();
43+
44+ if (request .tag (TelemetryOptions .class ) == null )
45+ request = request .newBuilder ().tag (TelemetryOptions .class , new TelemetryOptions ()).build ();
46+ request .tag (TelemetryOptions .class ).setFeatureUsage (TelemetryOptions .RETRY_HANDLER_ENABLED_FLAG );
47+
48+ final Integer dice = ThreadLocalRandom .current ().nextInt (1 , Integer .MAX_VALUE );
49+
50+ if (dice % failureRate == 0 ) {
51+ return new Response
52+ .Builder ()
53+ .request (request )
54+ .protocol (Protocol .HTTP_1_1 )
55+ .code (MSClientErrorCodeTooManyRequests )
56+ .message ("Too Many Requests" )
57+ .addHeader (RETRY_AFTER , retryAfterValue )
58+ .body (ResponseBody .create (MediaType .get ("application/json" ), responseBody ))
59+ .build ();
60+ } else {
61+ return chain .proceed (request );
62+ }
63+ }
64+
65+ }
0 commit comments