حِزم بيانات Cloud Firestore

حِزم بيانات Cloud Firestore هي ملفات بيانات ثابتة أنشأتها بنفسك مستندات Cloud Firestore ولقطات طلب البحث ونشرها من قِبلك على شبكة توصيل المحتوى (CDN) أو خدمة الاستضافة أو أي حل آخر. تتضمن حزم البيانات كلاً من المستندات التي تريد تقديمها إلى تطبيقات العميل والبيانات الوصفية المتعلقة بطلبات البحث التي أنشأها. تستخدم حزم تطوير البرامج (SDK) التابعة للعميل لتنزيل الحزم عبر الشبكة أو من مساحة التخزين المحلية، وبعدها يتم تحميل بيانات الحزمة إلى Cloud Firestore ذاكرة التخزين المؤقت المحلية. بعد تحميل حزمة، يمكن لتطبيق العميل الاستعلام عن المستندات من ذاكرة التخزين المؤقت المحلية أو الخلفية.

وباستخدام حِزم البيانات، يمكن لتطبيقاتك تحميل نتائج طلبات البحث الشائعة بشكل أسرع، نظرًا المستندات عند بدء التشغيل دون الحاجة إلى إجراء مكالمات خلفية Cloud Firestore. إذا تم تحميل النتائج من ذاكرة التخزين المؤقت المحلية، فيمكنك أيضًا يستفيدون من تقليل تكاليف الوصول. بدلاً من الدفع مقابل مليون تطبيق لإجراء طلب بحث عن نفس المستندات الأولية الـ 100، فإنك تدفع فقط مقابل الاستعلامات الحاجة إلى تجميع تلك المستندات الـ 100.

تم تصميم حِزم بيانات Cloud Firestore للعمل بشكل جيد مع تطبيقات Firebase الأخرى منتجات الخلفية. الاطّلاع على حلّ متكامل يتم فيها إنشاء الحِزم باستخدام دوال Cloud وعرضها للمستخدمين الذين لديهم استضافة Firebase.

يتضمن استخدام حزمة مع تطبيقك ثلاث خطوات:

  1. إنشاء الحزمة باستخدام SDK للمشرف
  2. عرض الحزمة من مساحة تخزين محلية أو من شبكة توصيل محتوى (CDN)
  3. جارٍ تحميل الحزم في حساب العميل

ما المقصود بحزمة البيانات؟

حزمة البيانات هي ملف ثنائي ثابت أنشأته لحزمة واحد أو أكثر. لقطات المستندات و/أو طلبات البحث والتي يمكنك منها استخراج البيانات المسمّاة طلبات البحث. وكما هو موضح أدناه، تسمح لك حِزم SDK من جانب الخادم بإنشاء حِزم حِزم تطوير البرامج (SDK) التابعة للعميل، وذلك بهدف السماح لك بتحميل الحِزم إلى ذاكرة التخزين المؤقت على الجهاز.

تعد طلبات البحث المُعنونة ميزة فعالة بشكل خاص للحزم. طلبات البحث المُعنونة هي Query عنصر يمكنك استخراجه من حزمة، ثم استخدامه على الفور للاستعلام عن البيانات إما من ذاكرة التخزين المؤقت أو من الخلفية، كما تفعل عادةً في من تطبيقك يخاطب Cloud Firestore.

إنشاء حِزم البيانات على الخادم

ويمنحك استخدام SDK للمشرف في Node.js أو Java إكمال التحكم في ما يتم تضمينه في الحزم وفي كيفية عرضها.

Node.js
var bundleId = "latest-stories";

var bundle = firestore.bundle(bundleId);

var docSnapshot = await firestore.doc('stories/stories').get();
var querySnapshot = await firestore.collection('stories').get();

// Build the bundle
// Note how querySnapshot is named "latest-stories-query"
var bundleBuffer = bundle.add(docSnapshot); // Add a document
                   .add('latest-stories-query', querySnapshot) // Add a named query.
                   .build()
      
جافا
Firestore db = FirestoreClient.getFirestore(app);

// Query the 50 latest stories
QuerySnapshot latestStories = db.collection("stories")
    .orderBy("timestamp", Direction.DESCENDING)
    .limit(50)
    .get()
    .get();

// Build the bundle from the query results
FirestoreBundle bundle = db.bundleBuilder("latest-stories")
    .add("latest-stories-query", latestStories)
    .build();
      
Python
from google.cloud import firestore
from google.cloud.firestore_bundle import FirestoreBundle

db = firestore.Client()
bundle = FirestoreBundle("latest-stories")

doc_snapshot = db.collection("stories").document("news-item").get()
query = db.collection("stories")._query()

# Build the bundle
# Note how `query` is named "latest-stories-query"
bundle_buffer: str = bundle.add_document(doc_snapshot).add_named_query(
    "latest-stories-query", query,
).build()
      

حِزم بيانات يتم عرضها

يمكنك عرض الحِزم لتطبيقات العميل من شبكة توصيل للمحتوى (CDN) أو من خلال تنزيلها. منها، على سبيل المثال، Cloud Storage.

لنفترض أنّ الحزمة التي تم إنشاؤها في القسم السابق كانت تم حفظه في ملف باسم "bundle.txt" ونشره على خادم. هذا النمط ملف الحِزمة مثل أي مادة عرض أخرى يمكنك عرضها على الويب، كما هو موضّح هنا لتطبيق Node.js Express بسيط.

const fs = require('fs');
const server = require('http').createServer();

server.on('request', (req, res) => {
  const src = fs.createReadStream('./bundle.txt');
  src.pipe(res);
});

server.listen(8000);

تحميل حِزم البيانات في حساب العميل

يمكنك تحميل حزم Firestore من خلال جلبها من خادم بعيد، سواء من خلال تقديم طلب HTTP أو استدعاء واجهة برمجة تطبيقات للتخزين أو استخدام أي أسلوب آخر لجلب الملفات الثنائية على الشبكة.

بعد استرجاع البيانات، باستخدام حزمة تطوير البرامج (SDK) لعميل Cloud Firestore، يستدعي تطبيقك loadBundle، التي تُرجع كائن تتبع المهمة، الذي ستتمكن من إكماله حتى تراقب كثيرًا حالة الوعد. عند اكتمال مهمة تحميل الحزمة بنجاح، يصبح محتوى الحزمة متاحًا في ذاكرة التخزين المؤقت المحلية.

Web

import { loadBundle, namedQuery, getDocsFromCache } from "firebase/firestore";

async function fetchFromBundle() {
  // Fetch the bundle from Firebase Hosting, if the CDN cache is hit the 'X-Cache'
  // response header will be set to 'HIT'
  const resp = await fetch('/createBundle');

  // Load the bundle contents into the Firestore SDK
  await loadBundle(db, resp.body);

  // Query the results from the cache
  const query = await namedQuery(db, 'latest-stories-query');
  const storiesSnap = await getDocsFromCache(query);

  // Use the results
  // ...
}

Web

// If you are using module bundlers.
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/firestore/bundle"; // This line enables bundle loading as a side effect.

// ...

async function fetchFromBundle() {
  // Fetch the bundle from Firebase Hosting, if the CDN cache is hit the 'X-Cache'
  // response header will be set to 'HIT'
  const resp = await fetch('/createBundle');

  // Load the bundle contents into the Firestore SDK
  await db.loadBundle(resp.body);

  // Query the results from the cache
  // Note: omitting "source: cache" will query the Firestore backend.
  const query = await db.namedQuery('latest-stories-query');
  const storiesSnap = await query.get({ source: 'cache' });

  // Use the results
  // ...
}
Swift
ملاحظة: لا يتوفّر هذا المنتج ضمن نظامَي التشغيل WatchOS وApp Clip.
// Utility function for errors when loading bundles.
func bundleLoadError(reason: String) -> NSError {
  return NSError(domain: "FIRSampleErrorDomain",
                 code: 0,
                 userInfo: [NSLocalizedFailureReasonErrorKey: reason])
}

func fetchRemoteBundle(for firestore: Firestore,
                       from url: URL) async throws -> LoadBundleTaskProgress {
  guard let inputStream = InputStream(url: url) else {
    let error = self.bundleLoadError(reason: "Unable to create stream from the given url: \(url)")
    throw error
  }

  return try await firestore.loadBundle(inputStream)
}

// Fetches a specific named query from the provided bundle.
func loadQuery(named queryName: String,
               fromRemoteBundle bundleURL: URL,
               with store: Firestore) async throws -> Query {
  let _ = try await fetchRemoteBundle(for: store, from: bundleURL)
  if let query = await store.getQuery(named: queryName) {
    return query
  } else {
    throw bundleLoadError(reason: "Could not find query named \(queryName)")
  }
}

// Load a query and fetch its results from a bundle.
func runStoriesQuery() async {
  let queryName = "latest-stories-query"
  let firestore = Firestore.firestore()
  let remoteBundle = URL(string: "https://example.com/createBundle")!

  do {
    let query = try await loadQuery(named: queryName,
                                    fromRemoteBundle: remoteBundle,
                                    with: firestore)
    let snapshot = try await query.getDocuments()
    print(snapshot)
    // handle query results
  } catch {
    print(error)
  }
}
Objective-C
ملاحظة: لا يتوفّر هذا المنتج ضمن نظامَي التشغيل WatchOS وApp Clip.
// Utility function for errors when loading bundles.
- (NSError *)bundleLoadErrorWithReason:(NSString *)reason {
  return [NSError errorWithDomain:@"FIRSampleErrorDomain"
                             code:0
                         userInfo:@{NSLocalizedFailureReasonErrorKey: reason}];
}

// Loads a remote bundle from the provided url.
- (void)fetchRemoteBundleForFirestore:(FIRFirestore *)firestore
                              fromURL:(NSURL *)url
                           completion:(void (^)(FIRLoadBundleTaskProgress *_Nullable,
                                                NSError *_Nullable))completion {
  NSInputStream *inputStream = [NSInputStream inputStreamWithURL:url];
  if (inputStream == nil) {
    // Unable to create input stream.
    NSError *error =
        [self bundleLoadErrorWithReason:
            [NSString stringWithFormat:@"Unable to create stream from the given url: %@", url]];
    completion(nil, error);
    return;
  }

  [firestore loadBundleStream:inputStream
                   completion:^(FIRLoadBundleTaskProgress * _Nullable progress,
                                NSError * _Nullable error) {
    if (progress == nil) {
      completion(nil, error);
      return;
    }

    if (progress.state == FIRLoadBundleTaskStateSuccess) {
      completion(progress, nil);
    } else {
      NSError *concreteError =
          [self bundleLoadErrorWithReason:
              [NSString stringWithFormat:
                  @"Expected bundle load to be completed, but got %ld instead",
                  (long)progress.state]];
      completion(nil, concreteError);
    }
    completion(nil, nil);
  }];
}

// Loads a bundled query.
- (void)loadQueryNamed:(NSString *)queryName
   fromRemoteBundleURL:(NSURL *)url
         withFirestore:(FIRFirestore *)firestore
            completion:(void (^)(FIRQuery *_Nullable, NSError *_Nullable))completion {
  [self fetchRemoteBundleForFirestore:firestore
                              fromURL:url
                           completion:^(FIRLoadBundleTaskProgress *progress, NSError *error) {
    if (error != nil) {
      completion(nil, error);
      return;
    }

    [firestore getQueryNamed:queryName completion:^(FIRQuery *query) {
      if (query == nil) {
        NSString *errorReason =
            [NSString stringWithFormat:@"Could not find query named %@", queryName];
        NSError *error = [self bundleLoadErrorWithReason:errorReason];
        completion(nil, error);
        return;
      }
      completion(query, nil);
    }];
  }];
}

- (void)runStoriesQuery {
  NSString *queryName = @"latest-stories-query";
  FIRFirestore *firestore = [FIRFirestore firestore];
  NSURL *bundleURL = [NSURL URLWithString:@"https://example.com/createBundle"];
  [self loadQueryNamed:queryName
   fromRemoteBundleURL:bundleURL
         withFirestore:firestore
            completion:^(FIRQuery *query, NSError *error) {
    // Handle query results
  }];
}

Kotlin+KTX

@Throws(IOException::class)
fun getBundleStream(urlString: String?): InputStream {
    val url = URL(urlString)
    val connection = url.openConnection() as HttpURLConnection
    return connection.inputStream
}

@Throws(IOException::class)
fun fetchFromBundle() {
    val bundleStream = getBundleStream("https://example.com/createBundle")
    val loadTask = db.loadBundle(bundleStream)

    // Chain the following tasks
    // 1) Load the bundle
    // 2) Get the named query from the local cache
    // 3) Execute a get() on the named query
    loadTask.continueWithTask<Query> { task ->
        // Close the stream
        bundleStream.close()

        // Calling .result propagates errors
        val progress = task.getResult(Exception::class.java)

        // Get the named query from the bundle cache
        db.getNamedQuery("latest-stories-query")
    }.continueWithTask { task ->
        val query = task.getResult(Exception::class.java)!!

        // get() the query results from the cache
        query.get(Source.CACHE)
    }.addOnCompleteListener { task ->
        if (!task.isSuccessful) {
            Log.w(TAG, "Bundle loading failed", task.exception)
            return@addOnCompleteListener
        }

        // Get the QuerySnapshot from the bundle
        val storiesSnap = task.result

        // Use the results
        // ...
    }
}

Java

public InputStream getBundleStream(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    return connection.getInputStream();
}

public void fetchBundleFrom() throws IOException {
    final InputStream bundleStream = getBundleStream("https://example.com/createBundle");
    LoadBundleTask loadTask = db.loadBundle(bundleStream);

    // Chain the following tasks
    // 1) Load the bundle
    // 2) Get the named query from the local cache
    // 3) Execute a get() on the named query
    loadTask.continueWithTask(new Continuation<LoadBundleTaskProgress, Task<Query>>() {
        @Override
        public Task<Query> then(@NonNull Task<LoadBundleTaskProgress> task) throws Exception {
            // Close the stream
            bundleStream.close();

            // Calling getResult() propagates errors
            LoadBundleTaskProgress progress = task.getResult(Exception.class);

            // Get the named query from the bundle cache
            return db.getNamedQuery("latest-stories-query");
        }
    }).continueWithTask(new Continuation<Query, Task<QuerySnapshot>>() {
        @Override
        public Task<QuerySnapshot> then(@NonNull Task<Query> task) throws Exception {
            Query query = task.getResult(Exception.class);

            // get() the query results from the cache
            return query.get(Source.CACHE);
        }
    }).addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (!task.isSuccessful()) {
                Log.w(TAG, "Bundle loading failed", task.getException());
                return;
            }

            // Get the QuerySnapshot from the bundle
            QuerySnapshot storiesSnap = task.getResult();

            // Use the results
            // ...
        }
    });
}
C++‎
db->LoadBundle("bundle_name", [](const LoadBundleTaskProgress& progress) {
  switch(progress.state()) {
    case LoadBundleTaskProgress::State::kError: {
      // The bundle load has errored. Handle the error in the returned future.
      return;
    }
    case LoadBundleTaskProgress::State::kInProgress: {
      std::cout << "Bytes loaded from bundle: " << progress.bytes_loaded()
                << std::endl;
      break;
    }
    case LoadBundleTaskProgress::State::kSuccess: {
      std::cout << "Bundle load succeeeded" << std::endl;
      break;
    }
  }
}).OnCompletion([db](const Future<LoadBundleTaskProgress>& future) {
  if (future.error() != Error::kErrorOk) {
    // Handle error...
    return;
  }

  const std::string& query_name = "latest_stories_query";
  db->NamedQuery(query_name).OnCompletion([](const Future<Query>& query_future){
    if (query_future.error() != Error::kErrorOk) {
      // Handle error...
      return;
    }

    const Query* query = query_future.result();
    query->Get().OnCompletion([](const Future<QuerySnapshot> &){
      // ...
    });
  });
});

يُرجى العِلم أنّه في حال تحميل طلب مُسمّى من حزمة تم إنشاؤها في أقل من 30 دقيقة سابقًا، بمجرد استخدامه للقراءة من الواجهة الخلفية بدلاً من ذاكرة التخزين المؤقت، سوف تدفع فقط مقابل قراءات قاعدة البيانات اللازمة لتحديث الوثائق لمطابقة ما هو المخزنة في الخلفية؛ أي أنك تدفع مقابل عمليات دلتا فقط.

ما هي الخطوات التالية؟