Search in sources :

Example 66 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException 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 67 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException in project amplify-android by aws-amplify.

the class SyncTimeRegistry method lookupLastSyncTime.

Single<SyncTime> lookupLastSyncTime(@NonNull String modelClassName) {
    return Single.create(emitter -> {
        QueryPredicate hasMatchingModelClassName = QueryField.field("modelClassName").eq(modelClassName);
        localStorageAdapter.query(LastSyncMetadata.class, Where.matches(hasMatchingModelClassName), results -> {
            try {
                LastSyncMetadata syncMetadata = extractSingleResult(modelClassName, results);
                emitter.onSuccess(SyncTime.from(syncMetadata.getLastSyncTime()));
            } catch (DataStoreException queryResultFailure) {
                emitter.onError(queryResultFailure);
            }
        }, emitter::onError);
    });
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException) QueryPredicate(com.amplifyframework.core.model.query.predicate.QueryPredicate)

Example 68 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException in project amplify-android by aws-amplify.

the class MutationProcessor method drainMutationOutbox.

private Completable drainMutationOutbox() {
    PendingMutation<? extends Model> next;
    do {
        next = mutationOutbox.peek();
        if (next == null) {
            return Completable.complete();
        }
        boolean itemFailedToProcess = !processOutboxItem(next).blockingAwait(ITEM_PROCESSING_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        if (itemFailedToProcess) {
            return Completable.error(new DataStoreException("Failed to process " + next, "Check your internet connection."));
        }
    } while (true);
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException)

Example 69 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException in project amplify-android by aws-amplify.

the class Orchestrator method performSynchronized.

private Completable performSynchronized(Action action) {
    boolean permitAvailable = startStopSemaphore.availablePermits() > 0;
    LOG.debug("Attempting to acquire lock. Permits available = " + permitAvailable);
    try {
        if (!startStopSemaphore.tryAcquire(LOCAL_OP_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
            return Completable.error(new DataStoreException("Timed out acquiring orchestrator lock.", "Retry your request."));
        }
    } catch (InterruptedException exception) {
        return Completable.error(new DataStoreException("Interrupted while acquiring orchestrator lock.", "Retry your request."));
    }
    LOG.info("Orchestrator lock acquired.");
    return Completable.fromAction(action).doFinally(() -> {
        startStopSemaphore.release();
        LOG.info("Orchestrator lock released.");
    });
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException)

Example 70 with DataStoreException

use of com.amplifyframework.datastore.DataStoreException in project amplify-android by aws-amplify.

the class PersistentMutationOutbox method markInFlight.

@NonNull
@Override
public Completable markInFlight(@NonNull TimeBasedUuid pendingMutationId) {
    return Completable.create(emitter -> {
        PendingMutation<? extends Model> mutation = mutationQueue.getMutationById(pendingMutationId);
        if (mutation != null) {
            inFlightMutations.add(mutation.getMutationId());
            emitter.onComplete();
            return;
        }
        emitter.onError(new DataStoreException("Outbox was asked to mark a mutation with ID = " + pendingMutationId + " as in-flight. " + "However, there was no mutation with that ID in the outbox, to begin with.", AmplifyException.REPORT_BUG_TO_AWS_SUGGESTION));
    });
}
Also used : DataStoreException(com.amplifyframework.datastore.DataStoreException) NonNull(androidx.annotation.NonNull)

Aggregations

DataStoreException (com.amplifyframework.datastore.DataStoreException)89 Test (org.junit.Test)52 BlogOwner (com.amplifyframework.testmodels.commentsblog.BlogOwner)36 Consumer (com.amplifyframework.core.Consumer)32 List (java.util.List)32 Cancelable (com.amplifyframework.core.async.Cancelable)31 Model (com.amplifyframework.core.model.Model)31 ArrayList (java.util.ArrayList)31 AmplifyException (com.amplifyframework.AmplifyException)29 ModelSchema (com.amplifyframework.core.model.ModelSchema)28 Collections (java.util.Collections)28 Action (com.amplifyframework.core.Action)27 QueryPredicate (com.amplifyframework.core.model.query.predicate.QueryPredicate)27 TimeUnit (java.util.concurrent.TimeUnit)25 Post (com.amplifyframework.testmodels.commentsblog.Post)23 PostStatus (com.amplifyframework.testmodels.commentsblog.PostStatus)23 Arrays (java.util.Arrays)23 Assert.assertEquals (org.junit.Assert.assertEquals)23 ObserveQueryOptions (com.amplifyframework.core.model.query.ObserveQueryOptions)22 DataStoreQuerySnapshot (com.amplifyframework.datastore.DataStoreQuerySnapshot)21