0Pricing
Firebase Auth & Realtime Database Apps · درس

العدادات الذرية وقوائم الانتظار

أنشئ عدادات ذرية موثوقة ونفّذ قوائم رسائل باستخدام Realtime Database لبناء منطق تطبيق متين

العدادات الذرية وقوائم الانتظار درس مجاني في Firebase Auth & Realtime Database Apps على CoddyKit. هذا هو الدرس 3 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Firebase Auth & Realtime Database Apps، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Firebase Auth & Realtime Database Apps 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Why Atomic Operations Matter

In real-time applications, multiple users might try to update the same piece of data simultaneously. This can lead to what's called a race condition.

  • Imagine two users liking a post at the exact same moment.
  • Without proper handling, one 'like' might overwrite the other.
  • This results in incorrect data, like a post showing 10 likes when it should have 11.

Atomic operations ensure that data updates are performed as a single, indivisible unit, preventing such issues.

Understanding Atomic Counters

An atomic counter is a numerical value that can be incremented or decremented reliably, even when multiple clients try to modify it at the same time.

It's crucial for features like:

  • Counting 'likes' or 'upvotes' on content.
  • Tracking page views or downloads.
  • Managing inventory levels in an e-commerce app.

Firebase Realtime Database provides a powerful mechanism to implement these safely.

Implementing with Transactions

Firebase's transaction() method is key to creating atomic operations. It ensures that an update function is executed on the most current data, even if other writes occur concurrently.

  • Your update function receives the current data.
  • It returns the new value you want to write.
  • Firebase automatically retries the transaction if the data changes during the process.

This guarantees that your counter updates are always based on the latest state.

Code: Simple Atomic Counter

Here's how to increment a counter atomically using a transaction. This example simulates the Firebase transaction logic.

class MockRef {
  constructor(value) {
    this.value = value;
  }
  async transaction(updateFunction) {
    const currentValue = this.value;
    const newValue = updateFunction(currentValue);
    if (newValue !== undefined) {
      this.value = newValue;
      console.log(`Counter updated to: ${this.value}`);
      return { committed: true, snapshot: { val: () => this.value } };
    }
    return { committed: false };
  }
  val() { return this.value; }
}

async function main() {
  const counterRef = new MockRef(0);
  console.log("Initial count:", counterRef.val());

  // Attempt to increment the counter
  await counterRef.transaction(currentCount => {
    return (currentCount || 0) + 1;
  });

  console.log("Final count (after one increment):");
  console.log(counterRef.val());
}

main();

Transaction Logic Explained

In the transaction() method, the callback function receives the currentCount. If the counter doesn't exist (null), it defaults to 0 before incrementing.

  • Returning undefined from the callback aborts the transaction.
  • Returning any other value (like the incremented count) commits the transaction.
  • Firebase handles retries automatically if the data changes while the transaction is running.

This ensures the final count is always accurate, even under heavy load.

Introducing Message Queues

A message queue is a way for different parts of an application (or different applications) to communicate asynchronously. It's like a to-do list for tasks that don't need immediate processing.

Key benefits include:

  • Decoupling: Senders don't wait for receivers.
  • Reliability: Tasks are stored until processed.
  • Scalability: Easily add more workers to process tasks.

Firebase Realtime Database can serve as a simple, effective message queue.

Building a Simple Queue

To build a queue with Realtime Database, you typically create a list of tasks. New tasks are pushed to this list, and worker processes consume them.

  • Each task is an object with relevant data (e.g., action, payload).
  • Using push() creates unique, time-ordered keys, perfect for a queue.
  • Workers listen for new items and process the oldest ones first.

This structure allows for robust background task management.

Code: Adding to a Queue

Adding tasks to a queue is straightforward using Firebase's push() method. Each new item gets a unique key.

class MockDatabase {
  constructor() {
    this.data = {};
  }
  ref(path) {
    return {
      push: (value) => {
        const key = `item_${Object.keys(this.data[path] || {}).length}_${Date.now()}`;
        if (!this.data[path]) {
          this.data[path] = {};
        }
        this.data[path][key] = value;
        console.log(`Added to ${path}: ${JSON.stringify(value)}`);
        return { key: key };
      },
      val: () => this.data[path]
    };
  }
}

async function main() {
  const mockDb = new MockDatabase();
  const queueRef = mockDb.ref("tasks");

  console.log("Adding tasks to the queue...");
  await queueRef.push({ action: "sendEmail", userId: "user123" });
  await queueRef.push({ action: "generateReport", reportId: "rpt456" });

  console.log("\nCurrent queue items:");
  console.log(JSON.stringify(queueRef.val(), null, 2));
}

main();

Code: Processing from a Queue

To process tasks reliably, you need to ensure only one worker processes a given task. This involves fetching the oldest task and then atomically removing it or marking it as 'processed' using a transaction.

class MockDatabase {
  constructor(initialData = {}) {
    this.data = initialData;
  }
  ref(path) {
    const self = this;
    return {
      orderByChild: (child) => ({ limitToFirst: (count) => ({ once: async (eventType) => {
        if (eventType === 'value') {
          const items = Object.entries(self.data[path] || {})
            .map(([key, value]) => ({ key, value }))
            .sort((a, b) => (a.value[child] || 0) - (b.value[child] || 0));
          const result = {};
          items.slice(0, count).forEach(item => { result[item.key] = item.value; });
          return { val: () => result };
        }
      }}) }),
      child: (key) => ({ transaction: async (updateFunction) => {
        const currentValue = self.data[path] ? self.data[path][key] : null;
        const newValue = updateFunction(currentValue);
        if (newValue === null) {
          delete self.data[path][key];
          console.log(`Transaction removed item: ${key}`);
          return { committed: true, snapshot: { val: () => null } };
        } else if (newValue !== undefined) {
          if (!self.data[path]) self.data[path] = {};
          self.data[path][key] = newValue;
          console.log(`Transaction updated item: ${key}`);
          return { committed: true, snapshot: { val: () => newValue } };
        }
        return { committed: false, snapshot: { val: () => currentValue } };
      }}),
      val: () => self.data[path]
    };
  }
}

async function main() {
  const initialTasks = {
    "task_A": { action: "sendEmail", userId: "user123", timestamp: 1678888000000 },
    "task_B": { action: "generateReport", reportId: "rpt456", timestamp: 1678888010000 }
  };
  const mockDb = new MockDatabase({ tasks: initialTasks });
  const queueRef = mockDb.ref("tasks");

  console.log("Initial queue items:", JSON.stringify(queueRef.val(), null, 2));

  const snapshot = await queueRef.orderByChild('timestamp').limitToFirst(1).once('value');
  const firstItem = snapshot.val();

  if (firstItem) {
    const firstKey = Object.keys(firstItem)[0];
    console.log(`Attempting to process task with key ${firstKey}`);
    const transactionResult = await queueRef.child(firstKey).transaction(currentData => {
      return currentData ? null : undefined; // Delete if exists, abort if not
    });

    if (transactionResult.committed) {
      console.log(`Successfully processed and removed task: ${firstKey}`);
    } else {
      console.log("Failed to process task (already processed or aborted).");
    }
  }
  console.log("\nQueue items after processing:");
  console.log(JSON.stringify(queueRef.val(), null, 2));
}

main();

Choosing Between Counters & Queues

While both atomic counters and queues leverage Firebase transactions, they solve different problems:

  • Atomic Counters: For simple, numerical updates that need to be highly consistent (e.g., vote counts, inventory).
  • Message Queues: For decoupling tasks, handling background processes, and ensuring reliable execution of jobs that can be processed later.

Understanding these patterns allows you to build more robust and scalable real-time applications.

Quick Check: Atomic Operations

You want to reliably increment a user's 'score' in your game, ensuring that simultaneous updates from different devices don't lead to lost increments. Which Firebase Realtime Database feature is most appropriate?

Recap: Atomic Counters & Queues

We've explored how Firebase Realtime Database enables robust application logic through atomic operations.

  • Atomic counters use transaction() to reliably increment/decrement numerical values, preventing race conditions.
  • Message queues leverage push() for adding tasks and transaction() for atomically processing (claiming/removing) the oldest tasks, enabling asynchronous and scalable background processing.

Mastering these patterns is crucial for building high-performance, consistent, and scalable real-time applications.

الأسئلة الشائعة

هل درس «العدادات الذرية وقوائم الانتظار» مجاني؟

نعم — نص درس «العدادات الذرية وقوائم الانتظار» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Firebase Auth & Realtime Database Apps، انتقل إلى CoddyKit PRO. تتضمن دورة Firebase Auth & Realtime Database Apps 4 دروس في المجموع.

ماذا ستتعلم في «العدادات الذرية وقوائم الانتظار»؟

أنشئ عدادات ذرية موثوقة ونفّذ قوائم رسائل باستخدام Realtime Database لبناء منطق تطبيق متين تتمرن على Firebase Auth & Realtime Database Apps مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Firebase Auth & Realtime Database Apps؟

لا تُشترط خبرة سابقة. Firebase Auth & Realtime Database Apps على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 4.

كم من الوقت يستغرق درس «العدادات الذرية وقوائم الانتظار»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Firebase Auth & Realtime Database Apps هذا؟

نعم. كل درس في Firebase Auth & Realtime Database Apps يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. تحديثات Fan-Out للبيانات
  2. عمليات البيانات بالمعاملات
  3. العدادات الذرية وقوائم الانتظار
  4. استراتيجيات إلغاء التطبيع وتكرار البيانات
← العودة إلى Firebase Auth & Realtime Database Apps