|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License |
| 4 | + * 2.0; you may not use this file except in compliance with the Elastic License |
| 5 | + * 2.0. |
| 6 | + */ |
| 7 | + |
| 8 | +package org.elasticsearch.xpack.inference.external.http; |
| 9 | + |
| 10 | +import org.apache.http.HttpResponse; |
| 11 | +import org.elasticsearch.ExceptionsHelper; |
| 12 | +import org.elasticsearch.action.ActionListener; |
| 13 | +import org.elasticsearch.rest.RestStatus; |
| 14 | + |
| 15 | +import java.io.ByteArrayOutputStream; |
| 16 | +import java.util.concurrent.Flow; |
| 17 | +import java.util.concurrent.atomic.AtomicReference; |
| 18 | + |
| 19 | +public record StreamingHttpResult(HttpResponse response, Flow.Publisher<byte[]> body) { |
| 20 | + public boolean isSuccessfulResponse() { |
| 21 | + return RestStatus.isSuccessful(response.getStatusLine().getStatusCode()); |
| 22 | + } |
| 23 | + |
| 24 | + public Flow.Publisher<HttpResult> toHttpResult() { |
| 25 | + return subscriber -> body().subscribe(new Flow.Subscriber<>() { |
| 26 | + @Override |
| 27 | + public void onSubscribe(Flow.Subscription subscription) { |
| 28 | + subscriber.onSubscribe(subscription); |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public void onNext(byte[] item) { |
| 33 | + subscriber.onNext(new HttpResult(response(), item)); |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public void onError(Throwable throwable) { |
| 38 | + subscriber.onError(throwable); |
| 39 | + } |
| 40 | + |
| 41 | + @Override |
| 42 | + public void onComplete() { |
| 43 | + subscriber.onComplete(); |
| 44 | + } |
| 45 | + }); |
| 46 | + } |
| 47 | + |
| 48 | + public void readFullResponse(ActionListener<HttpResult> fullResponse) { |
| 49 | + var stream = new ByteArrayOutputStream(); |
| 50 | + AtomicReference<Flow.Subscription> upstream = new AtomicReference<>(null); |
| 51 | + body.subscribe(new Flow.Subscriber<>() { |
| 52 | + @Override |
| 53 | + public void onSubscribe(Flow.Subscription subscription) { |
| 54 | + upstream.set(subscription); |
| 55 | + upstream.get().request(1); |
| 56 | + } |
| 57 | + |
| 58 | + @Override |
| 59 | + public void onNext(byte[] item) { |
| 60 | + stream.writeBytes(item); |
| 61 | + upstream.get().request(1); |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + public void onError(Throwable throwable) { |
| 66 | + ExceptionsHelper.maybeError(throwable).ifPresent(ExceptionsHelper::maybeDieOnAnotherThread); |
| 67 | + fullResponse.onFailure(new RuntimeException("Fatal while fully consuming stream", throwable)); |
| 68 | + } |
| 69 | + |
| 70 | + @Override |
| 71 | + public void onComplete() { |
| 72 | + fullResponse.onResponse(new HttpResult(response, stream.toByteArray())); |
| 73 | + } |
| 74 | + }); |
| 75 | + } |
| 76 | +} |
0 commit comments