Cloud Task Creation : Error: 3 INVALID_ARGUMENT: Request contains an invalid argument - grpc

I'm following thist tutorial : https://cloud.google.com/tasks/docs/tutorial-gcf
To create a Task that would call a cloud function.
I've done quite some tries and still get this error:
If I change the body encoding to something else, I get another error about serialisation method.
It's likely not a permission issues, as I got some before and got rid of it.
The object which is pass to the createTask() is the following :
task: {
httpRequest: {
url: "https://europe-west1-project_id.cloudfunctions.net/FunctionName"
httpMethod: "POST"
oidcToken: {
serviceAccountEmail: "cf-targetFunctionSA#project_id.gserviceaccount.com"
}
body: ""
headers: {
Content-Type: "application/json"
}
}
(or with body: base64 encoded json string.)
The code I use is the following :
'use strict';
const common = require('./common');
const {v2beta3} = require('#google-cloud/tasks');
const cloudTasksClient = new v2beta3.CloudTasksClient();
let projectName = common.getProjectName();
let location = "europe-west3";
let queue = "compute-stats-on-mysql";
const parent = cloudTasksClient.queuePath(projectName, location, queue);
async function createTask(url, serviceAccount, data)
{
const dataBuffer = Buffer.from(JSON.stringify(data)).toString('base64');
const task = {
httpRequest: {
httpMethod: 'POST',
url:url,
oidcToken: {
serviceAccountEmail: serviceAccount,
},
headers: {
'Content-Type': 'application/json',
},
body:dataBuffer,
},
};
try
{
// Send create task request.
common.logDebug(`Before creating task`, {parent:parent,task:task, data:data});
const [response] = await cloudTasksClient.createTask({parent, task});
common.logDebug(`Created task ${response.name}`, {parent:parent,task:task, response:response, data:data});
return response;
}
catch (error)
{
// Construct error for Stackdriver Error Reporting
console.error("error while creating tasks",error);
}
}
module.exports = {
createTask : createTask,
cloudTasksClient:cloudTasksClient
};
The lack of details in the error makes me hit a wall blind...
Any suggestions ?

My service account was missing a part...
it was
"cf-"+functionName+"#"+projectName+".gserviceaccount.com";
instead of
"cf-"+functionName+"#"+projectName+".iam.gserviceaccount.com";
I left out the ".iam" during my numerous test to make it work.
For sure there's room for improvement in the error messages.

I had same problem. In your case I think there is not property scheduleTime into task param.
To me, the scheduleTime.seconds was with a wrong value.

Related

What is the best practice to bypass my specific dynamic code evaluation in next.js middleware?

I use next.js middleware to retrieve a data stored inside a cookie, and to check in a db (using strapi) if this specific user exists, or if he needs to register before going further.
// middleware.js
import { getToken } from 'next-auth/jwt';
import qs from 'qs';
import { MY_DB } from './constants';
export async function middleware(request) {
const token = await getToken({
req: request,
secret: process.env.SECRET,
});
const params = qs.stringify({
filters: {
address: {
$eq: token.sub,
},
},
});
const url = MY_DB + '/api/users/?' + params;
const result = await fetch(url, {
method: 'GET',
headers: { accept: 'application/json' },
});
// remaining code checks if the request is empty or not and returns the appropriate page
(...)
building my project returns the following error :
Failed to compile.
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/implementation.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation
Import trace for requested module:
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/implementation.js
./node_modules/.pnpm/function-bind#1.1.1/node_modules/function-bind/index.js
./node_modules/.pnpm/get-intrinsic#1.1.3/node_modules/get-intrinsic/index.js
./node_modules/.pnpm/side-channel#1.0.4/node_modules/side-channel/index.js
./node_modules/.pnpm/qs#6.11.0/node_modules/qs/lib/stringify.js
./node_modules/.pnpm/qs#6.11.0/node_modules/qs/lib/index.js
> Build failed because of webpack errors
 ELIFECYCLE  Command failed with exit code 1.
I highly suspect the qs.stringify call given the stacktrace, but how can I overcome this in an elegant way ?

Nuxt3: Error using function inside defineEventHandler() in server/api/ file

I am trying to pass some authentication headers to fetch a third party API , but I am getting the following error when running a /server/api/walmart.js file in Nuxt3:
[nuxt] [request error] this[D].init is not a function at new Sign
(https://nuxt-starter-jzgdht.w.staticblitz.com/blitz.331c80ffab288536319518a60349d00207075dad.js:6:1135208)
at Object.createSign
(https://nuxt-starter-jzgdht.w.staticblitz.com/blitz.331c80ffab288536319518a60349d00207075dad.js:6:808197)
at Scheme.sign (./node_modules/node-rsa/src/schemes/pkcs1.js:152:32)
at RSAKey.module.exports.Key.RSAKey.sign
(./node_modules/node-rsa/src/libs/rsa.js:264:40) at
NodeRSA.module.exports.NodeRSA.sign
(./node_modules/node-rsa/src/NodeRSA.js:318:32) at
generateWalmartHeaders (./.nuxt/dev/index.mjs:446:28) at eval
(./.nuxt/dev/index.mjs:458:14) at eval
(./node_modules/h3/dist/index.mjs:364:14) at Object.eval [as handler]
(./node_modules/h3/dist/index.mjs:564:12) at eval
(./node_modules/h3/dist/index.mjs:475:31) [nuxt] [request error]
this[D].init is not a function at new Sign
(https://nuxt-starter-jzgdht.w.staticblitz.com/blitz.331c80ffab288536319518a60349d00207075dad.js:6:1135208)
at Object.createSign
(https://nuxt-starter-jzgdht.w.staticblitz.com/blitz.331c80ffab288536319518a60349d00207075dad.js:6:808197)
at Scheme.sign (./node_modules/node-rsa/src/schemes/pkcs1.js:152:32)
at RSAKey.module.exports.Key.RSAKey.sign
(./node_modules/node-rsa/src/libs/rsa.js:264:40) at
NodeRSA.module.exports.NodeRSA.sign
(./node_modules/node-rsa/src/NodeRSA.js:318:32) at
generateWalmartHeaders (./.nuxt/dev/index.mjs:446:28) at eval
(./.nuxt/dev/index.mjs:458:14) at eval
(./node_modules/h3/dist/index.mjs:364:14) at Object.eval [as handler]
(./node_modules/h3/dist/index.mjs:564:12) at eval
(./node_modules/h3/dist/index.mjs:475:31)
import NodeRSA from 'node-rsa';
const keyData = {
consumerId: '<consumer id removed for this post>',
privateKey: `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAiDffvTlnBcHfDhPjYlJhSk+atPFE6HpFaf4mm/aYBXmOn89A
MMulkkmpu+RGj0SaPrpX/ockoSeMuuEPPd3AQ5uZAnJw9TBnE2/kJrPsHaKyVFGV
hZneksIK/KdP/kpGSuVAkocPdit5zKwliMnc6/GVLpDFvU8K2QPnvYu2Jp8XBDwg
gTu2tzHQkrm0cdCYZklKKqN9NdVLJy+6AL50+vX19nHwDdCYCvnPtH/hXxMwRnIJ
3qibO8owPWh+q/xMld2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SZh752DjNc1pM
qmTw2cITx1MiUylVOr0caROi4XrrELUPGSVDA1FOaegSuVE89XhgmdNkRBh0p7Qt
4zYGWQKBgFGuZgbPl76K3fj5POY5OlPusXdCCqJMHKPug+4e5mG82T1KvLFCj1PQ
Fm0y9PoS3A8SXf+aEeLhRqVrpaU4w5RK8PqeF6IB2hpDrHJ8b+3ERU3J7/KuU8Vw
pmwDIbjWypH4dNJgRMti+RKDb9llup6xP5Q4PQRzvUQdklSCp3D8
-----END RSA PRIVATE KEY-----`,
keyVer: 1,
};
const generateWalmartHeaders = () => {
const { privateKey, consumerId, keyVer } = keyData;
const hashList = {
'WM_CONSUMER.ID': consumerId,
'WM_CONSUMER.INTIMESTAMP': Date.now().toString(),
'WM_SEC.KEY_VERSION': keyVer,
};
const sortedHashString = `${hashList['WM_CONSUMER.ID']}\n${hashList['WM_CONSUMER.INTIMESTAMP']}\n${hashList['WM_SEC.KEY_VERSION']}\n`;
const signer = new NodeRSA(privateKey, 'pkcs1');
const signature = signer.sign(sortedHashString);
const signatureEnc = signature.toString('base64');
return {
'WM_SEC.AUTH_SIGNATURE': signatureEnc,
'WM_CONSUMER.INTIMESTAMP': hashList['WM_CONSUMER.INTIMESTAMP'],
'WM_CONSUMER.ID': hashList['WM_CONSUMER.ID'],
'WM_SEC.KEY_VERSION': hashList['WM_SEC.KEY_VERSION'],
};
};
export default defineEventHandler(() => {
const options = {
method: 'GET',
headers: generateWalmartHeaders(), // <--- the error seems to originate from this
return {
api: 'works',
options: options,
};
});
Am I not using the defineEventHandler() correctly there?
#redshift,
1.The const 'options' in the defineEventHandler() function has not closing tag (unterminated).
Keep in mind we're working in server side here, check your functions within generateWalmartHeaders(). Are they all functioning in the backend ?
Fire this code with hard coded headers , and see if it runs / debug it.
Check Docs - they changed the documentation 20th of June sometime later than u posted this question.
check this example...
export default defineEventHandler((event) => {
return {
api: 'works'
}
})
Check my working example , maybe it will help you get on your way :
const config = useRuntimeConfig()
let environment = process.env.NODE_ENV;
let $endpoint = environment == 'development' ? 'http://dev.endpointisdev/' : 'http://prod.production/';
console.log('ENVIRONMENT =', process.env.NODE_ENV)
console.log('$ENDPOINTS =', $endpoint)
export default defineEventHandler(async(event) => {
const productsRequest = await $fetch(`${$endpoint}` +'somelistrequest', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(`${config.auth_user}:${config.auth_pw}`),
'guiId': '7552662'
},
body: {
reference : "blablabla", //
productListRequest : {
securityKey : `${config._key}`
}
}
});
return responseObject.list
})
IMPORTANT :
I fire this from my store with something like this ..
Now i've encountered a situation today where deployment to production made this api call fail because it needed to be "camelCase"
let submitOrder = await $fetch("/api/submitOrder", {method: 'POST', body: orderPayload});

Next.js API / API resolved without sending a response for /api/employees, this may result in stalled requests

I looked over the previous postings but they did not seem to match my issue. I am only using the next.js package and the integrated api pages. Mongoose is what I am using to make my schemas. I keep getting the above error only for my post calls. Any ideas what is going wrong here?
import dbConnect from "../../../utils/dbConnect";
import Employee from "../../../models/Employee";
dbConnect();
export default async (req, res) => {
const { method } = req;
switch (method) {
case "POST":
await Employee.create(req.body, function (err, data) {
if (err) {
res.status(500).json({
success: false,
data: err,
});
} else {
res.status(201).json({
success: true,
data: data,
});
}
});
break;
default:
res.status(405).json({
success: false,
});
}
};
This is a false warning because in the provided code you always return a response. It's just Next.js doesn't know it.
If you are sure that you return a response in every single case, you can disable warnings for unresolved requests.
/pages/api/your_endpoint.js
export const config = {
api: {
externalResolver: true,
},
}
Custom Config For API Routes

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

HTTP request to a google service returns Error: read ECONNRESET firebase cloud functions

I am trying to translate the name of a user from english to an indian language using google translate api and storing the data back in realtime database with a cloud function.
This function is invoked by a write to the database, and I am using a HTTP POST request to send a request to the cloud translate api and the response is stored back to the database. My code for the translate request is this.
var translate_options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
qs:
{ key: 'key goes here',
},
form: {
q: fullData.name,
target: "te"
},
};
request(translate_options, function (error, translate_response, translate_body) {
if (error){
console.log("In translating, got an error");
console.log(error);
}
// Query to the database goes here.
});
This code, if tried in my laptop, gives me the correct translation, but if I deploy it as a cloud function, it gives me an error. Very specifically
{ Error: read ECONNRESET
at exports._errnoException (util.js:1020:11)
at TLSWrap.onread (net.js:568:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
I am on firebase blaze plan, and I am able to sent POST request to my other services, but not a google service.
Can anybody help me with this issue. Thanks in advance.
Edit :
The full code is
var functions = require('firebase-functions');
var admin = require('firebase-admin');
var request = require("request");
admin.initializeApp(functions.config().firebase);
exports.whenUserIsAdded = functions.database.ref('users/{companyId}/{uid}').onCreate(event => {
var fullData = event.data.val();
var lang_code = {
"bengali": "bn",
"telugu": "te",
"english": "en"
}
var lang_var = lang_code[fullData['edition']];
var translate_options = { method: 'POST',
url: 'https://translation.googleapis.com/language/translate/v2',
qs:
{ key: 'Key goes here',
},
form: {
q: fullData.name,
target: lang_var
},
};
request(translate_options, function (error, translate_response, translate_body) {
var farmer_name = "";
if(error){
console.log("There is an error in translation");
console.log(error);
}
translate_body = JSON.parse(translate_body);
if(translate_body.data.translations){
farmer_name = translate_body.data.translations[0].translatedText;
console.log("The farmer name is " + fullData.name +" : " + farmer_name);
// Code to write to the database;
} else{
console.log("The translation failed");
farmer_name = fullData.name;
console.log("The famrer name is " + farmer_name);
}
})
});
You're not returning a promise that's resolved when all the work of your function is complete. If the work was completing in the past, that possibly just means you were lucky. Without returning a promise, Cloud Functions may terminate and clean up any work that wasn't complete when the function returns. Properly returning a promise will prevent Cloud Functions from cleaning up before the work is done.
Please consider reading my blog post about this. There is a section special just for ECONNRESET.

Resources