|
| 1 | +package com.alibaba.dashscope.protocol.okhttp; |
| 2 | + |
| 3 | +import com.alibaba.dashscope.protocol.FullDuplexRequest; |
| 4 | +import com.alibaba.dashscope.utils.JsonUtils; |
| 5 | +import com.google.gson.JsonObject; |
| 6 | +import io.reactivex.Flowable; |
| 7 | +import io.reactivex.functions.Action; |
| 8 | +import lombok.extern.slf4j.Slf4j; |
| 9 | +import okhttp3.OkHttpClient; |
| 10 | +import okio.ByteString; |
| 11 | + |
| 12 | +import java.nio.ByteBuffer; |
| 13 | +import java.util.concurrent.*; |
| 14 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 15 | +import java.util.concurrent.atomic.AtomicInteger; |
| 16 | + |
| 17 | +/** |
| 18 | + * @author songsong.shao |
| 19 | + * @date 2025/11/5 |
| 20 | + */ |
| 21 | +@Slf4j |
| 22 | +public class OkHttpWebSocketClientForAudio extends OkHttpWebSocketClient { |
| 23 | + |
| 24 | + private static final AtomicInteger STREAMING_REQUEST_THREAD_NUM = new AtomicInteger(0); |
| 25 | + private static final AtomicBoolean SHUTDOWN_INITIATED = new AtomicBoolean(false); |
| 26 | + |
| 27 | + private static final ExecutorService STREAMING_REQUEST_EXECUTOR = |
| 28 | + new ThreadPoolExecutor(1, 100, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), r -> { |
| 29 | + Thread t = new Thread(r, "WS-STREAMING-REQ-Worker-" + STREAMING_REQUEST_THREAD_NUM.updateAndGet(n -> n == Integer.MAX_VALUE ? 0 : n + 1)); |
| 30 | + t.setDaemon(true); |
| 31 | + return t; |
| 32 | + }); |
| 33 | + |
| 34 | + public OkHttpWebSocketClientForAudio(OkHttpClient client, boolean passTaskStarted) { |
| 35 | + super(client, passTaskStarted); |
| 36 | + log.info("Use OkHttpWebSocketClientForAudio"); |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + protected CompletableFuture<Void> sendStreamRequest(FullDuplexRequest req) { |
| 41 | + CompletableFuture<Void> future = |
| 42 | + CompletableFuture.runAsync( |
| 43 | + () -> { |
| 44 | + try { |
| 45 | + isFirstMessage.set(false); |
| 46 | + |
| 47 | + JsonObject startMessage = req.getStartTaskMessage(); |
| 48 | + log.info("send run-task request {}", JsonUtils.toJson(startMessage)); |
| 49 | + String taskId = |
| 50 | + startMessage.get("header").getAsJsonObject().get("task_id").getAsString(); |
| 51 | + // send start message out. |
| 52 | + sendTextWithRetry( |
| 53 | + req.getApiKey(), |
| 54 | + req.isSecurityCheck(), |
| 55 | + JsonUtils.toJson(startMessage), |
| 56 | + req.getWorkspace(), |
| 57 | + req.getHeaders(), |
| 58 | + req.getBaseWebSocketUrl()); |
| 59 | + |
| 60 | + Flowable<Object> streamingData = req.getStreamingData(); |
| 61 | + streamingData.subscribe( |
| 62 | + data -> { |
| 63 | + try { |
| 64 | + if (data instanceof String) { |
| 65 | + JsonObject continueData = req.getContinueMessage((String) data, taskId); |
| 66 | + sendTextWithRetry( |
| 67 | + req.getApiKey(), |
| 68 | + req.isSecurityCheck(), |
| 69 | + JsonUtils.toJson(continueData), |
| 70 | + req.getWorkspace(), |
| 71 | + req.getHeaders(), |
| 72 | + req.getBaseWebSocketUrl()); |
| 73 | + } else if (data instanceof byte[]) { |
| 74 | + sendBinaryWithRetry( |
| 75 | + req.getApiKey(), |
| 76 | + req.isSecurityCheck(), |
| 77 | + ByteString.of((byte[]) data), |
| 78 | + req.getWorkspace(), |
| 79 | + req.getHeaders(), |
| 80 | + req.getBaseWebSocketUrl()); |
| 81 | + } else if (data instanceof ByteBuffer) { |
| 82 | + sendBinaryWithRetry( |
| 83 | + req.getApiKey(), |
| 84 | + req.isSecurityCheck(), |
| 85 | + ByteString.of((ByteBuffer) data), |
| 86 | + req.getWorkspace(), |
| 87 | + req.getHeaders(), |
| 88 | + req.getBaseWebSocketUrl()); |
| 89 | + } else { |
| 90 | + JsonObject continueData = req.getContinueMessage(data, taskId); |
| 91 | + sendTextWithRetry( |
| 92 | + req.getApiKey(), |
| 93 | + req.isSecurityCheck(), |
| 94 | + JsonUtils.toJson(continueData), |
| 95 | + req.getWorkspace(), |
| 96 | + req.getHeaders(), |
| 97 | + req.getBaseWebSocketUrl()); |
| 98 | + } |
| 99 | + } catch (Throwable ex) { |
| 100 | + log.error(String.format("sendStreamData exception: %s", ex.getMessage())); |
| 101 | + responseEmitter.onError(ex); |
| 102 | + } |
| 103 | + }, |
| 104 | + err -> { |
| 105 | + log.error(String.format("Get stream data error!")); |
| 106 | + responseEmitter.onError(err); |
| 107 | + }, |
| 108 | + new Action() { |
| 109 | + @Override |
| 110 | + public void run() throws Exception { |
| 111 | + log.debug(String.format("Stream data send completed!")); |
| 112 | + sendTextWithRetry( |
| 113 | + req.getApiKey(), |
| 114 | + req.isSecurityCheck(), |
| 115 | + JsonUtils.toJson(req.getFinishedTaskMessage(taskId)), |
| 116 | + req.getWorkspace(), |
| 117 | + req.getHeaders(), |
| 118 | + req.getBaseWebSocketUrl()); |
| 119 | + } |
| 120 | + }); |
| 121 | + } catch (Throwable ex) { |
| 122 | + log.error(String.format("sendStreamData exception: %s", ex.getMessage())); |
| 123 | + responseEmitter.onError(ex); |
| 124 | + } |
| 125 | + }); |
| 126 | + return future; |
| 127 | + } |
| 128 | + |
| 129 | + static {//auto close when jvm shutdown |
| 130 | + Runtime.getRuntime().addShutdownHook(new Thread(OkHttpWebSocketClientForAudio::shutdownStreamingExecutor)); |
| 131 | + } |
| 132 | + /** |
| 133 | + * Shutdown the streaming request executor gracefully. |
| 134 | + * This method should be called when the application is shutting down |
| 135 | + * to ensure proper resource cleanup. |
| 136 | + */ |
| 137 | + private static void shutdownStreamingExecutor() { |
| 138 | + if (!SHUTDOWN_INITIATED.compareAndSet(false, true)) { |
| 139 | + log.debug("Shutdown already in progress"); |
| 140 | + return; |
| 141 | + } |
| 142 | + |
| 143 | + if (!STREAMING_REQUEST_EXECUTOR.isShutdown()) { |
| 144 | + log.debug("Shutting down streaming request executor..."); |
| 145 | + STREAMING_REQUEST_EXECUTOR.shutdown(); |
| 146 | + try { |
| 147 | + // Wait up to 60 seconds for existing tasks to terminate |
| 148 | + if (!STREAMING_REQUEST_EXECUTOR.awaitTermination(60, TimeUnit.SECONDS)) { |
| 149 | + log.warn("Streaming request executor did not terminate in 60 seconds, forcing shutdown..."); |
| 150 | + STREAMING_REQUEST_EXECUTOR.shutdownNow(); |
| 151 | + // Wait up to 60 seconds for tasks to respond to being cancelled |
| 152 | + if (!STREAMING_REQUEST_EXECUTOR.awaitTermination(60, TimeUnit.SECONDS)) { |
| 153 | + log.error("Streaming request executor did not terminate"); |
| 154 | + } |
| 155 | + } |
| 156 | + } catch (InterruptedException ie) { |
| 157 | + // (Re-)Cancel if current thread also interrupted |
| 158 | + STREAMING_REQUEST_EXECUTOR.shutdownNow(); |
| 159 | + // Preserve interrupt status |
| 160 | + Thread.currentThread().interrupt(); |
| 161 | + } |
| 162 | + log.info("Streaming request executor shut down completed"); |
| 163 | + } |
| 164 | + } |
| 165 | +} |
0 commit comments