Search in sources :

Example 11 with SubscriptionType

use of com.amplifyframework.api.graphql.SubscriptionType in project amplify-android by aws-amplify.

the class SubscriptionProcessor method startSubscriptions.

/**
 * Start subscribing to model mutations.
 */
synchronized void startSubscriptions() throws DataStoreException {
    int subscriptionCount = modelProvider.modelNames().size() * SubscriptionType.values().length;
    // Create a latch with the number of subscriptions are requesting. Each of these will be
    // counted down when each subscription's onStarted event is called.
    AbortableCountDownLatch<DataStoreException> latch = new AbortableCountDownLatch<>(subscriptionCount);
    // Need to create a new buffer so we can properly handle retries and stop/start scenarios.
    // Re-using the same buffer has some unexpected results due to the replay aspect of the subject.
    buffer = ReplaySubject.create();
    Set<Observable<SubscriptionEvent<? extends Model>>> subscriptions = new HashSet<>();
    for (ModelSchema modelSchema : modelProvider.modelSchemas().values()) {
        for (SubscriptionType subscriptionType : SubscriptionType.values()) {
            subscriptions.add(subscriptionObservable(appSync, subscriptionType, latch, modelSchema));
        }
    }
    ongoingOperationsDisposable.add(Observable.merge(subscriptions).subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).doOnSubscribe(disposable -> LOG.info("Starting processing subscription events.")).doOnError(failure -> LOG.warn("Reading subscription events has failed.", failure)).doOnComplete(() -> LOG.warn("Reading subscription events is completed.")).subscribe(buffer::onNext, buffer::onError, buffer::onComplete));
    boolean subscriptionsStarted;
    try {
        LOG.debug("Waiting for subscriptions to start.");
        subscriptionsStarted = latch.abortableAwait(adjustedTimeoutSeconds, TimeUnit.SECONDS);
    } catch (InterruptedException exception) {
        LOG.warn("Subscription operations were interrupted during setup.");
        return;
    }
    if (subscriptionsStarted) {
        Amplify.Hub.publish(HubChannel.DATASTORE, HubEvent.create(DataStoreChannelEventName.SUBSCRIPTIONS_ESTABLISHED));
        LOG.info(String.format(Locale.US, "Started subscription processor for models: %s of types %s.", modelProvider.modelNames(), Arrays.toString(SubscriptionType.values())));
    } else {
        throw new DataStoreException("Timed out waiting for subscription processor to start.", "Retry");
    }
}
Also used : Arrays(java.util.Arrays) AmplifyException(com.amplifyframework.AmplifyException) NonNull(androidx.annotation.NonNull) ModelWithMetadata(com.amplifyframework.datastore.appsync.ModelWithMetadata) ModelProvider(com.amplifyframework.core.model.ModelProvider) DataStoreChannelEventName(com.amplifyframework.datastore.DataStoreChannelEventName) AppSync(com.amplifyframework.datastore.appsync.AppSync) AtomicReference(java.util.concurrent.atomic.AtomicReference) Empty(com.amplifyframework.util.Empty) SchemaRegistry(com.amplifyframework.core.model.SchemaRegistry) HashSet(java.util.HashSet) Schedulers(io.reactivex.rxjava3.schedulers.Schedulers) AppSyncExtensions(com.amplifyframework.datastore.appsync.AppSyncExtensions) Consumer(com.amplifyframework.core.Consumer) CompositeDisposable(io.reactivex.rxjava3.disposables.CompositeDisposable) SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) Locale(java.util.Locale) Observable(io.reactivex.rxjava3.core.Observable) ModelSchema(com.amplifyframework.core.model.ModelSchema) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) HubEvent(com.amplifyframework.hub.HubEvent) Amplify(com.amplifyframework.core.Amplify) HubChannel(com.amplifyframework.hub.HubChannel) SerializedModel(com.amplifyframework.core.model.SerializedModel) AppSyncErrorType(com.amplifyframework.datastore.appsync.AppSyncExtensions.AppSyncErrorType) Model(com.amplifyframework.core.model.Model) Set(java.util.Set) Completable(io.reactivex.rxjava3.core.Completable) Action(com.amplifyframework.core.Action) Logger(com.amplifyframework.logging.Logger) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) DataStoreException(com.amplifyframework.datastore.DataStoreException) List(java.util.List) Cancelable(com.amplifyframework.core.async.Cancelable) ReplaySubject(io.reactivex.rxjava3.subjects.ReplaySubject) AmplifyDisposables(com.amplifyframework.datastore.AmplifyDisposables) GraphQLResponseException(com.amplifyframework.datastore.DataStoreException.GraphQLResponseException) VisibleForTesting(androidx.annotation.VisibleForTesting) ModelSchema(com.amplifyframework.core.model.ModelSchema) SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) DataStoreException(com.amplifyframework.datastore.DataStoreException) Observable(io.reactivex.rxjava3.core.Observable) HashSet(java.util.HashSet)

Example 12 with SubscriptionType

use of com.amplifyframework.api.graphql.SubscriptionType in project amplify-android by aws-amplify.

the class AppSyncClient method subscription.

private <T extends Model> Cancelable subscription(SubscriptionType subscriptionType, ModelSchema modelSchema, Consumer<String> onSubscriptionStarted, Consumer<GraphQLResponse<ModelWithMetadata<T>>> onNextResponse, Consumer<DataStoreException> onSubscriptionFailure, Action onSubscriptionCompleted) {
    final GraphQLRequest<ModelWithMetadata<T>> request;
    try {
        request = AppSyncRequestFactory.buildSubscriptionRequest(modelSchema, subscriptionType, authModeStrategyType);
    } catch (DataStoreException requestGenerationException) {
        onSubscriptionFailure.accept(requestGenerationException);
        return new NoOpCancelable();
    }
    final Consumer<GraphQLResponse<ModelWithMetadata<T>>> responseConsumer = response -> {
        if (response.hasErrors()) {
            onSubscriptionFailure.accept(new DataStoreException.GraphQLResponseException("Subscription error for " + modelSchema.getName() + ": " + response.getErrors(), response.getErrors()));
        } else {
            onNextResponse.accept(response);
        }
    };
    final Consumer<ApiException> failureConsumer = failure -> onSubscriptionFailure.accept(new DataStoreException("Error during subscription.", failure, "Evaluate details."));
    final Cancelable cancelable = api.subscribe(request, onSubscriptionStarted, responseConsumer, failureConsumer, onSubscriptionCompleted);
    if (cancelable != null) {
        return cancelable;
    }
    return new NoOpCancelable();
}
Also used : Amplify(com.amplifyframework.core.Amplify) AmplifyException(com.amplifyframework.AmplifyException) NonNull(androidx.annotation.NonNull) QueryPredicates(com.amplifyframework.core.model.query.predicate.QueryPredicates) GraphQLRequest(com.amplifyframework.api.graphql.GraphQLRequest) Model(com.amplifyframework.core.model.Model) Action(com.amplifyframework.core.Action) ApiException(com.amplifyframework.api.ApiException) Logger(com.amplifyframework.logging.Logger) GraphQLBehavior(com.amplifyframework.api.graphql.GraphQLBehavior) DataStoreException(com.amplifyframework.datastore.DataStoreException) Consumer(com.amplifyframework.core.Consumer) Nullable(androidx.annotation.Nullable) Cancelable(com.amplifyframework.core.async.Cancelable) SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) AuthModeStrategyType(com.amplifyframework.api.aws.AuthModeStrategyType) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ModelSchema(com.amplifyframework.core.model.ModelSchema) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) ApiCategoryBehavior(com.amplifyframework.api.ApiCategoryBehavior) PaginatedResult(com.amplifyframework.api.graphql.PaginatedResult) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate) DataStoreException(com.amplifyframework.datastore.DataStoreException) GraphQLResponse(com.amplifyframework.api.graphql.GraphQLResponse) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) Cancelable(com.amplifyframework.core.async.Cancelable) NoOpCancelable(com.amplifyframework.core.async.NoOpCancelable) ApiException(com.amplifyframework.api.ApiException)

Example 13 with SubscriptionType

use of com.amplifyframework.api.graphql.SubscriptionType in project amplify-android by aws-amplify.

the class AuthRuleRequestDecoratorTest method ownerArgumentAddedIfOwnerIsNotInCustomGroup.

/**
 * Verify owner argument is added if model contains both owner-based and group-based
 * authorization and the user is not in any read-restricted group.
 * @throws AmplifyException if a ModelSchema can't be derived from the Model class.
 */
@Test
public void ownerArgumentAddedIfOwnerIsNotInCustomGroup() throws AmplifyException {
    final AuthorizationType mode = AuthorizationType.OPENID_CONNECT;
    final String expectedOwner = FakeOidcAuthProvider.SUB;
    // but user is not in the read-restricted custom group.
    for (SubscriptionType subscriptionType : SubscriptionType.values()) {
        GraphQLRequest<OwnerNotInCustomGroup> originalRequest = createRequest(OwnerNotInCustomGroup.class, subscriptionType);
        GraphQLRequest<OwnerNotInCustomGroup> modifiedRequest = decorator.decorate(originalRequest, mode);
        assertEquals(expectedOwner, getOwnerField(modifiedRequest));
    }
}
Also used : SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) AuthorizationType(com.amplifyframework.api.aws.AuthorizationType) Test(org.junit.Test)

Example 14 with SubscriptionType

use of com.amplifyframework.api.graphql.SubscriptionType in project amplify-android by aws-amplify.

the class AuthRuleRequestDecoratorTest method ownerArgumentNotAddedForNonRestrictedReadWithUserPools.

/**
 * Verify owner argument is NOT required if the subscription type is not one of the restricted operations.
 * @throws AmplifyException if a ModelSchema can't be derived from the Model class.
 */
@Test
public void ownerArgumentNotAddedForNonRestrictedReadWithUserPools() throws AmplifyException {
    final AuthorizationType mode = AuthorizationType.AMAZON_COGNITO_USER_POOLS;
    // OwnerCreate class only has restriction on CREATE
    for (SubscriptionType subscriptionType : SubscriptionType.values()) {
        GraphQLRequest<OwnerCreate> originalRequest = createRequest(OwnerCreate.class, subscriptionType);
        GraphQLRequest<OwnerCreate> modifiedRequest = decorator.decorate(originalRequest, mode);
        assertNull(getOwnerField(modifiedRequest));
    }
    // OwnerUpdate class only has restriction on UPDATE
    for (SubscriptionType subscriptionType : SubscriptionType.values()) {
        GraphQLRequest<OwnerUpdate> originalRequest = createRequest(OwnerUpdate.class, subscriptionType);
        GraphQLRequest<OwnerUpdate> modifiedRequest = decorator.decorate(originalRequest, mode);
        assertNull(getOwnerField(modifiedRequest));
    }
    // OwnerDelete class only has restriction on DELETE
    for (SubscriptionType subscriptionType : SubscriptionType.values()) {
        GraphQLRequest<OwnerDelete> originalRequest = createRequest(OwnerDelete.class, subscriptionType);
        GraphQLRequest<OwnerDelete> modifiedRequest = decorator.decorate(originalRequest, mode);
        assertNull(getOwnerField(modifiedRequest));
    }
}
Also used : SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) AuthorizationType(com.amplifyframework.api.aws.AuthorizationType) Test(org.junit.Test)

Example 15 with SubscriptionType

use of com.amplifyframework.api.graphql.SubscriptionType in project amplify-android by aws-amplify.

the class AuthRuleRequestDecoratorTest method ownerArgumentAddedForRestrictedReadWithUserPools.

/**
 * Verify that owner argument is required for all subscriptions if ModelOperation.READ is specified
 * while using Cognito User Pools auth mode.
 * @throws AmplifyException if a ModelSchema can't be derived from the Model class.
 */
@Test
public void ownerArgumentAddedForRestrictedReadWithUserPools() throws AmplifyException {
    final AuthorizationType mode = AuthorizationType.AMAZON_COGNITO_USER_POOLS;
    final String expectedOwner = FakeCognitoAuthProvider.USERNAME;
    // Owner class has restriction on every operation including READ
    for (SubscriptionType subscriptionType : SubscriptionType.values()) {
        GraphQLRequest<Owner> originalRequest = createRequest(Owner.class, subscriptionType);
        GraphQLRequest<Owner> modifiedRequest = decorator.decorate(originalRequest, mode);
        assertEquals(expectedOwner, getOwnerField(modifiedRequest));
    }
    // OwnerRead class only has restriction on READ
    for (SubscriptionType subscriptionType : SubscriptionType.values()) {
        GraphQLRequest<OwnerRead> originalRequest = createRequest(OwnerRead.class, subscriptionType);
        GraphQLRequest<OwnerRead> modifiedRequest = decorator.decorate(originalRequest, mode);
        assertEquals(expectedOwner, getOwnerField(modifiedRequest));
    }
}
Also used : SubscriptionType(com.amplifyframework.api.graphql.SubscriptionType) AuthorizationType(com.amplifyframework.api.aws.AuthorizationType) Test(org.junit.Test)

Aggregations

SubscriptionType (com.amplifyframework.api.graphql.SubscriptionType)15 Test (org.junit.Test)12 AuthorizationType (com.amplifyframework.api.aws.AuthorizationType)9 GraphQLResponse (com.amplifyframework.api.graphql.GraphQLResponse)6 Action (com.amplifyframework.core.Action)6 Consumer (com.amplifyframework.core.Consumer)6 Cancelable (com.amplifyframework.core.async.Cancelable)6 Model (com.amplifyframework.core.model.Model)6 ModelSchema (com.amplifyframework.core.model.ModelSchema)6 DataStoreException (com.amplifyframework.datastore.DataStoreException)6 ModelProvider (com.amplifyframework.core.model.ModelProvider)5 SchemaRegistry (com.amplifyframework.core.model.SchemaRegistry)5 AppSync (com.amplifyframework.datastore.appsync.AppSync)5 ModelWithMetadata (com.amplifyframework.datastore.appsync.ModelWithMetadata)5 Completable (io.reactivex.rxjava3.core.Completable)5 Observable (io.reactivex.rxjava3.core.Observable)5 List (java.util.List)5 TimeUnit (java.util.concurrent.TimeUnit)5 NoOpCancelable (com.amplifyframework.core.async.NoOpCancelable)4 NonNull (androidx.annotation.NonNull)3