|
| 1 | +package com.openlayer.api.core.http |
| 2 | + |
| 3 | +import com.openlayer.api.core.http.AsyncStreamResponse.Handler |
| 4 | +import java.util.Optional |
| 5 | +import java.util.concurrent.CompletableFuture |
| 6 | +import java.util.concurrent.Executor |
| 7 | +import java.util.concurrent.atomic.AtomicReference |
| 8 | + |
| 9 | +/** |
| 10 | + * A class providing access to an API response as an asynchronous stream of chunks of type [T], |
| 11 | + * where each chunk can be individually processed as soon as it arrives instead of waiting on the |
| 12 | + * full response. |
| 13 | + */ |
| 14 | +interface AsyncStreamResponse<T> { |
| 15 | + |
| 16 | + /** |
| 17 | + * Registers [handler] to be called for events of this stream. |
| 18 | + * |
| 19 | + * [handler]'s methods will be called in the client's configured or default thread pool. |
| 20 | + * |
| 21 | + * @throws IllegalStateException if [subscribe] has already been called. |
| 22 | + */ |
| 23 | + fun subscribe(handler: Handler<T>): AsyncStreamResponse<T> |
| 24 | + |
| 25 | + /** |
| 26 | + * Registers [handler] to be called for events of this stream. |
| 27 | + * |
| 28 | + * [handler]'s methods will be called in the given [executor]. |
| 29 | + * |
| 30 | + * @throws IllegalStateException if [subscribe] has already been called. |
| 31 | + */ |
| 32 | + fun subscribe(handler: Handler<T>, executor: Executor): AsyncStreamResponse<T> |
| 33 | + |
| 34 | + /** |
| 35 | + * Returns a future that completes when a stream is fully consumed, errors, or gets closed |
| 36 | + * early. |
| 37 | + */ |
| 38 | + fun onCompleteFuture(): CompletableFuture<Void?> |
| 39 | + |
| 40 | + /** |
| 41 | + * Closes this resource, relinquishing any underlying resources. |
| 42 | + * |
| 43 | + * This is purposefully not inherited from [AutoCloseable] because this response should not be |
| 44 | + * synchronously closed via try-with-resources. |
| 45 | + */ |
| 46 | + fun close() |
| 47 | + |
| 48 | + /** A class for handling streaming events. */ |
| 49 | + fun interface Handler<in T> { |
| 50 | + |
| 51 | + /** Called whenever a chunk is received. */ |
| 52 | + fun onNext(value: T) |
| 53 | + |
| 54 | + /** |
| 55 | + * Called when a stream is fully consumed, errors, or gets closed early. |
| 56 | + * |
| 57 | + * [onNext] will not be called once this method is called. |
| 58 | + * |
| 59 | + * @param error Non-empty if the stream completed due to an error. |
| 60 | + */ |
| 61 | + fun onComplete(error: Optional<Throwable>) {} |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +@JvmSynthetic |
| 66 | +internal fun <T> CompletableFuture<StreamResponse<T>>.toAsync(streamHandlerExecutor: Executor) = |
| 67 | + PhantomReachableClosingAsyncStreamResponse( |
| 68 | + object : AsyncStreamResponse<T> { |
| 69 | + |
| 70 | + private val onCompleteFuture = CompletableFuture<Void?>() |
| 71 | + private val state = AtomicReference(State.NEW) |
| 72 | + |
| 73 | + init { |
| 74 | + this@toAsync.whenComplete { _, error -> |
| 75 | + // If an error occurs from the original future, then we should resolve the |
| 76 | + // `onCompleteFuture` even if `subscribe` has not been called. |
| 77 | + error?.let(onCompleteFuture::completeExceptionally) |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + override fun subscribe(handler: Handler<T>): AsyncStreamResponse<T> = |
| 82 | + subscribe(handler, streamHandlerExecutor) |
| 83 | + |
| 84 | + override fun subscribe( |
| 85 | + handler: Handler<T>, |
| 86 | + executor: Executor, |
| 87 | + ): AsyncStreamResponse<T> = apply { |
| 88 | + // TODO(JDK): Use `compareAndExchange` once targeting JDK 9. |
| 89 | + check(state.compareAndSet(State.NEW, State.SUBSCRIBED)) { |
| 90 | + if (state.get() == State.SUBSCRIBED) "Cannot subscribe more than once" |
| 91 | + else "Cannot subscribe after the response is closed" |
| 92 | + } |
| 93 | + |
| 94 | + this@toAsync.whenCompleteAsync( |
| 95 | + { streamResponse, futureError -> |
| 96 | + if (state.get() == State.CLOSED) { |
| 97 | + // Avoid doing any work if `close` was called before the future |
| 98 | + // completed. |
| 99 | + return@whenCompleteAsync |
| 100 | + } |
| 101 | + |
| 102 | + if (futureError != null) { |
| 103 | + // An error occurred before we started passing chunks to the handler. |
| 104 | + handler.onComplete(Optional.of(futureError)) |
| 105 | + return@whenCompleteAsync |
| 106 | + } |
| 107 | + |
| 108 | + var streamError: Throwable? = null |
| 109 | + try { |
| 110 | + streamResponse.stream().forEach(handler::onNext) |
| 111 | + } catch (e: Throwable) { |
| 112 | + streamError = e |
| 113 | + } |
| 114 | + |
| 115 | + try { |
| 116 | + handler.onComplete(Optional.ofNullable(streamError)) |
| 117 | + } finally { |
| 118 | + try { |
| 119 | + // Notify completion via the `onCompleteFuture` as well. This is in |
| 120 | + // a separate `try-finally` block so that we still complete the |
| 121 | + // future if `handler.onComplete` throws. |
| 122 | + if (streamError == null) { |
| 123 | + onCompleteFuture.complete(null) |
| 124 | + } else { |
| 125 | + onCompleteFuture.completeExceptionally(streamError) |
| 126 | + } |
| 127 | + } finally { |
| 128 | + close() |
| 129 | + } |
| 130 | + } |
| 131 | + }, |
| 132 | + executor, |
| 133 | + ) |
| 134 | + } |
| 135 | + |
| 136 | + override fun onCompleteFuture(): CompletableFuture<Void?> = onCompleteFuture |
| 137 | + |
| 138 | + override fun close() { |
| 139 | + val previousState = state.getAndSet(State.CLOSED) |
| 140 | + if (previousState == State.CLOSED) { |
| 141 | + return |
| 142 | + } |
| 143 | + |
| 144 | + this@toAsync.whenComplete { streamResponse, error -> streamResponse?.close() } |
| 145 | + // When the stream is closed, we should always consider it closed. If it closed due |
| 146 | + // to an error, then we will have already completed the future earlier, and this |
| 147 | + // will be a no-op. |
| 148 | + onCompleteFuture.complete(null) |
| 149 | + } |
| 150 | + } |
| 151 | + ) |
| 152 | + |
| 153 | +private enum class State { |
| 154 | + NEW, |
| 155 | + SUBSCRIBED, |
| 156 | + CLOSED, |
| 157 | +} |
0 commit comments