Search code examples
jsonfirebasegoogle-cloud-functionsgoogle-cloud-pubsub

JSON parsing error in Firebase PubSub function when publishing message with gcloud CLI on Windows


I'm trying to set up a billing PubSub listener in cloud functions to cap billing and prevent unexpected costs. I had a look at the youtube series, but started implementing it using v2 as outlined here. I've been sending a sample JSON using the google cloud CLI (on Windows) and have been encountering this really annoying JSON parsing error. Here's my command, cloud function, and error (from cloud function's logs), respectively:

Command:

gcloud pubsub topics publish billing --message '{"budgetDisplayName":"name-of-budget","alertThresholdExceeded":1,"costAmount":100.01,"costIntervalStart":"2019-01-01T00:00:00Z","budgetAmount":100,"budgetAmountType":"SPECIFIED_AMOUNT","currencyCode":"USD"}'

Cloud Function:

import { onMessagePublished } from "firebase-functions/v2/pubsub";
import * as logger from "firebase-functions/logger";
exports.onBillingAlert = onMessagePublished(
  "projects/thrilling-tales/topics/billing",
  async (event) => {
    logger.debug("onBillingAlert");
    logger.debug(event.data.message.json);
  }
);

Error:

Unable to parse Pub/Sub message data as JSON: Unexpected token b in JSON at position 1

EDIT: JSON is valid and follows format from Firebase Docs

On another note, I managed to log the string received by the Cloud Function:

{budgetDisplayName:name-of-budget,alertThresholdExceeded:1,costAmount:100.01,costIntervalStart:2019-01-01T00:00:00Z,budgetAmount:100,budgetAmountType:SPECIFIED_AMOUNT,currencyCode:USD}

Weirdly, it seems like the double quotes are being removed? Seems like a bug from Firebase / Google Cloud, but I'm not entirely sure. I tried switching to v1 as well, but got the same error using the cli.

EDIT 2: I tried testing the function using the Google Cloud Console, as outlined here, and got the logs perfectly. So, if I had to guess, I'd say it's a bug in the google cloud CLI for Windows. But it's odd how no one noticed this before. Might have shown up in a recent update.


Solution

  • As Jon pointed out in the comments:

    if you're using it from Windows, I suspect it's the command prompt doing double quote removal. See stackoverflow.com/questions/7760545.

    In summary, if you're on Windows, you have 2 choices:

    1. Run gcloud CLI command from Bash (you likely have Git Bash installed), which is the default shell on Linux and MacOS.
    2. Use any of the other ways to send a PubSub message. I recommend using the Google Cloud Console.