What could be causing this Cloud Function to be triggered multiple times by an Android HTTP request?

A scenario in my Android app involves sending a POST request to an HTTP triggered Cloud Function. The issue arises when Firebase registers the event twice on the Firebase console even though the function is called only once. I have ensured that the button triggering the message send disappears after the first click, eliminating the possibility of accidental double clicks. Despite my limited knowledge of Firebase and unsuccessful attempts at finding relevant documentation or similar queries, I am seeking assistance from experts in this community.

Below is the method responsible for sending a message to my FCM cloud function:

public  void sendPushToSingleInstance(final Context activity, final String message, final String myId, final String theirId) {

    final String url = URL_TO_CLOUD_FUNCTION;

    StringRequest myReq = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(activity, "Success", Toast.LENGTH_SHORT).show();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (error.networkResponse != null)
                        Toast.makeText(activity, String.valueOf(error.networkResponse.statusCode), Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(activity, "some error", Toast.LENGTH_SHORT).show();
                }
            }) {
            
        // Request body implementation

        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        // Header details

        public byte[] getBody() throws com.android.volley.AuthFailureError {
            Map<String, String> rawParameters = new Hashtable<String, String>();

            return new JSONObject(rawParameters).toString().getBytes();
        };

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();

            headers.put("from", myId);
            headers.put("message", message);
            headers.put("sendingTo", theirId);

            return headers;
        }
    };

    Volley.newRequestQueue(activity).add(myReq);
}

To elaborate further, my JavaScript intercepts the HTTP request, segments it, and transmits the message to a topic corresponding to the other user's id rather than targeting a specific device. Below is the JavaScript snippet for my Cloud Function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendMessage = functions.https.onRequest((request, response) => {

    var topicId = request.get('sendingTo');
    var color = request.get('color');
    var from = request.get('from')

    console.log('tried to push notification');

    const payload = {
        notification: {
            title: from,
            body: color,
            sound: "default"
        },

    };

    const options = {
        priority: "high",
        timeToLive: 60 * 60 * 24
    };

    admin.messaging().sendToTopic(topicId, payload, options);
});

The logs presented below indicate the repeated invocation of the function: firebase console logs Fueling my quest for answers, I have referred to resources such as: https://firebase.google.com/docs/functions/http-events

In addition, I have scoured multiple StackOverflow discussions without encountering any users facing a similar dilemma. Any insights you could provide would be greatly appreciated.

Answer №1

Quoting @mohamadrabee, they mentioned in the documentation that it's crucial to always end an HTTP function with send(), redirect(), or end(). If you fail to do so, your function might continue running and get forcibly terminated by the system. Check out firebase.google.com/docs/functions/http-events for more details.

To address this issue, I included:

response.end();

right after the line:

admin.messaging().sendToTopic(topicId, payload, options);

A notable update: Even after implementing the above code snippet, I encountered the problem about 7% of the time. To resolve this, I had to modify response.end(); as follows:

if (response.status(200)) {
    response.status(200).end(); 
} else {
    response.end();
}

Ever since making this adjustment, I have not faced any further issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for generating a PDF file using XSL and Java programming?

It seems like in order to convert my XML files to PDF, I will need to utilize an XSLFO stylesheet document. Additionally, I would have to employ Java's Transform API to execute the conversion process. ...

Managing the entire minification and obfuscation process: Best practices and tips

I am working on deploying my AngularJS application and have discovered the importance of minifying/uglifying my javascript files for production. There are various methods to achieve this, such as using grunt. However, I am still unclear about... After m ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Updating an HTML input field property with JavaScript is not reflecting the changes

I am currently working on a form with two fields: stationery type and stationery request quantity. The stationery request quantity field only accepts numerical input. The minimum quantity that can be entered in this field depends on the value selected in t ...

How to export HTML table information to Excel using JQuery and display a Save As dialog box

This script has been an absolute lifesaver for my web application. Huge thanks to sampopes for providing the solution on this specific thread. function exportToExcel() { var tab_text="<table border='2px'><tr bgcolor='#87AFC6& ...

Tips for displaying specific HTML elements in AngularJS using ng-repeat and ng-if

I am working with some bootstrap HTML code that includes an ng-repeat function. <div class="row"> <div class="col-lg-4" ng-repeat="p in persons"> <img class="img-circle" src="images/{{ p.image }}" width="140" height="140"> < ...

What is the easiest way to check the left/right audio balance on my device?

Is there a way to programmatically detect the current device's audio balance? On Android 10 - the setting that I'm trying to detect can be found under: Settings -> Accessibility -> Audio & On-Screen Text -> Audio balance More in ...

Where is the best place for these Sequelize methods to be located?

You are faced with 2 tables: Individuals Financial Accounts An individual can be connected to multiple financial accounts. To attach a new account to an individual, you can utilize Sequelize by adding an instance method called addAccount() to the Indiv ...

Receiving an error message of ".then is not a function" while using Inquirer

I am encountering an issue with a basic function I am trying to run using Node.js and inquirer. When I attempt to execute it, the console log shows me the error message: "TypeError: inquirer.createPromptModule(...).then is not a function." Although I have ...

Arrange the objects in the array according to the specified items that should come after

Consider the following data structure: var set = [ { "name":"alpha", "require":[] }, { "name":"beta", "require":["echo"] }, { "name":"charlie", "require":[] }, { "name":"d ...

axios encountered a JSON parsing issue due to an unexpected character in the server's response

I'm encountering an issue with JSON parsing as I attempt to retrieve data from a server endpoint. This is the first instance where Axios is unable to automatically decode the JSON response. Upon inspecting my code, I noticed that Axios is detecting ...

Tips for properly invoking an asynchronous function on every rerender of a component in Vue.js

Situation: An analysis module on a website that needs to display three different data tables, one at a time. Approach: The module is a component containing three buttons. Each button sets a variable which determines which table to render. Depending on the ...

What are the benefits of creating multiple DTOs for a single model?

Imagine I have a class called User with various fields: public class User { public Integer id; public String name; public String username; public Integer age; public Address address; public String phoneNumber; public String emai ...

What is the reason for setters being overridden rather than invoked when utilized in web components?

I am delving into the realm of creating custom tables using web components, and I'm exploring how to define properties on my custom elements using getters and setters. Here is a simple table with one column and a custom row element that includes a lin ...

Access PHP variables in JavaScript

In my project, I have a file named english.php which holds various variable values stored in the $LANG array. For example: $LANG['value_1']="abc"; $LANG['value_2']="xyz"; In addition to numerous .php files that include require_once( ...

Error: Unable to convert value to a string in Mongoose Schema

Hey everyone, I'm facing an issue while trying to send an array of strings with Mongoose Schema. It works fine for the tags but not for the selectedFile... Mongoose Schema: import mongoose from "mongoose"; const postSchema = mongoose.Schem ...

a popup window that appears upon clicking a linked button

<td colspan ="2" style="width: 64px"> <div style="float:left; padding-left:9px;"> <asp:LinkButton ID="lnkremoveloc" runat="server" OnClick="lnkremoveloc_Click" CssClass="linkclass" style="cursor:pointer" ...

Accessing packet data details in JavaScript

I am curious about the feasibility of a certain task. Essentially, I am interested in executing JavaScript code on the client side while simultaneously sending an AJAX request to my server to perform specific actions and then receive information back fro ...

Navigate to the Bootstrap Panel body when the relevant link is clicked

I am facing an issue with a long list of panels that are tedious to scroll through. To make navigation easier, I am attempting to create a shortcut link at the top of the page. Below is the code for the shortcut: <a data-toggle="collapse" data-parent ...

A guide to extracting functions from a `v-for` loop in a table

Beginner here. I am attempting to create a dropdown menu for the div with an id matching my specific name. For instance, let's say my table column names are: A, B, C. I only want to have a dropdown menu for column A. The template of my table looks ...