ক্লাউড ফায়ারস্টোর ডেটা বান্ডিল

ক্লাউড ফায়ারস্টোর ডেটা বান্ডেলগুলি হল স্ট্যাটিক ডেটা ফাইল যা আপনি ক্লাউড ফায়ারস্টোর ডকুমেন্ট এবং ক্যোয়ারী স্ন্যাপশট থেকে তৈরি করেছেন এবং আপনার দ্বারা CDN, হোস্টিং পরিষেবা বা অন্য সমাধানে প্রকাশিত হয়েছে৷ ডেটা বান্ডেলগুলিতে আপনি আপনার ক্লায়েন্ট অ্যাপগুলিকে যে নথিগুলি সরবরাহ করতে চান এবং সেগুলি তৈরি করা প্রশ্নের সম্পর্কে মেটাডেটা উভয়ই অন্তর্ভুক্ত করে৷ আপনি নেটওয়ার্কে বা স্থানীয় স্টোরেজ থেকে বান্ডিল ডাউনলোড করতে ক্লায়েন্ট SDK ব্যবহার করেন, তারপরে আপনি ক্লাউড ফায়ারস্টোর স্থানীয় ক্যাশে বান্ডিল ডেটা লোড করেন। একবার একটি বান্ডেল লোড হয়ে গেলে, একটি ক্লায়েন্ট অ্যাপ স্থানীয় ক্যাশে বা ব্যাকএন্ড থেকে নথি অনুসন্ধান করতে পারে।

ডেটা বান্ডেলের সাহায্যে, আপনার অ্যাপগুলি শীঘ্রই সাধারণ প্রশ্নের ফলাফলগুলি লোড করতে পারে, যেহেতু ক্লাউড ফায়ারস্টোর ব্যাকএন্ডে কল করার প্রয়োজন ছাড়াই স্টার্ট-আপে নথিগুলি পাওয়া যায়৷ স্থানীয় ক্যাশে থেকে ফলাফল লোড করা হলে, আপনি হ্রাস অ্যাক্সেস খরচ থেকেও উপকৃত হবেন। একই প্রারম্ভিক 100টি নথির জন্য একটি মিলিয়ন অ্যাপ ইন্সট্যান্সের জন্য অর্থপ্রদান করার পরিবর্তে, আপনি শুধুমাত্র সেই 100টি নথি বান্ডিল করার জন্য প্রয়োজনীয় প্রশ্নের জন্য অর্থ প্রদান করবেন৷

ক্লাউড ফায়ারস্টোর ডেটা বান্ডেলগুলি অন্যান্য ফায়ারবেস ব্যাকএন্ড পণ্যগুলির সাথে ভালভাবে কাজ করার জন্য তৈরি করা হয়েছে৷ একটি সমন্বিত সমাধান দেখুন যেখানে বান্ডেলগুলি ক্লাউড ফাংশন দ্বারা তৈরি করা হয় এবং Firebase হোস্টিং সহ ব্যবহারকারীদের পরিবেশন করা হয়।

আপনার অ্যাপের সাথে একটি বান্ডিল ব্যবহার করার জন্য তিনটি ধাপ জড়িত:

  1. অ্যাডমিন SDK-এর সাথে বান্ডিল তৈরি করা
  2. স্থানীয় স্টোরেজ বা CDN থেকে বান্ডিল পরিবেশন করা
  3. ক্লায়েন্টে বান্ডিল লোড হচ্ছে

একটি ডেটা বান্ডেল কি?

একটি ডেটা বান্ডেল হল একটি স্ট্যাটিক বাইনারি ফাইল যা আপনি এক বা একাধিক নথি এবং/অথবা কোয়েরি স্ন্যাপশট প্যাকেজ করার জন্য তৈরি করেছেন এবং যেখান থেকে আপনি নামযুক্ত প্রশ্নগুলি বের করতে পারেন। যেমন আমরা নীচে আলোচনা করছি, সার্ভার-সাইড SDKগুলি আপনাকে বান্ডিল তৈরি করতে দেয় এবং ক্লায়েন্ট SDKগুলি আপনাকে স্থানীয় ক্যাশে বান্ডিলগুলি লোড করতে দেওয়ার পদ্ধতিগুলি সরবরাহ করে৷

নামযুক্ত প্রশ্নগুলি বান্ডিলের একটি বিশেষ শক্তিশালী বৈশিষ্ট্য। নামযুক্ত ক্যোয়ারীগুলি হল Query অবজেক্ট যা আপনি একটি বান্ডেল থেকে বের করতে পারেন, তারপর ক্যাশে বা ব্যাকএন্ড থেকে ডেটা অনুসন্ধান করতে অবিলম্বে ব্যবহার করুন, যেমন আপনি সাধারণত আপনার অ্যাপের যেকোনো অংশে করেন যা ক্লাউড ফায়ারস্টোরের সাথে কথা বলে।

সার্ভারে ডেটা বান্ডিল তৈরি করা

Node.js বা Java Admin SDK ব্যবহার করলে আপনি বান্ডেলগুলিতে কী অন্তর্ভুক্ত করবেন এবং কীভাবে সেগুলি পরিবেশন করবেন তার উপর সম্পূর্ণ নিয়ন্ত্রণ দেয়৷

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();
      
পাইথন
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 থেকে বা ক্লাউড স্টোরেজ থেকে ডাউনলোড করে আপনার ক্লায়েন্ট অ্যাপে বান্ডিল পরিবেশন করতে পারেন।

অনুমান করুন পূর্ববর্তী বিভাগে তৈরি বান্ডেলটি 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 অনুরোধ করে, একটি স্টোরেজ API কল করে বা একটি নেটওয়ার্কে বাইনারি ফাইলগুলি আনার জন্য অন্য কোনো কৌশল ব্যবহার করে।

একবার আনা হলে, ক্লাউড ফায়ারস্টোর ক্লায়েন্ট SDK ব্যবহার করে, আপনার অ্যাপটি loadBundle পদ্ধতিতে কল করে, যা একটি টাস্ক ট্র্যাকিং অবজেক্ট রিটার্ন করে, যার সমাপ্তিটি আপনি একটি প্রতিশ্রুতির স্থিতি নিরীক্ষণের মতোই নিরীক্ষণ করতে পারেন। সফল বান্ডেল লোডিং টাস্ক সমাপ্তিতে, বান্ডেল বিষয়বস্তু স্থানীয় ক্যাশে উপলব্ধ।

Web modular API

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 namespaced API

// 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
  // ...
}
সুইফট
দ্রষ্টব্য: এই পণ্যটি watchOS এবং অ্যাপ ক্লিপ লক্ষ্যে উপলব্ধ নয়।
// 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)
  }
}
উদ্দেশ্য গ
দ্রষ্টব্য: এই পণ্যটি watchOS এবং অ্যাপ ক্লিপ লক্ষ্যে উপলব্ধ নয়।
// 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
            // ...
        }
    });
}
সি++
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 মিনিটেরও কম আগে নির্মিত একটি বান্ডিল থেকে একটি নামযুক্ত ক্যোয়ারী লোড করেন, একবার আপনি এটিকে ক্যাশের পরিবর্তে ব্যাকএন্ড থেকে পড়ার জন্য ব্যবহার করেন, তাহলে আপনি ব্যাকএন্ডে যা সংরক্ষিত আছে তার সাথে মেলে ডকুমেন্ট আপডেট করার জন্য প্রয়োজনীয় ডাটাবেস পড়ার জন্য অর্থ প্রদান করবেন। ; অর্থাৎ, আপনি শুধুমাত্র ডেল্টাগুলির জন্য অর্থ প্রদান করেন।

এরপর কী?