|
35 | 35 | import com.google.genai.types.Part; |
36 | 36 | import com.google.genai.types.PartialArg; |
37 | 37 | import io.reactivex.rxjava3.core.Flowable; |
| 38 | +import io.reactivex.rxjava3.schedulers.Schedulers; |
38 | 39 | import java.time.Duration; |
39 | 40 | import java.util.ArrayList; |
| 41 | +import java.util.Iterator; |
40 | 42 | import java.util.LinkedHashMap; |
41 | 43 | import java.util.List; |
42 | 44 | import java.util.Map; |
43 | 45 | import java.util.Objects; |
44 | 46 | import java.util.concurrent.CompletableFuture; |
45 | 47 | import java.util.concurrent.ExecutorService; |
| 48 | +import java.util.concurrent.atomic.AtomicBoolean; |
46 | 49 | import okhttp3.OkHttpClient; |
47 | 50 | import org.jspecify.annotations.Nullable; |
48 | 51 | import org.slf4j.Logger; |
@@ -296,11 +299,7 @@ private Flowable<LlmResponse> sendRequest( |
296 | 299 | effectiveModelName, llmRequest.contents(), config); |
297 | 300 |
|
298 | 301 | return Flowable.defer( |
299 | | - () -> |
300 | | - new StreamingResponseAggregator() |
301 | | - .process( |
302 | | - Flowable.fromFuture(streamFuture).flatMapIterable(iterable -> iterable), |
303 | | - cacheMetadata)); |
| 302 | + () -> new StreamingResponseAggregator().process(readStream(streamFuture), cacheMetadata)); |
304 | 303 | } else { |
305 | 304 | logger.debug("Sending generateContent request to model {}", effectiveModelName); |
306 | 305 | return Flowable.fromFuture( |
@@ -330,6 +329,78 @@ private static GenerateContentConfig withTrackingHeaders(@Nullable GenerateConte |
330 | 329 | .build(); |
331 | 330 | } |
332 | 331 |
|
| 332 | + /** |
| 333 | + * Reads the stream and, when the subscriber cancels, closes it on {@link Schedulers#io()} so a |
| 334 | + * partial read doesn't leave the HTTP response open. The close waits for the stream to open and |
| 335 | + * can block behind a {@code readLine()} in progress. An iterator call that returns after the |
| 336 | + * cancel closes the stream again, covering a continuation request opened during that call. |
| 337 | + */ |
| 338 | + @VisibleForTesting |
| 339 | + static <T, S extends Iterable<T> & AutoCloseable> Flowable<T> readStream( |
| 340 | + CompletableFuture<S> streamFuture) { |
| 341 | + return Flowable.defer( |
| 342 | + () -> { |
| 343 | + AtomicBoolean cancelled = new AtomicBoolean(); |
| 344 | + AtomicBoolean terminated = new AtomicBoolean(); |
| 345 | + return Flowable.using( |
| 346 | + () -> streamFuture, |
| 347 | + future -> |
| 348 | + Flowable.fromFuture(future) |
| 349 | + .flatMapIterable(stream -> closingAfterCancel(stream, cancelled)) |
| 350 | + .doOnTerminate(() -> terminated.set(true)), |
| 351 | + future -> { |
| 352 | + if (!terminated.get()) { |
| 353 | + cancelled.set(true); |
| 354 | + var unused = future.thenAccept(Gemini::closeAsync); |
| 355 | + } |
| 356 | + }, |
| 357 | + /* eager= */ false); |
| 358 | + }); |
| 359 | + } |
| 360 | + |
| 361 | + private static <T, S extends Iterable<T> & AutoCloseable> Iterable<T> closingAfterCancel( |
| 362 | + S stream, AtomicBoolean cancelled) { |
| 363 | + Iterator<T> delegate = stream.iterator(); |
| 364 | + return () -> |
| 365 | + new Iterator<T>() { |
| 366 | + @Override |
| 367 | + public boolean hasNext() { |
| 368 | + try { |
| 369 | + return delegate.hasNext(); |
| 370 | + } finally { |
| 371 | + closeIfCancelled(); |
| 372 | + } |
| 373 | + } |
| 374 | + |
| 375 | + @Override |
| 376 | + public T next() { |
| 377 | + try { |
| 378 | + return delegate.next(); |
| 379 | + } finally { |
| 380 | + closeIfCancelled(); |
| 381 | + } |
| 382 | + } |
| 383 | + |
| 384 | + private void closeIfCancelled() { |
| 385 | + if (cancelled.get()) { |
| 386 | + closeAsync(stream); |
| 387 | + } |
| 388 | + } |
| 389 | + }; |
| 390 | + } |
| 391 | + |
| 392 | + private static void closeAsync(AutoCloseable stream) { |
| 393 | + Schedulers.io().scheduleDirect(() -> closeQuietly(stream)); |
| 394 | + } |
| 395 | + |
| 396 | + private static void closeQuietly(AutoCloseable stream) { |
| 397 | + try { |
| 398 | + stream.close(); |
| 399 | + } catch (Exception e) { |
| 400 | + logger.debug("Failed to close the response stream", e); |
| 401 | + } |
| 402 | + } |
| 403 | + |
333 | 404 | private static LlmResponse withCacheMetadata( |
334 | 405 | LlmResponse response, @Nullable CacheMetadata cacheMetadata) { |
335 | 406 | return cacheMetadata == null |
|
0 commit comments