software.amazon.awssdk.services.transcribestreaming.DefaultTranscribeStreamingAsyncClient Maven / Gradle / Ivy
Show all versions of transcribestreaming Show documentation
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package software.amazon.awssdk.services.transcribestreaming;
import static software.amazon.awssdk.utils.FunctionalUtils.runAndLogError;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.Generated;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.client.handler.AwsAsyncClientHandler;
import software.amazon.awssdk.awscore.client.handler.AwsClientHandlerUtils;
import software.amazon.awssdk.awscore.eventstream.EventStreamAsyncResponseTransformer;
import software.amazon.awssdk.awscore.eventstream.EventStreamTaggedUnionJsonMarshaller;
import software.amazon.awssdk.awscore.eventstream.EventStreamTaggedUnionPojoSupplier;
import software.amazon.awssdk.awscore.eventstream.RestEventStreamAsyncResponseTransformer;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.awscore.internal.AwsProtocolMetadata;
import software.amazon.awssdk.awscore.internal.AwsServiceProtocol;
import software.amazon.awssdk.awscore.retry.AwsRetryStrategy;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkPlugin;
import software.amazon.awssdk.core.SdkPojoBuilder;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkAdvancedAsyncClientOption;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.client.handler.AsyncClientHandler;
import software.amazon.awssdk.core.client.handler.AttachHttpMetadataResponseHandler;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.protocol.VoidSdkResponse;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.json.AwsJsonProtocol;
import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory;
import software.amazon.awssdk.protocols.json.BaseAwsJsonProtocolFactory;
import software.amazon.awssdk.protocols.json.JsonOperationMetadata;
import software.amazon.awssdk.retries.api.RetryStrategy;
import software.amazon.awssdk.services.transcribestreaming.internal.TranscribeStreamingServiceClientConfigurationBuilder;
import software.amazon.awssdk.services.transcribestreaming.model.AudioEvent;
import software.amazon.awssdk.services.transcribestreaming.model.AudioStream;
import software.amazon.awssdk.services.transcribestreaming.model.BadRequestException;
import software.amazon.awssdk.services.transcribestreaming.model.CallAnalyticsTranscriptResultStream;
import software.amazon.awssdk.services.transcribestreaming.model.ConflictException;
import software.amazon.awssdk.services.transcribestreaming.model.InternalFailureException;
import software.amazon.awssdk.services.transcribestreaming.model.LimitExceededException;
import software.amazon.awssdk.services.transcribestreaming.model.MedicalTranscriptResultStream;
import software.amazon.awssdk.services.transcribestreaming.model.ServiceUnavailableException;
import software.amazon.awssdk.services.transcribestreaming.model.StartCallAnalyticsStreamTranscriptionRequest;
import software.amazon.awssdk.services.transcribestreaming.model.StartCallAnalyticsStreamTranscriptionResponse;
import software.amazon.awssdk.services.transcribestreaming.model.StartCallAnalyticsStreamTranscriptionResponseHandler;
import software.amazon.awssdk.services.transcribestreaming.model.StartMedicalStreamTranscriptionRequest;
import software.amazon.awssdk.services.transcribestreaming.model.StartMedicalStreamTranscriptionResponse;
import software.amazon.awssdk.services.transcribestreaming.model.StartMedicalStreamTranscriptionResponseHandler;
import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionRequest;
import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponse;
import software.amazon.awssdk.services.transcribestreaming.model.StartStreamTranscriptionResponseHandler;
import software.amazon.awssdk.services.transcribestreaming.model.TranscribeStreamingException;
import software.amazon.awssdk.services.transcribestreaming.model.TranscriptResultStream;
import software.amazon.awssdk.services.transcribestreaming.model.audiostream.DefaultConfigurationEvent;
import software.amazon.awssdk.services.transcribestreaming.transform.AudioEventMarshaller;
import software.amazon.awssdk.services.transcribestreaming.transform.ConfigurationEventMarshaller;
import software.amazon.awssdk.services.transcribestreaming.transform.StartCallAnalyticsStreamTranscriptionRequestMarshaller;
import software.amazon.awssdk.services.transcribestreaming.transform.StartMedicalStreamTranscriptionRequestMarshaller;
import software.amazon.awssdk.services.transcribestreaming.transform.StartStreamTranscriptionRequestMarshaller;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* Internal implementation of {@link TranscribeStreamingAsyncClient}.
*
* @see TranscribeStreamingAsyncClient#builder()
*/
@Generated("software.amazon.awssdk:codegen")
@SdkInternalApi
final class DefaultTranscribeStreamingAsyncClient implements TranscribeStreamingAsyncClient {
private static final Logger log = LoggerFactory.getLogger(DefaultTranscribeStreamingAsyncClient.class);
private static final AwsProtocolMetadata protocolMetadata = AwsProtocolMetadata.builder()
.serviceProtocol(AwsServiceProtocol.REST_JSON).build();
private final AsyncClientHandler clientHandler;
private final AwsJsonProtocolFactory protocolFactory;
private final SdkClientConfiguration clientConfiguration;
private final Executor executor;
protected DefaultTranscribeStreamingAsyncClient(SdkClientConfiguration clientConfiguration) {
this.clientHandler = new AwsAsyncClientHandler(clientConfiguration);
this.clientConfiguration = clientConfiguration.toBuilder().option(SdkClientOption.SDK_CLIENT, this).build();
this.protocolFactory = init(AwsJsonProtocolFactory.builder()).build();
this.executor = clientConfiguration.option(SdkAdvancedAsyncClientOption.FUTURE_COMPLETION_EXECUTOR);
}
/**
*
* Starts a bidirectional HTTP/2 or WebSocket stream where audio is streamed to Amazon Transcribe and the
* transcription results are streamed to your application. Use this operation for Call Analytics transcriptions.
*
*
* The following parameters are required:
*
*
* -
*
* language-code
*
*
* -
*
* media-encoding
*
*
* -
*
* sample-rate
*
*
*
*
* For more information on streaming with Amazon Transcribe, see Transcribing streaming audio.
*
*
* @param startCallAnalyticsStreamTranscriptionRequest
* @return A Java Future containing the result of the StartCallAnalyticsStreamTranscription operation returned by
* the service.
* The CompletableFuture returned by this method can be completed exceptionally with the following
* exceptions. The exception returned is wrapped with CompletionException, so you need to invoke
* {@link Throwable#getCause} to retrieve the underlying exception.
*
* - BadRequestException One or more arguments to the
StartStreamTranscription
,
* StartMedicalStreamTranscription
, or StartCallAnalyticsStreamTranscription
* operation was not valid. For example, MediaEncoding
or LanguageCode
used not
* valid values. Check the specified parameters and try your request again.
* - LimitExceededException Your client has exceeded one of the Amazon Transcribe limits. This is
* typically the audio length limit. Break your audio stream into smaller chunks and try your request again.
*
* - InternalFailureException A problem occurred while processing the audio. Amazon Transcribe terminated
* processing.
* - ConflictException A new stream started with the same session ID. The current stream has been
* terminated.
* - ServiceUnavailableException The service is currently unavailable. Try your request later.
* - SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
* Can be used for catch all scenarios.
* - SdkClientException If any client side error occurs such as an IO related failure, failure to get
* credentials, etc.
* - TranscribeStreamingException Base class for all service exceptions. Unknown exceptions will be thrown
* as an instance of this type.
*
* @sample TranscribeStreamingAsyncClient.StartCallAnalyticsStreamTranscription
* @see AWS API Documentation
*/
@Override
public CompletableFuture startCallAnalyticsStreamTranscription(
StartCallAnalyticsStreamTranscriptionRequest startCallAnalyticsStreamTranscriptionRequest,
Publisher requestStream, StartCallAnalyticsStreamTranscriptionResponseHandler asyncResponseHandler) {
SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(startCallAnalyticsStreamTranscriptionRequest,
this.clientConfiguration);
List metricPublishers = resolveMetricPublishers(clientConfiguration,
startCallAnalyticsStreamTranscriptionRequest.overrideConfiguration().orElse(null));
MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector
.create("ApiCall");
try {
apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "Transcribe Streaming");
apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "StartCallAnalyticsStreamTranscription");
JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false)
.isPayloadJson(true).build();
HttpResponseHandler responseHandler = new AttachHttpMetadataResponseHandler(
protocolFactory.createResponseHandler(operationMetadata,
StartCallAnalyticsStreamTranscriptionResponse::builder));
HttpResponseHandler voidResponseHandler = protocolFactory.createResponseHandler(JsonOperationMetadata
.builder().isPayloadJson(false).hasStreamingSuccessResponse(true).build(), VoidSdkResponse::builder);
HttpResponseHandler extends CallAnalyticsTranscriptResultStream> eventResponseHandler = protocolFactory
.createResponseHandler(
JsonOperationMetadata.builder().isPayloadJson(true).hasStreamingSuccessResponse(false).build(),
EventStreamTaggedUnionPojoSupplier
.builder()
.putSdkPojoSupplier("UtteranceEvent",
CallAnalyticsTranscriptResultStream::utteranceEventBuilder)
.putSdkPojoSupplier("CategoryEvent",
CallAnalyticsTranscriptResultStream::categoryEventBuilder)
.defaultSdkPojoSupplier(() -> new SdkPojoBuilder(CallAnalyticsTranscriptResultStream.UNKNOWN))
.build());
HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory,
operationMetadata);
EventStreamTaggedUnionJsonMarshaller eventMarshaller = EventStreamTaggedUnionJsonMarshaller.builder()
.putMarshaller(AudioEvent.class, new AudioEventMarshaller(protocolFactory))
.putMarshaller(DefaultConfigurationEvent.class, new ConfigurationEventMarshaller(protocolFactory)).build();
SdkPublisher eventPublisher = SdkPublisher.adapt(requestStream);
Publisher adapted = eventPublisher.map(event -> eventMarshaller.marshall(event)).map(
AwsClientHandlerUtils::encodeEventStreamRequestToByteBuffer);
CompletableFuture future = new CompletableFuture<>();
EventStreamAsyncResponseTransformer asyncResponseTransformer = EventStreamAsyncResponseTransformer
. builder()
.eventStreamResponseHandler(asyncResponseHandler).eventResponseHandler(eventResponseHandler)
.initialResponseHandler(responseHandler).exceptionResponseHandler(errorResponseHandler).future(future)
.executor(executor).serviceName(serviceName()).build();
RestEventStreamAsyncResponseTransformer restAsyncResponseTransformer = RestEventStreamAsyncResponseTransformer
. builder()
.eventStreamAsyncResponseTransformer(asyncResponseTransformer)
.eventStreamResponseHandler(asyncResponseHandler).build();
CompletableFuture executeFuture = clientHandler
.execute(
new ClientExecutionParams()
.withOperationName("StartCallAnalyticsStreamTranscription")
.withProtocolMetadata(protocolMetadata)
.withMarshaller(new StartCallAnalyticsStreamTranscriptionRequestMarshaller(protocolFactory))
.withAsyncRequestBody(AsyncRequestBody.fromPublisher(adapted)).withFullDuplex(true)
.withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler)
.withRequestConfiguration(clientConfiguration).withMetricCollector(apiCallMetricCollector)
.withInput(startCallAnalyticsStreamTranscriptionRequest), restAsyncResponseTransformer);
CompletableFuture whenCompleted = executeFuture.whenComplete((r, e) -> {
if (e != null) {
try {
asyncResponseHandler.exceptionOccurred(e);
} finally {
future.completeExceptionally(e);
}
}
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
});
executeFuture = CompletableFutureUtils.forwardExceptionTo(whenCompleted, executeFuture);
return CompletableFutureUtils.forwardExceptionTo(future, executeFuture);
} catch (Throwable t) {
runAndLogError(log, "Exception thrown in exceptionOccurred callback, ignoring",
() -> asyncResponseHandler.exceptionOccurred(t));
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
return CompletableFutureUtils.failedFuture(t);
}
}
/**
*
* Starts a bidirectional HTTP/2 or WebSocket stream where audio is streamed to Amazon Transcribe Medical and the
* transcription results are streamed to your application.
*
*
* The following parameters are required:
*
*
* -
*
* language-code
*
*
* -
*
* media-encoding
*
*
* -
*
* sample-rate
*
*
*
*
* For more information on streaming with Amazon Transcribe Medical, see Transcribing streaming audio.
*
*
* @param startMedicalStreamTranscriptionRequest
* @return A Java Future containing the result of the StartMedicalStreamTranscription operation returned by the
* service.
* The CompletableFuture returned by this method can be completed exceptionally with the following
* exceptions. The exception returned is wrapped with CompletionException, so you need to invoke
* {@link Throwable#getCause} to retrieve the underlying exception.
*
* - BadRequestException One or more arguments to the
StartStreamTranscription
,
* StartMedicalStreamTranscription
, or StartCallAnalyticsStreamTranscription
* operation was not valid. For example, MediaEncoding
or LanguageCode
used not
* valid values. Check the specified parameters and try your request again.
* - LimitExceededException Your client has exceeded one of the Amazon Transcribe limits. This is
* typically the audio length limit. Break your audio stream into smaller chunks and try your request again.
*
* - InternalFailureException A problem occurred while processing the audio. Amazon Transcribe terminated
* processing.
* - ConflictException A new stream started with the same session ID. The current stream has been
* terminated.
* - ServiceUnavailableException The service is currently unavailable. Try your request later.
* - SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
* Can be used for catch all scenarios.
* - SdkClientException If any client side error occurs such as an IO related failure, failure to get
* credentials, etc.
* - TranscribeStreamingException Base class for all service exceptions. Unknown exceptions will be thrown
* as an instance of this type.
*
* @sample TranscribeStreamingAsyncClient.StartMedicalStreamTranscription
* @see AWS API Documentation
*/
@Override
public CompletableFuture startMedicalStreamTranscription(
StartMedicalStreamTranscriptionRequest startMedicalStreamTranscriptionRequest, Publisher requestStream,
StartMedicalStreamTranscriptionResponseHandler asyncResponseHandler) {
SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(startMedicalStreamTranscriptionRequest,
this.clientConfiguration);
List metricPublishers = resolveMetricPublishers(clientConfiguration,
startMedicalStreamTranscriptionRequest.overrideConfiguration().orElse(null));
MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector
.create("ApiCall");
try {
apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "Transcribe Streaming");
apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "StartMedicalStreamTranscription");
JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false)
.isPayloadJson(true).build();
HttpResponseHandler responseHandler = new AttachHttpMetadataResponseHandler(
protocolFactory.createResponseHandler(operationMetadata, StartMedicalStreamTranscriptionResponse::builder));
HttpResponseHandler voidResponseHandler = protocolFactory.createResponseHandler(JsonOperationMetadata
.builder().isPayloadJson(false).hasStreamingSuccessResponse(true).build(), VoidSdkResponse::builder);
HttpResponseHandler extends MedicalTranscriptResultStream> eventResponseHandler = protocolFactory
.createResponseHandler(
JsonOperationMetadata.builder().isPayloadJson(true).hasStreamingSuccessResponse(false).build(),
EventStreamTaggedUnionPojoSupplier.builder()
.putSdkPojoSupplier("TranscriptEvent", MedicalTranscriptResultStream::transcriptEventBuilder)
.defaultSdkPojoSupplier(() -> new SdkPojoBuilder(MedicalTranscriptResultStream.UNKNOWN))
.build());
HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory,
operationMetadata);
EventStreamTaggedUnionJsonMarshaller eventMarshaller = EventStreamTaggedUnionJsonMarshaller.builder()
.putMarshaller(AudioEvent.class, new AudioEventMarshaller(protocolFactory))
.putMarshaller(DefaultConfigurationEvent.class, new ConfigurationEventMarshaller(protocolFactory)).build();
SdkPublisher eventPublisher = SdkPublisher.adapt(requestStream);
Publisher adapted = eventPublisher.map(event -> eventMarshaller.marshall(event)).map(
AwsClientHandlerUtils::encodeEventStreamRequestToByteBuffer);
CompletableFuture future = new CompletableFuture<>();
EventStreamAsyncResponseTransformer asyncResponseTransformer = EventStreamAsyncResponseTransformer
. builder()
.eventStreamResponseHandler(asyncResponseHandler).eventResponseHandler(eventResponseHandler)
.initialResponseHandler(responseHandler).exceptionResponseHandler(errorResponseHandler).future(future)
.executor(executor).serviceName(serviceName()).build();
RestEventStreamAsyncResponseTransformer restAsyncResponseTransformer = RestEventStreamAsyncResponseTransformer
. builder()
.eventStreamAsyncResponseTransformer(asyncResponseTransformer)
.eventStreamResponseHandler(asyncResponseHandler).build();
CompletableFuture executeFuture = clientHandler.execute(
new ClientExecutionParams()
.withOperationName("StartMedicalStreamTranscription").withProtocolMetadata(protocolMetadata)
.withMarshaller(new StartMedicalStreamTranscriptionRequestMarshaller(protocolFactory))
.withAsyncRequestBody(AsyncRequestBody.fromPublisher(adapted)).withFullDuplex(true)
.withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler)
.withRequestConfiguration(clientConfiguration).withMetricCollector(apiCallMetricCollector)
.withInput(startMedicalStreamTranscriptionRequest), restAsyncResponseTransformer);
CompletableFuture whenCompleted = executeFuture.whenComplete((r, e) -> {
if (e != null) {
try {
asyncResponseHandler.exceptionOccurred(e);
} finally {
future.completeExceptionally(e);
}
}
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
});
executeFuture = CompletableFutureUtils.forwardExceptionTo(whenCompleted, executeFuture);
return CompletableFutureUtils.forwardExceptionTo(future, executeFuture);
} catch (Throwable t) {
runAndLogError(log, "Exception thrown in exceptionOccurred callback, ignoring",
() -> asyncResponseHandler.exceptionOccurred(t));
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
return CompletableFutureUtils.failedFuture(t);
}
}
/**
*
* Starts a bidirectional HTTP/2 or WebSocket stream where audio is streamed to Amazon Transcribe and the
* transcription results are streamed to your application.
*
*
* The following parameters are required:
*
*
* -
*
* language-code
or identify-language
or identify-multiple-language
*
*
* -
*
* media-encoding
*
*
* -
*
* sample-rate
*
*
*
*
* For more information on streaming with Amazon Transcribe, see Transcribing streaming audio.
*
*
* @param startStreamTranscriptionRequest
* @return A Java Future containing the result of the StartStreamTranscription operation returned by the service.
* The CompletableFuture returned by this method can be completed exceptionally with the following
* exceptions. The exception returned is wrapped with CompletionException, so you need to invoke
* {@link Throwable#getCause} to retrieve the underlying exception.
*
* - BadRequestException One or more arguments to the
StartStreamTranscription
,
* StartMedicalStreamTranscription
, or StartCallAnalyticsStreamTranscription
* operation was not valid. For example, MediaEncoding
or LanguageCode
used not
* valid values. Check the specified parameters and try your request again.
* - LimitExceededException Your client has exceeded one of the Amazon Transcribe limits. This is
* typically the audio length limit. Break your audio stream into smaller chunks and try your request again.
*
* - InternalFailureException A problem occurred while processing the audio. Amazon Transcribe terminated
* processing.
* - ConflictException A new stream started with the same session ID. The current stream has been
* terminated.
* - ServiceUnavailableException The service is currently unavailable. Try your request later.
* - SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
* Can be used for catch all scenarios.
* - SdkClientException If any client side error occurs such as an IO related failure, failure to get
* credentials, etc.
* - TranscribeStreamingException Base class for all service exceptions. Unknown exceptions will be thrown
* as an instance of this type.
*
* @sample TranscribeStreamingAsyncClient.StartStreamTranscription
* @see AWS API Documentation
*/
@Override
public CompletableFuture startStreamTranscription(StartStreamTranscriptionRequest startStreamTranscriptionRequest,
Publisher requestStream, StartStreamTranscriptionResponseHandler asyncResponseHandler) {
SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(startStreamTranscriptionRequest,
this.clientConfiguration);
List metricPublishers = resolveMetricPublishers(clientConfiguration, startStreamTranscriptionRequest
.overrideConfiguration().orElse(null));
MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector
.create("ApiCall");
try {
apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "Transcribe Streaming");
apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "StartStreamTranscription");
JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false)
.isPayloadJson(true).build();
HttpResponseHandler responseHandler = new AttachHttpMetadataResponseHandler(
protocolFactory.createResponseHandler(operationMetadata, StartStreamTranscriptionResponse::builder));
HttpResponseHandler voidResponseHandler = protocolFactory.createResponseHandler(JsonOperationMetadata
.builder().isPayloadJson(false).hasStreamingSuccessResponse(true).build(), VoidSdkResponse::builder);
HttpResponseHandler extends TranscriptResultStream> eventResponseHandler = protocolFactory.createResponseHandler(
JsonOperationMetadata.builder().isPayloadJson(true).hasStreamingSuccessResponse(false).build(),
EventStreamTaggedUnionPojoSupplier.builder()
.putSdkPojoSupplier("TranscriptEvent", TranscriptResultStream::transcriptEventBuilder)
.defaultSdkPojoSupplier(() -> new SdkPojoBuilder(TranscriptResultStream.UNKNOWN)).build());
HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory,
operationMetadata);
EventStreamTaggedUnionJsonMarshaller eventMarshaller = EventStreamTaggedUnionJsonMarshaller.builder()
.putMarshaller(AudioEvent.class, new AudioEventMarshaller(protocolFactory))
.putMarshaller(DefaultConfigurationEvent.class, new ConfigurationEventMarshaller(protocolFactory)).build();
SdkPublisher eventPublisher = SdkPublisher.adapt(requestStream);
Publisher adapted = eventPublisher.map(event -> eventMarshaller.marshall(event)).map(
AwsClientHandlerUtils::encodeEventStreamRequestToByteBuffer);
CompletableFuture future = new CompletableFuture<>();
EventStreamAsyncResponseTransformer asyncResponseTransformer = EventStreamAsyncResponseTransformer
. builder()
.eventStreamResponseHandler(asyncResponseHandler).eventResponseHandler(eventResponseHandler)
.initialResponseHandler(responseHandler).exceptionResponseHandler(errorResponseHandler).future(future)
.executor(executor).serviceName(serviceName()).build();
RestEventStreamAsyncResponseTransformer restAsyncResponseTransformer = RestEventStreamAsyncResponseTransformer
. builder()
.eventStreamAsyncResponseTransformer(asyncResponseTransformer)
.eventStreamResponseHandler(asyncResponseHandler).build();
CompletableFuture executeFuture = clientHandler.execute(
new ClientExecutionParams()
.withOperationName("StartStreamTranscription").withProtocolMetadata(protocolMetadata)
.withMarshaller(new StartStreamTranscriptionRequestMarshaller(protocolFactory))
.withAsyncRequestBody(AsyncRequestBody.fromPublisher(adapted)).withFullDuplex(true)
.withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler)
.withRequestConfiguration(clientConfiguration).withMetricCollector(apiCallMetricCollector)
.withInput(startStreamTranscriptionRequest), restAsyncResponseTransformer);
CompletableFuture whenCompleted = executeFuture.whenComplete((r, e) -> {
if (e != null) {
try {
asyncResponseHandler.exceptionOccurred(e);
} finally {
future.completeExceptionally(e);
}
}
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
});
executeFuture = CompletableFutureUtils.forwardExceptionTo(whenCompleted, executeFuture);
return CompletableFutureUtils.forwardExceptionTo(future, executeFuture);
} catch (Throwable t) {
runAndLogError(log, "Exception thrown in exceptionOccurred callback, ignoring",
() -> asyncResponseHandler.exceptionOccurred(t));
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
return CompletableFutureUtils.failedFuture(t);
}
}
@Override
public final TranscribeStreamingServiceClientConfiguration serviceClientConfiguration() {
return new TranscribeStreamingServiceClientConfigurationBuilder(this.clientConfiguration.toBuilder()).build();
}
@Override
public final String serviceName() {
return SERVICE_NAME;
}
private > T init(T builder) {
return builder
.clientConfiguration(clientConfiguration)
.defaultServiceExceptionSupplier(TranscribeStreamingException::builder)
.protocol(AwsJsonProtocol.REST_JSON)
.protocolVersion("1.1")
.registerModeledException(
ExceptionMetadata.builder().errorCode("ConflictException")
.exceptionBuilderSupplier(ConflictException::builder).httpStatusCode(409).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("InternalFailureException")
.exceptionBuilderSupplier(InternalFailureException::builder).httpStatusCode(500).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("ServiceUnavailableException")
.exceptionBuilderSupplier(ServiceUnavailableException::builder).httpStatusCode(503).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("BadRequestException")
.exceptionBuilderSupplier(BadRequestException::builder).httpStatusCode(400).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("LimitExceededException")
.exceptionBuilderSupplier(LimitExceededException::builder).httpStatusCode(429).build());
}
private static List resolveMetricPublishers(SdkClientConfiguration clientConfiguration,
RequestOverrideConfiguration requestOverrideConfiguration) {
List publishers = null;
if (requestOverrideConfiguration != null) {
publishers = requestOverrideConfiguration.metricPublishers();
}
if (publishers == null || publishers.isEmpty()) {
publishers = clientConfiguration.option(SdkClientOption.METRIC_PUBLISHERS);
}
if (publishers == null) {
publishers = Collections.emptyList();
}
return publishers;
}
private void updateRetryStrategyClientConfiguration(SdkClientConfiguration.Builder configuration) {
ClientOverrideConfiguration.Builder builder = configuration.asOverrideConfigurationBuilder();
RetryMode retryMode = builder.retryMode();
if (retryMode != null) {
configuration.option(SdkClientOption.RETRY_STRATEGY, AwsRetryStrategy.forRetryMode(retryMode));
} else {
Consumer> configurator = builder.retryStrategyConfigurator();
if (configurator != null) {
RetryStrategy.Builder, ?> defaultBuilder = AwsRetryStrategy.defaultRetryStrategy().toBuilder();
configurator.accept(defaultBuilder);
configuration.option(SdkClientOption.RETRY_STRATEGY, defaultBuilder.build());
} else {
RetryStrategy retryStrategy = builder.retryStrategy();
if (retryStrategy != null) {
configuration.option(SdkClientOption.RETRY_STRATEGY, retryStrategy);
}
}
}
configuration.option(SdkClientOption.CONFIGURED_RETRY_MODE, null);
configuration.option(SdkClientOption.CONFIGURED_RETRY_STRATEGY, null);
configuration.option(SdkClientOption.CONFIGURED_RETRY_CONFIGURATOR, null);
}
private SdkClientConfiguration updateSdkClientConfiguration(SdkRequest request, SdkClientConfiguration clientConfiguration) {
List plugins = request.overrideConfiguration().map(c -> c.plugins()).orElse(Collections.emptyList());
SdkClientConfiguration.Builder configuration = clientConfiguration.toBuilder();
if (plugins.isEmpty()) {
return configuration.build();
}
TranscribeStreamingServiceClientConfigurationBuilder serviceConfigBuilder = new TranscribeStreamingServiceClientConfigurationBuilder(
configuration);
for (SdkPlugin plugin : plugins) {
plugin.configureClient(serviceConfigBuilder);
}
updateRetryStrategyClientConfiguration(configuration);
return configuration.build();
}
private HttpResponseHandler createErrorResponseHandler(BaseAwsJsonProtocolFactory protocolFactory,
JsonOperationMetadata operationMetadata) {
return protocolFactory.createErrorResponseHandler(operationMetadata);
}
@Override
public void close() {
clientHandler.close();
}
}