NOT_FOUND when adding tasks to Google Cloud Tasks - firebase

I'm getting an error called NOT_FOUND while adding tasks to Google Cloud Tasks from the Firebase Functions. It's only 1 task that I tried to add. Not sure why this is happening.
The queue is present and from the command line, it works fine.
Here is the detailed error log:
Error: 5 NOT_FOUND: Requested entity was not found.
at Object.callErrorFromStatus (/workspace/node_modules/#grpc/grpc-js/build/src/call.js:31:26)
at Object.onReceiveStatus (/workspace/node_modules/#grpc/grpc-js/build/src/client.js:189:52)
at Object.onReceiveStatus (/workspace/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:365:141)
at Object.onReceiveStatus (/workspace/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:328:181)
at /workspace/node_modules/#grpc/grpc-js/build/src/call-stream.js:187:78
at processTicksAndRejections (node:internal/process/task_queues:78:11)
It would save my day.
Thanks in advance

check the service account email you are using, suppose you have the task object like this:
const task = {
httpRequest: {
httpMethod: 'POST',
url,
body: Buffer.from(JSON.stringify((payload))).toString('base64'), // required by cloud tasks api
headers: {
'Content-Type': 'application/json',
},
oidcToken: {
serviceAccountEmail // check if this is a valid serviceAccountEmail
}
},
scheduleTime: {
seconds: sendAtSeconds // THE STUFF
}
}

Related

Firebase cloud function error: Maximum call size stack size exceeded

I've made firebase cloud function which adds the claim to a user that he or she has paid (set paid to true for user):
const admin = require("firebase-admin");
exports.addPaidClaim = functions.https.onCall(async (data, context) => {
// add custom claim (paid)
return admin.auth().setCustomUserClaims(data.uid, {
paid: true,
}).then(() => {
return {
message: `Succes! ${data.email} has paid for the course`,
};
}).catch((err) => {
return err;
});
});
However, when I'm running this function: I'm receiving the following error: "Unhandled Rejection (RangeError): Maximum call stack size exceeded". I really don't understand why this is happening. Does somebody see what could cause what's getting recalled which in turn causes the function to never end?
Asynchronous operations need to return a promise as stated in the documentation. Therefore, Cloud Functions is trying to serialize the data contained by promise returned by transaction, then send it in JSON format to the client. I believe your setCustomClaims does not send any object to consider it as an answer to the promise to finish the process so it keeps in a waiting loop that throws the Range Error.
To avoid this error I can think of two different options:
Add a paid parameter to be able to send a JSON response (and remove the setCustomUserClaim if it there isn’t any need to change the user access control because they are not designed to store additional data) .
Insert a promise that resolves and sends any needed information to the client. Something like:
return new Promise(function(resolve, reject) {
request({
url: URL,
method: "POST",
json: true,
body: queryJSON //A json variable I've built previously
}, function (error, response, body) {
if (error) {
reject(error);
}
else {
resolve(body)
}
});
});

Close open resource handles returned from Deno APIs before finishing test case

I'm getting this error message:
Make sure to close all open resource handles returned from Deno APIs before
finishing test case.
When I'm running this Deno testing function:
import { assertEquals } from "https://deno.land/std/testing/asserts.ts";
Deno.test("fetch example", async function (): Promise<void> {
await fetch("http://www.google.com.br").then(data => {
console.log('completed')
});
assertEquals("world", "world");
});
The command I use to run it is:
deno test --allow-net
I looked at the documentation but I wasn't able to find a way to solve it.
This is the complete error stack:
$ deno test --allow-net
Compile file:///<my_path>/isolated_test.ts
running 1 tests
test fetch example ... completed
FAILED (199ms)
failures:
fetch example
AssertionError: Test case is leaking resources.
Before: {
"0": "stdin",
"1": "stdout",
"2": "stderr"
}
After: {
"0": "stdin",
"1": "stdout",
"2": "stderr",
"3": "httpBody"
}
Make sure to close all open resource handles returned from Deno APIs before
finishing test case.
at Object.assert ($deno$/util.ts:33:11)
at Object.resourceSanitizer [as fn] ($deno$/testing.ts:81:5)
at async TestApi.[Symbol.asyncIterator] ($deno$/testing.ts:264:11)
at async Object.runTests ($deno$/testing.ts:346:20)
failures:
fetch example
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out (199ms)
My deno version
$ deno --version
deno 1.0.2
v8 8.4.300
typescript 3.9.2
Deno tests checks for resource handles that were not closed properly during a test.
In order to fix your test, you need to consume the response body, since internally uses a resource handle. A simple way would be to call .text or any other of the methods to consume the body: arrayBuffer, json, formData, blob
Deno.test("fetch example", async function (): Promise<void> {
const res = await fetch("http://www.google.com.br")
await res.text(); // Consume the body so the file handle is closed
assertEquals("world", "world");
});
You can see that one of the resource handles is httpBody:
After: {
"0": "stdin",
"1": "stdout",
"2": "stderr",
"3": "httpBody"
}
Currently, there's no way to disregard the body since Deno's fetch does not support AbortController.
Deno only closes automatically the resource handle if the status code is one of 301, 302, 303, 307, 308
Update
As of Deno 1.0.3, Response.body is now a ReadableStream (PR #5787) and the resource handle can be closed calling `res.body.cancel();
Deno.test("fetch example", async function (): Promise<void> {
const res = await fetch("http://www.google.com.br")
await res.body.cancel(); // Cancel the body so the file handle is closed
assertEquals("world", "world");
});

Cloud Vision with Cloud Functions: Exception occurred in retry method that was not classified as transient

I've been getting the following error from a Cloud function that uses the Cloud Vision API:
Error: 1 CANCELLED: The operation was cancelled.
at Object.callErrorFromStatus (/srv/functions/node_modules/#grpc/grpc-js/build/src/call.js:30:26)
at Http2CallStream.call.on (/srv/functions/node_modules/#grpc/grpc-js/build/src/client.js:96:33)
at Http2CallStream.emit (events.js:203:15)
at Http2CallStream.EventEmitter.emit (domain.js:466:23)
at process.nextTick (/srv/functions/node_modules/#grpc/grpc-js/build/src/call-stream.js:100:22)
at process._tickCallback (internal/process/next_tick.js:61:11)
code: 1,
details: 'The operation was cancelled.',
metadata:
Metadata {
internalRepr:
Map {
'google.rpc.debuginfo-bin' => [Array],
'grpc-status-details-bin' => [Array] },
options: {} },
note:
'Exception occurred in retry method that was not classified as transient' }
The code is as follows:
const vision = require('#google-cloud/vision');
const client = new vision.ImageAnnotatorClient();
const [result] = await client.textDetection(`gs://${process.env.GCLOUD_PROJECT}.appspot.com/${fileName}`)
.catch((err: any) => {
return db.doc(event.ref.path).update({ status: 'error' });
});
Not sure if this has to do with the problems Firebase had today?
I resolved this by adding using google-gax version 1.15.2 and adding the following resolution:
"resolutions": {
"google-gax": "1.15.2"
},

Firebase / Google Cloud Function cron function returns INVALID_ARGUMENT

I'm trying to deploy a scheduled Cloud Function as in this article.
I've got two functions in my /functions/index.js. The first one is a https function and it works correctly, but englishSyntax doesn't run.
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
exports.englishSyntax = functions.pubsub
.schedule('every 30 seconds')
.timeZone('America/New_York')
.onRun(context => {
console.log('triggered every 30 secs', context);
});
I'm on the minimum versions for cron.
"dependencies": {
"firebase-admin": "~7.0.0",
"firebase-functions": "^2.3.0"
},
In my Logs Viewer:
2019-08-23 11:18:52.048 EDT
Cloud Scheduler API
CreateJob
us-central1
email#mail.com
INVALID_ARGUMENT
And the details:
status: {
code: 3
message: "INVALID_ARGUMENT"
}
...
resource: {
labels: {
method: ""
project_id: "my-project"
service: ""
}
type: "audited_resource"
}
severity: "ERROR"
What does this error indicate? How can I fix it so that it runs my function on schedule? Besides the status of the function, where would I check the console.log output to verify it's working?
Figured it out. The error message was accurate after all. The problem is that seconds is not a valid argument. It needed to be either minutes or hours. It seems that every minute still needs a numerical second arg as well. The docs make it more clear exactly how "English-y" the syntax really is or isn't.
https://cloud.google.com/appengine/docs/standard/python/config/cronref#start-time

How to use SailsJs with firebase functions

I'm trying to create nodejs app with sails.js and firebase. Cannot understand how to access express part of SailsJs.
Firebase app initialized by
exports.app = functions.https.onRequest(app);
app - express app.
Sails app initialized by
sails.lift(rc('sails'));
Tried to access to sails.hooks.http.app but it is undefined. Any ideas?
Thanks
hi you can use this piece of code to to execute fire base messaging services and in same manner other services too
var request = require('request');
function sendMessageToUser(deviceId, message) {
request({
url: 'https://fcm.googleapis.com/fcm/send',
method: 'POST',
headers: {
'Content-Type' :' application/json',
'Authorization': 'key=AI...8o'
},
body: JSON.stringify(
{ "data": {
"message": message
},
"to" : deviceId
}
)
}, function(error, response, body) {
if (error) {
console.error(error, response, body);
}
else if (response.statusCode >= 400) {
console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage+'\n'+body);
}
else {
console.log('Done!')
}
});
sendMessageToUser(
"d7x...KJQ",
{ message: 'Hello puf'}
);
as sails provide a method mentioned below ,but i was not able find exact example to implement Firebase with it so i used core node to explain it , I will be updating this answer after i finished with this method and sails + Firebase
res.created()
hope this helps you in your work

Resources