Search in sources :

Example 71 with DocumentKey

use of com.google.firebase.firestore.model.DocumentKey in project firebase-android-sdk by firebase.

the class SyncEngine method loadBundle.

public void loadBundle(BundleReader bundleReader, LoadBundleTask resultTask) {
    try {
        BundleMetadata bundleMetadata = bundleReader.getBundleMetadata();
        boolean hasNewerBundle = localStore.hasNewerBundle(bundleMetadata);
        if (hasNewerBundle) {
            resultTask.setResult(LoadBundleTaskProgress.forSuccess(bundleMetadata));
            return;
        }
        @Nullable LoadBundleTaskProgress progress = LoadBundleTaskProgress.forInitial(bundleMetadata);
        resultTask.updateProgress(progress);
        BundleLoader bundleLoader = new BundleLoader(localStore, bundleMetadata);
        long currentBytesRead = 0;
        BundleElement bundleElement;
        while ((bundleElement = bundleReader.getNextElement()) != null) {
            long oldBytesRead = currentBytesRead;
            currentBytesRead = bundleReader.getBytesRead();
            progress = bundleLoader.addElement(bundleElement, currentBytesRead - oldBytesRead);
            if (progress != null) {
                resultTask.updateProgress(progress);
            }
        }
        ImmutableSortedMap<DocumentKey, Document> changes = bundleLoader.applyChanges();
        // TODO(b/160876443): This currently raises snapshots with `fromCache=false` if users already
        // listen to some queries and bundles has newer version.
        emitNewSnapsAndNotifyLocalStore(changes, /* remoteEvent= */
        null);
        // Save metadata, so loading the same bundle will skip.
        localStore.saveBundle(bundleMetadata);
        resultTask.setResult(LoadBundleTaskProgress.forSuccess(bundleMetadata));
    } catch (Exception e) {
        Logger.warn("Firestore", "Loading bundle failed : %s", e);
        resultTask.setException(new FirebaseFirestoreException("Bundle failed to load", FirebaseFirestoreException.Code.INVALID_ARGUMENT, e));
    } finally {
        try {
            bundleReader.close();
        } catch (IOException e) {
            Logger.warn("SyncEngine", "Exception while closing bundle", e);
        }
    }
}
Also used : BundleElement(com.google.firebase.firestore.bundle.BundleElement) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) IOException(java.io.IOException) Document(com.google.firebase.firestore.model.Document) MutableDocument(com.google.firebase.firestore.model.MutableDocument) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) IOException(java.io.IOException) BundleMetadata(com.google.firebase.firestore.bundle.BundleMetadata) DocumentKey(com.google.firebase.firestore.model.DocumentKey) LoadBundleTaskProgress(com.google.firebase.firestore.LoadBundleTaskProgress) Nullable(androidx.annotation.Nullable) BundleLoader(com.google.firebase.firestore.bundle.BundleLoader)

Example 72 with DocumentKey

use of com.google.firebase.firestore.model.DocumentKey in project firebase-android-sdk by firebase.

the class SyncEngine method handleRejectedListen.

/**
 * Called by FirestoreClient to notify us of a rejected listen.
 */
@Override
public void handleRejectedListen(int targetId, Status error) {
    assertCallback("handleRejectedListen");
    LimboResolution limboResolution = activeLimboResolutionsByTarget.get(targetId);
    DocumentKey limboKey = limboResolution != null ? limboResolution.key : null;
    if (limboKey != null) {
        // Since this query failed, we won't want to manually unlisten to it.
        // So go ahead and remove it from bookkeeping.
        activeLimboTargetsByKey.remove(limboKey);
        activeLimboResolutionsByTarget.remove(targetId);
        pumpEnqueuedLimboResolutions();
        // TODO: Retry on transient errors?
        // It's a limbo doc. Create a synthetic event saying it was deleted. This is kind of a hack.
        // Ideally, we would have a method in the local store to purge a document. However, it would
        // be tricky to keep all of the local store's invariants with another method.
        MutableDocument result = MutableDocument.newNoDocument(limboKey, SnapshotVersion.NONE);
        Map<DocumentKey, MutableDocument> documentUpdates = Collections.singletonMap(limboKey, result);
        Set<DocumentKey> limboDocuments = Collections.singleton(limboKey);
        RemoteEvent event = new RemoteEvent(SnapshotVersion.NONE, /* targetChanges= */
        Collections.emptyMap(), /* targetMismatches= */
        Collections.emptySet(), documentUpdates, limboDocuments);
        handleRemoteEvent(event);
    } else {
        localStore.releaseTarget(targetId);
        removeAndCleanupTarget(targetId, error);
    }
}
Also used : RemoteEvent(com.google.firebase.firestore.remote.RemoteEvent) DocumentKey(com.google.firebase.firestore.model.DocumentKey) MutableDocument(com.google.firebase.firestore.model.MutableDocument)

Example 73 with DocumentKey

use of com.google.firebase.firestore.model.DocumentKey in project firebase-android-sdk by firebase.

the class SyncEngine method removeAndCleanupTarget.

private void removeAndCleanupTarget(int targetId, Status status) {
    for (Query query : queriesByTarget.get(targetId)) {
        queryViewsByQuery.remove(query);
        if (!status.isOk()) {
            syncEngineListener.onError(query, status);
            logErrorIfInteresting(status, "Listen for %s failed", query);
        }
    }
    queriesByTarget.remove(targetId);
    ImmutableSortedSet<DocumentKey> limboKeys = limboDocumentRefs.referencesForId(targetId);
    limboDocumentRefs.removeReferencesForId(targetId);
    for (DocumentKey key : limboKeys) {
        if (!limboDocumentRefs.containsKey(key)) {
            // We removed the last reference for this key.
            removeLimboTarget(key);
        }
    }
}
Also used : DocumentKey(com.google.firebase.firestore.model.DocumentKey)

Example 74 with DocumentKey

use of com.google.firebase.firestore.model.DocumentKey in project firebase-android-sdk by firebase.

the class BundleSerializer method decodeBundledDocumentMetadata.

public BundledDocumentMetadata decodeBundledDocumentMetadata(JSONObject bundledDocumentMetadata) throws JSONException {
    DocumentKey key = DocumentKey.fromPath(decodeName(bundledDocumentMetadata.getString("name")));
    SnapshotVersion readTime = decodeSnapshotVersion(bundledDocumentMetadata.get("readTime"));
    boolean exists = bundledDocumentMetadata.optBoolean("exists", false);
    JSONArray queriesJson = bundledDocumentMetadata.optJSONArray("queries");
    List<String> queries = new ArrayList<>();
    // array the same to avoid crashing during data import.
    if (queriesJson != null) {
        for (int i = 0; i < queriesJson.length(); ++i) {
            queries.add(queriesJson.getString(i));
        }
    }
    return new BundledDocumentMetadata(key, readTime, exists, queries);
}
Also used : SnapshotVersion(com.google.firebase.firestore.model.SnapshotVersion) DocumentKey(com.google.firebase.firestore.model.DocumentKey) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString)

Example 75 with DocumentKey

use of com.google.firebase.firestore.model.DocumentKey in project firebase-android-sdk by firebase.

the class BundleSerializer method decodeDocument.

BundleDocument decodeDocument(JSONObject document) throws JSONException {
    String name = document.getString("name");
    DocumentKey key = DocumentKey.fromPath(decodeName(name));
    SnapshotVersion updateTime = decodeSnapshotVersion(document.get("updateTime"));
    Value.Builder value = Value.newBuilder();
    decodeMapValue(value, document.getJSONObject("fields"));
    return new BundleDocument(MutableDocument.newFoundDocument(key, updateTime, ObjectValue.fromMap(value.getMapValue().getFieldsMap())));
}
Also used : SnapshotVersion(com.google.firebase.firestore.model.SnapshotVersion) DocumentKey(com.google.firebase.firestore.model.DocumentKey) ObjectValue(com.google.firebase.firestore.model.ObjectValue) Value(com.google.firestore.v1.Value) NullValue(com.google.protobuf.NullValue) MapValue(com.google.firestore.v1.MapValue) ArrayValue(com.google.firestore.v1.ArrayValue) ByteString(com.google.protobuf.ByteString)

Aggregations

DocumentKey (com.google.firebase.firestore.model.DocumentKey)134 MutableDocument (com.google.firebase.firestore.model.MutableDocument)52 Test (org.junit.Test)36 HashMap (java.util.HashMap)29 ArrayList (java.util.ArrayList)25 Document (com.google.firebase.firestore.model.Document)23 SnapshotVersion (com.google.firebase.firestore.model.SnapshotVersion)16 Mutation (com.google.firebase.firestore.model.mutation.Mutation)15 Map (java.util.Map)15 ResourcePath (com.google.firebase.firestore.model.ResourcePath)13 MutationBatch (com.google.firebase.firestore.model.mutation.MutationBatch)11 HashSet (java.util.HashSet)11 Overlay (com.google.firebase.firestore.model.mutation.Overlay)10 ImmutableSortedMap (com.google.firebase.database.collection.ImmutableSortedMap)9 TestUtil.patchMutation (com.google.firebase.firestore.testutil.TestUtil.patchMutation)7 TestUtil.setMutation (com.google.firebase.firestore.testutil.TestUtil.setMutation)7 ByteString (com.google.protobuf.ByteString)7 Query (com.google.firebase.firestore.core.Query)6 ObjectValue (com.google.firebase.firestore.model.ObjectValue)6 Timestamp (com.google.firebase.Timestamp)5