Saturday, 21 January 2023

What would happen to concurrent requests using this security rule?

I have a set of items in the real time database:

items
|
|-------item_id_1
       
        -name:
        -color:
        -type:

Another node is the my_items node, looks like this:

my_items
|
|-------user_id_1
        |         
        |-------item_id_2
                
                -name:
                -color:
                -type:

I have this function that does a multi-path update, this function deletes an item from items and adds it to the user's my_items:

private void getItem(String uid, String item_key) {

Map<String, Object> updates = new HashMap<>();

//delete item
updates.put("items/" + item_key, null);

//give the item to the user
updates.put("my_items/" + uid + "/" + item_key, itemObject);


mDatabaseReference.updateChildren(updates);


}

If this is the security rule for the my_items node. Which means you can't write the item to the user if it doesn't exist in items node:

{

"my_items":{

     "$user_id":{

         "$item_id":{

           ".write" : "auth.uid == $user_id && root.child('items').child($item_id).exists()"

        }
     }
}
}

Question:

  • Knowing that Firebase Database handles requests one by one.

If users A,B,C,D called the getItem(..) function for the same item id together at the same time:

Does this means that if the first request to be processed by the database succeeds all other must fail (According to my security rule above) ?

Example:

  1. A request reached the server first: Succeeds

(now the item was deleted from items and added to user A)

  1. B: Fails

(because the item no longer exists in items, so security rule prevents this)

  1. C: Fails

(same reason)

  1. D: Fails

(same reason)

Is this what should happen ? Or something else ?

Thanks.



from What would happen to concurrent requests using this security rule?

No comments:

Post a Comment