|
| 1 | +package com.volcengine.ark.runtime.interceptor; |
| 2 | + |
| 3 | +import com.volcengine.ark.runtime.utils.ModelBreaker; |
| 4 | +import okhttp3.*; |
| 5 | + |
| 6 | +import java.io.IOException; |
| 7 | +import java.time.Duration; |
| 8 | +import java.util.concurrent.ConcurrentHashMap; |
| 9 | + |
| 10 | +import static com.volcengine.ark.runtime.Const.*; |
| 11 | + |
| 12 | +public class BatchInterceptor implements Interceptor { |
| 13 | + |
| 14 | + private final ConcurrentHashMap<String, ModelBreaker> modelBreakerMap; |
| 15 | + |
| 16 | + public BatchInterceptor() { |
| 17 | + this.modelBreakerMap = new ConcurrentHashMap<>(); |
| 18 | + } |
| 19 | + |
| 20 | + @Override |
| 21 | + public Response intercept(Chain chain) throws IOException { |
| 22 | + Request request = chain.request(); |
| 23 | + HttpUrl url = request.url(); |
| 24 | + if (!url.encodedPath().equals(BATCH_CHAT_PATH)) { |
| 25 | + return chain.proceed(request); |
| 26 | + } |
| 27 | + String endpoint = request.header(REQUEST_MODEL); |
| 28 | + try { |
| 29 | + waitModelForRetryAfter(endpoint); |
| 30 | + } catch (InterruptedException e) { |
| 31 | + throw new RuntimeException(e); |
| 32 | + } |
| 33 | + Response response = chain.proceed(chain.request()); |
| 34 | + String retryAfter = response.header(RETRY_AFTER); |
| 35 | + if (retryAfter != null && !retryAfter.isEmpty()) { |
| 36 | + try { |
| 37 | + int delay = Integer.parseInt(retryAfter); |
| 38 | + setModelForRetryAfter(endpoint, Duration.ofSeconds(delay)); |
| 39 | + } catch (NumberFormatException e) { |
| 40 | + // 无效的RetryAfter Header. 跳过 |
| 41 | + } |
| 42 | + } |
| 43 | + return response; |
| 44 | + } |
| 45 | + private void waitModelForRetryAfter(String model) throws InterruptedException { |
| 46 | + ModelBreaker breaker = this.getModelBreaker(model); |
| 47 | + while (!breaker.Allow()){ |
| 48 | + Duration duration = breaker.GetAllowedDuration(); |
| 49 | + if (duration.getSeconds() > 0) { |
| 50 | + Thread.sleep(duration.toMillis()); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + private void setModelForRetryAfter(String model, Duration duration) { |
| 56 | + ModelBreaker breaker = this.getModelBreaker(model); |
| 57 | + breaker.Reset(duration); |
| 58 | + } |
| 59 | + |
| 60 | + private ModelBreaker getModelBreaker(String model){ |
| 61 | + ModelBreaker breaker; |
| 62 | + if (this.modelBreakerMap.containsKey(model)) { |
| 63 | + breaker = this.modelBreakerMap.get(model); |
| 64 | + } else { |
| 65 | + breaker = new ModelBreaker(); |
| 66 | + this.modelBreakerMap.put(model, breaker); |
| 67 | + } |
| 68 | + return breaker; |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments