|
| 1 | +/* |
| 2 | + * Copyright 2017, Google LLC All rights reserved. |
| 3 | + * |
| 4 | + * Redistribution and use in source and binary forms, with or without |
| 5 | + * modification, are permitted provided that the following conditions are |
| 6 | + * met: |
| 7 | + * |
| 8 | + * * Redistributions of source code must retain the above copyright |
| 9 | + * notice, this list of conditions and the following disclaimer. |
| 10 | + * * Redistributions in binary form must reproduce the above |
| 11 | + * copyright notice, this list of conditions and the following disclaimer |
| 12 | + * in the documentation and/or other materials provided with the |
| 13 | + * distribution. |
| 14 | + * * Neither the name of Google LLC nor the names of its |
| 15 | + * contributors may be used to endorse or promote products derived from |
| 16 | + * this software without specific prior written permission. |
| 17 | + * |
| 18 | + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 19 | + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 20 | + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 21 | + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 22 | + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 23 | + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 24 | + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 25 | + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 26 | + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 | + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 28 | + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | + */ |
| 30 | +packagecom.google.api.gax.rpc; |
| 31 | + |
| 32 | +importcom.google.api.core.BetaApi; |
| 33 | +importcom.google.api.core.InternalApi; |
| 34 | +importcom.google.common.base.Throwables; |
| 35 | +importcom.google.common.collect.Queues; |
| 36 | +importjava.util.Iterator; |
| 37 | +importjava.util.NoSuchElementException; |
| 38 | +importjava.util.concurrent.BlockingQueue; |
| 39 | +importjavax.annotation.Nonnull; |
| 40 | + |
| 41 | +/** |
| 42 | + * A blocking Iterable-style wrapper around server stream responses. |
| 43 | + * |
| 44 | + * <p>This class asynchronously pulls responses from upstream via {@link |
| 45 | + * StreamController#request(int)} and exposes them via its Iterator. The implementation is back |
| 46 | + * pressure aware and uses a constant buffer of 1 item. |
| 47 | + * |
| 48 | + * <p>Please note that the stream can only be consumed once and must either be fully consumed or be |
| 49 | + * canceled. |
| 50 | + * |
| 51 | + * <p>This class is not thread safe. |
| 52 | + * |
| 53 | + * <p>Example usage: |
| 54 | + * |
| 55 | + * <pre>{@code |
| 56 | + * ServerStream<Item> stream = ...; |
| 57 | + * |
| 58 | + * for (Item item : stream) { |
| 59 | + * System.out.println(item.id()); |
| 60 | + * |
| 61 | + * // Allow for early termination |
| 62 | + * if (item.id().equals("needle")) { |
| 63 | + * stream.cancel(); |
| 64 | + * } |
| 65 | + * } |
| 66 | + * }</pre> |
| 67 | + * |
| 68 | + * @param <V> The type of each response. |
| 69 | + */ |
| 70 | +@BetaApi("The surface for streaming is not stable yet and may change in the future.") |
| 71 | +publicfinalclassServerStream<V> implementsIterable<V> { |
| 72 | +privatestaticfinalObjectEOF_MARKER = newObject(); |
| 73 | + |
| 74 | +privatefinalQueuingResponseObserver<V> observer = newQueuingResponseObserver<>(); |
| 75 | +privatefinalServerStreamIterator<V> iterator = newServerStreamIterator<>(observer); |
| 76 | +privatebooleanconsumed; |
| 77 | + |
| 78 | +@InternalApi("For use by ServerStreamingCallable only.") |
| 79 | +ServerStream() {} |
| 80 | + |
| 81 | +@InternalApi("For use by ServerStreamingCallable only.") |
| 82 | +ResponseObserver<V> observer() { |
| 83 | +returnobserver; |
| 84 | + } |
| 85 | + |
| 86 | +/** {@inheritDoc} */ |
| 87 | +@Override |
| 88 | +@Nonnull |
| 89 | +publicIterator<V> iterator() { |
| 90 | +if (consumed) { |
| 91 | +thrownewIllegalStateException("Iterator already consumed"); |
| 92 | + } |
| 93 | +consumed = true; |
| 94 | + |
| 95 | +returniterator; |
| 96 | + } |
| 97 | + |
| 98 | +/** |
| 99 | + * Returns true if the next call to the iterator's hasNext() or next() is guaranteed to be |
| 100 | + * nonblocking. |
| 101 | + * |
| 102 | + * @return If the call on any of the iterator's methods is guaranteed to be nonblocking. |
| 103 | + */ |
| 104 | +publicbooleanisReady() { |
| 105 | +returniterator.isReady(); |
| 106 | + } |
| 107 | + |
| 108 | +/** |
| 109 | + * Cleanly cancels a partially consumed stream. The associated iterator will return false for the |
| 110 | + * hasNext() in the next iteration. This maintains the contract that an observed true from |
| 111 | + * hasNext() will yield an item in next(), but afterwards will return false. |
| 112 | + */ |
| 113 | +publicvoidcancel() { |
| 114 | +observer.cancel(); |
| 115 | + } |
| 116 | + |
| 117 | +/** |
| 118 | + * Internal implementation of a blocking Iterator, which will coordinate with the |
| 119 | + * QueuingResponseObserver fetch new items from upstream. The Iterator expects the observer to |
| 120 | + * request the first item, afterwards, new items will be requested when the current ones are |
| 121 | + * consumed by next(). |
| 122 | + * |
| 123 | + * @param <V> The type of items to be Iterated over. |
| 124 | + */ |
| 125 | +privatestaticfinalclassServerStreamIterator<V> implementsIterator<V> { |
| 126 | +privatefinalQueuingResponseObserver<V> observer; |
| 127 | +privateObjectlast; |
| 128 | + |
| 129 | +ServerStreamIterator(QueuingResponseObserver<V> observer) { |
| 130 | +this.observer = observer; |
| 131 | + } |
| 132 | + |
| 133 | +/** |
| 134 | + * Checks if the next call to {@code hasNext()} (and {@code next()}) will block. |
| 135 | + * |
| 136 | + * @return true if the next call is guaranteed to be nonblocking. |
| 137 | + */ |
| 138 | +booleanisReady() { |
| 139 | +returnlast != null || observer.isReady(); |
| 140 | + } |
| 141 | + |
| 142 | +/** |
| 143 | + * Consumes the next response and asynchronously request the next response from the observer. |
| 144 | + * |
| 145 | + * @return The next response. |
| 146 | + * @throws NoSuchElementException If the stream has been consumed or cancelled. |
| 147 | + */ |
| 148 | +@Override |
| 149 | +publicVnext() { |
| 150 | +if (!hasNext()) { |
| 151 | +thrownewNoSuchElementException(); |
| 152 | + } |
| 153 | +try { |
| 154 | +observer.request(); |
| 155 | +@SuppressWarnings("unchecked") |
| 156 | +Vtmp = (V) last; |
| 157 | +returntmp; |
| 158 | + } finally { |
| 159 | +last = null; |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | +/** |
| 164 | + * Checks if the stream has been fully consumed or cancelled. This method will block until the |
| 165 | + * observer enqueues another event (response or completion event). If the observer encountered |
| 166 | + * an error, this method will propagte the error and put itself into an error where it will |
| 167 | + * always return the same error. |
| 168 | + * |
| 169 | + * @return true If iterator has more responses. |
| 170 | + */ |
| 171 | +@Override |
| 172 | +publicbooleanhasNext() { |
| 173 | +if (last == null) { |
| 174 | +try { |
| 175 | +last = observer.getNext(); |
| 176 | + } catch (InterruptedExceptione) { |
| 177 | +Thread.currentThread().interrupt(); |
| 178 | +thrownewRuntimeException(e); |
| 179 | + } |
| 180 | + } |
| 181 | +if (lastinstanceofThrowable) { |
| 182 | +Throwablethrowable = (Throwable) this.last; |
| 183 | + |
| 184 | +Throwables.throwIfUnchecked(throwable); |
| 185 | +thrownewRuntimeException(throwable); |
| 186 | + } |
| 187 | +returnlast != EOF_MARKER; |
| 188 | + } |
| 189 | + |
| 190 | +/** Unsupported. */ |
| 191 | +@Override |
| 192 | +publicvoidremove() { |
| 193 | +thrownewUnsupportedOperationException(); |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | +/** |
| 198 | + * A back pressure aware bridge from a {@link ResponseObserver} to a {@link BlockingQueue}. The |
| 199 | + * queue size is fixed to 1 item & a close signal. The observer will manage it's own flow control |
| 200 | + * keeping the queue in one of 3 states: |
| 201 | + * |
| 202 | + * <ul> |
| 203 | + * <li>empty: a item has been requested and we are awaiting the next item |
| 204 | + * <li>1 item: an in progress stream with 1 item buffered |
| 205 | + * <li>1 control signal: either a Throwable or an EOF_MARKER means that the stream is closed |
| 206 | + * <li>1 item & 1 control signal: this is the last item of the stream |
| 207 | + * </ul> |
| 208 | + * |
| 209 | + * The observer can also be abruptly cancelled, which cancels the underlying call and always |
| 210 | + * returns an EOF_MARKER. |
| 211 | + * |
| 212 | + * @param <V> The item type. |
| 213 | + */ |
| 214 | +privatestaticfinalclassQueuingResponseObserver<V> implementsResponseObserver<V> { |
| 215 | +privatefinalBlockingQueue<Object> buffer = Queues.newArrayBlockingQueue(2); |
| 216 | +privateStreamControllercontroller; |
| 217 | +privatebooleanisCancelled; |
| 218 | + |
| 219 | +voidrequest() { |
| 220 | +controller.request(1); |
| 221 | + } |
| 222 | + |
| 223 | +ObjectgetNext() throwsInterruptedException { |
| 224 | +if (isCancelled) { |
| 225 | +returnEOF_MARKER; |
| 226 | + } |
| 227 | +returnbuffer.take(); |
| 228 | + } |
| 229 | + |
| 230 | +booleanisReady() { |
| 231 | +returnisCancelled || !buffer.isEmpty(); |
| 232 | + } |
| 233 | + |
| 234 | +/** |
| 235 | + * Cancels the underlying RPC and causes getNext to always return EOF_MARKER. This can only be |
| 236 | + * called after starting the underlying call. |
| 237 | + */ |
| 238 | +voidcancel() { |
| 239 | +isCancelled = true; |
| 240 | +controller.cancel(); |
| 241 | + } |
| 242 | + |
| 243 | +/** |
| 244 | + * Before starting the RPC, disable automatic flow control and retain a reference to the |
| 245 | + * controller. |
| 246 | + * |
| 247 | + * @param controller The controller for the stream. |
| 248 | + */ |
| 249 | +@Override |
| 250 | +publicvoidonStart(StreamControllercontroller) { |
| 251 | +this.controller = controller; |
| 252 | +controller.disableAutoInboundFlowControl(); |
| 253 | +controller.request(1); |
| 254 | + } |
| 255 | + |
| 256 | +/** |
| 257 | + * Buffer the response. There should be at most 1 response in the buffer |
| 258 | + * |
| 259 | + * @param response The received response. |
| 260 | + */ |
| 261 | +@Override |
| 262 | +publicvoidonResponse(Vresponse) { |
| 263 | +buffer.add(response); |
| 264 | + } |
| 265 | + |
| 266 | +/** |
| 267 | + * Enqueue the error to be thrown later on. The error might occur w/o a request so the queue |
| 268 | + * might grow to 2 elements, in that case the previous response will be consumed first. |
| 269 | + * |
| 270 | + * @param t The error occurred on the stream |
| 271 | + */ |
| 272 | +@Override |
| 273 | +publicvoidonError(Throwablet) { |
| 274 | +buffer.add(t); |
| 275 | + } |
| 276 | + |
| 277 | +/** |
| 278 | + * Enqueue a marker to notify the consumer that the stream is finished. In most situations this |
| 279 | + * will cause the queue to grow to 2 elements: the requested response and an unsolicited |
| 280 | + * completion marker. |
| 281 | + */ |
| 282 | +@Override |
| 283 | +publicvoidonComplete() { |
| 284 | +buffer.add(EOF_MARKER); |
| 285 | + } |
| 286 | + } |
| 287 | +} |
0 commit comments