Cloud Firestore ডেটা বান্ডেল হলো স্ট্যাটিক ডেটা ফাইল, যা আপনি Cloud Firestore ডকুমেন্ট এবং কোয়েরি স্ন্যাপশট থেকে তৈরি করেন এবং একটি সিডিএন, হোস্টিং পরিষেবা বা অন্য কোনো সলিউশনে প্রকাশ করেন। ডেটা বান্ডেলে আপনার ক্লায়েন্ট অ্যাপগুলোকে সরবরাহ করতে চাওয়া ডকুমেন্ট এবং যে কোয়েরিগুলো সেগুলোকে তৈরি করেছে, সেগুলোর মেটাডেটা উভয়ই অন্তর্ভুক্ত থাকে। আপনি ক্লায়েন্ট এসডিকে ব্যবহার করে নেটওয়ার্কের মাধ্যমে বা লোকাল স্টোরেজ থেকে বান্ডেল ডাউনলোড করেন, যার পরে আপনি বান্ডেলের ডেটা Cloud Firestore লোকাল ক্যাশে লোড করেন। একবার একটি বান্ডেল লোড হয়ে গেলে, একটি ক্লায়েন্ট অ্যাপ লোকাল ক্যাশে বা ব্যাকএন্ড থেকে ডকুমেন্ট কোয়েরি করতে পারে।
ডেটা বান্ডেলের সাহায্যে আপনার অ্যাপগুলো সাধারণ কোয়েরিগুলোর ফলাফল আরও দ্রুত লোড করতে পারে, কারণ Cloud Firestore ব্যাকএন্ডে কল করার প্রয়োজন ছাড়াই অ্যাপ চালু হওয়ার সাথে সাথেই ডকুমেন্টগুলো পাওয়া যায়। যদি ফলাফল লোকাল ক্যাশ থেকে লোড করা হয়, তাহলে আপনার অ্যাক্সেস খরচও কমে যায়। একই প্রাথমিক ১০০টি ডকুমেন্ট কোয়েরি করার জন্য দশ লক্ষ অ্যাপ ইনস্ট্যান্সের খরচ দেওয়ার পরিবর্তে, আপনি শুধুমাত্র সেই ১০০টি ডকুমেন্ট বান্ডেল করার জন্য প্রয়োজনীয় কোয়েরিগুলোর খরচ দেন।
Cloud Firestore ডেটা বান্ডেলগুলো অন্যান্য ফায়ারবেস ব্যাকএন্ড প্রোডাক্টের সাথে ভালোভাবে কাজ করার জন্য তৈরি করা হয়েছে। এমন একটি সমন্বিত সমাধান দেখুন যেখানে Cloud Functions দ্বারা বান্ডেলগুলো তৈরি করা হয় এবং Firebase Hosting এর মাধ্যমে ব্যবহারকারীদের কাছে পরিবেশন করা হয়।
আপনার অ্যাপের সাথে একটি বান্ডেল ব্যবহার করতে তিনটি ধাপ অনুসরণ করতে হয়:
- অ্যাডমিন এসডিকে দিয়ে বান্ডেলটি তৈরি করা
- বান্ডেলটি স্থানীয় স্টোরেজ থেকে অথবা একটি CDN থেকে পরিবেশন করা হচ্ছে
- ক্লায়েন্টে বান্ডেল লোড করা হচ্ছে
ডেটা বান্ডেল বলতে কী বোঝায়?
ডেটা বান্ডেল হলো একটি স্ট্যাটিক বাইনারি ফাইল, যা আপনি এক বা একাধিক ডকুমেন্ট এবং/অথবা কোয়েরি স্ন্যাপশট প্যাকেজ করার জন্য তৈরি করেন এবং যেখান থেকে আপনি নামযুক্ত কোয়েরিগুলো নিষ্কাশন করতে পারেন। আমরা নিচে যেমন আলোচনা করব, সার্ভার-সাইড SDK-গুলো আপনাকে বান্ডেল তৈরি করতে দেয় এবং ক্লায়েন্ট SDK-গুলো স্থানীয় ক্যাশে বান্ডেল লোড করার জন্য মেথড সরবরাহ করে।
নেমড কোয়েরি হলো বান্ডেলের একটি বিশেষভাবে শক্তিশালী বৈশিষ্ট্য। নেমড কোয়েরি হলো Query অবজেক্ট, যা আপনি একটি বান্ডেল থেকে এক্সট্র্যাক্ট করে সাথে সাথেই ক্যাশে অথবা ব্যাকএন্ড থেকে ডেটা কোয়েরি করতে ব্যবহার করতে পারেন; ঠিক যেমনটি আপনি আপনার অ্যাপের যেকোনো অংশে Cloud Firestore সাথে সংযোগ স্থাপনের জন্য সাধারণত করে থাকেন।
সার্ভারে ডেটা বান্ডেল তৈরি করা হচ্ছে
Node.js বা Java অ্যাডমিন SDK ব্যবহার করে বান্ডেলগুলোতে কী অন্তর্ভুক্ত করতে হবে এবং কীভাবে সেগুলো পরিবেশন করতে হবে, তার ওপর আপনি সম্পূর্ণ নিয়ন্ত্রণ পান।
নোড.জেএস
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();
পাইথন
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);
ক্লায়েন্টে ডেটা বান্ডেল লোড করা হচ্ছে
আপনি একটি রিমোট সার্ভার থেকে ফায়ারস্টোর বান্ডেলগুলি লোড করেন, তা HTTP অনুরোধ করে, স্টোরেজ API কল করে বা নেটওয়ার্কে বাইনারি ফাইল আনার অন্য কোনো কৌশল ব্যবহার করেই হোক না কেন।
Cloud Firestore ক্লায়েন্ট SDK ব্যবহার করে বান্ডেলটি আনার পর, আপনার অ্যাপ ` loadBundle মেথডটি কল করে, যা একটি টাস্ক ট্র্যাকিং অবজেক্ট রিটার্ন করে। এই অবজেক্টটির সমাপ্তি আপনি একটি `Promise`-এর স্ট্যাটাস পর্যবেক্ষণের মতোই নিরীক্ষণ করতে পারেন। বান্ডেল লোডিং টাস্কটি সফলভাবে সম্পন্ন হলে, বান্ডেলের বিষয়বস্তু স্থানীয় ক্যাশে উপলব্ধ হয়।
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 // ... }
সুইফট
// 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) } }
উদ্দেশ্য-সি
// 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
@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 // ... } }); }
Dart
// Get a bundle from a server final url = Uri.https('example.com', '/create-bundle'); final response = await http.get(url); String body = response.body; final buffer = Uint8List.fromList(body.codeUnits); // Load a bundle from a buffer LoadBundleTask task = FirebaseFirestore.instance.loadBundle(buffer); await task.stream.toList(); // Use the cached named query final results = await FirebaseFirestore.instance.namedQueryGet( "latest-stories-query", options: const GetOptions( source: Source.cache, ), );
সি++
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> &){ // ... }); }); });
মনে রাখবেন যে, যদি আপনি ৩০ মিনিটেরও কম সময় আগে তৈরি করা কোনো বান্ডেল থেকে একটি নেমড কোয়েরি লোড করেন, এবং ক্যাশের পরিবর্তে ব্যাকএন্ড থেকে ডেটা পড়ার জন্য এটি ব্যবহার করেন, তাহলে আপনাকে শুধুমাত্র ব্যাকএন্ডে সংরক্ষিত তথ্যের সাথে ডকুমেন্টগুলো মেলানোর জন্য প্রয়োজনীয় ডাটাবেস রিডের খরচই বহন করতে হবে; অর্থাৎ, আপনাকে কেবল ডেটার পার্থক্যের (ডেল্টা) জন্যই অর্থ প্রদান করতে হবে।
এরপর কী?
ক্লায়েন্ট সাইড ( Apple , Android , web ) এবং সার্ভার সাইডের ( Node.js ) জন্য ডেটা বান্ডেল API রেফারেন্স ডকুমেন্টেশন দেখুন।
যদি আপনি ইতিমধ্যে তা না করে থাকেন, তাহলে বান্ডেল তৈরি ও পরিবেশনের জন্য Cloud Functions এবং Firebase Hosting সমাধানটি দেখে নিন।