Why does my opentok method does not work in firebase? - firebase

I use a firebase function which executes OpenTok SDK when it is triggered. The function creates a session. I was able to create a session successfully on my local server, but when I put it in production – in firebase- following error occurs:
Error creating session: Error: Failed to createSession. Error: The request failed: Error: getaddrinfo EAI_AGAIN api.opentok.com:443
at createSessionCallback (/srv/node_modules/opentok/lib/opentok.js:1125:16)
at Request._callback (/srv/node_modules/opentok/lib/client.js:59:14)
at self.callback (/srv/node_modules/request/request.js:185:22)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at Request.onRequestError (/srv/node_modules/request/request.js:877:8)
at emitOne (events.js:121:20)
at ClientRequest.emit (events.js:211:7)
at TLSSocket.socketErrorListener (_http_client.js:401:9)
at emitOne (events.js:116:13)
Other methods of this third party SDK like token generation also works on firebase but the method createSession fails. Can you help me please?
exports.dbUpdate = functions.database.ref('/test/{pushId}/text').onUpdate((change, context) => {
const beforeData = change.before.val(); // data before the write
const afterData = change.after.val();
if (beforeData == afterData) {
console.log("Text did not change");
return null;
}
opentok = new OpenTok("...", "...");
var sessionId;
opentok.createSession({
mediaMode: "routed"
}, function(error, session) {
if (error) {
console.log("Error creating session:", error)
token = "Failed";
} else {
sessionId = session.sessionId;
token = opentok.generateToken(sessionId);
}
});
return change.after.ref.parent.child('neuertest').set(token);
});
//The same code works on local server

The free Spark plan only allows for HTTP calls to Google services (see Cloud Functions on https://firebase.google.com/pricing/)
You’ll need to upgrade your plan to be able to run your function

Related

Prisma on production - User 'xxx' has exceeded the 'max_user_connections' resource

I'm having an issue when I upload my Next.js app in production (in Vercel). When I run the app in development, it works fine. Only 1 connection is created. But when I use the app in production, instantly reaches the max users connections (5).
I don't know what to share exactly, but this is my client.js:
import { PrismaClient } from "./generators/app";
export const prisma =
global.prisma ||
new PrismaClient();
if (process.env.NODE_ENV !== 'production') global.prisma = prisma;
And this is how I import it from api files:
import { prisma } from "../../../prisma/client";
I've tried both guides:
https://www.prisma.io/docs/guides/performance-and-optimization/connection-management
https://www.prisma.io/docs/guides/database/troubleshooting-orm/help-articles/nextjs-prisma-client-dev-practices
This is the error:
2022-10-27T20:58:32.492Z 07594f4a-727a-4e98-a4aa-264d060dc08b ERROR PrismaClientInitializationError:
Invalid `prisma.user.findUnique()` invocation:
Error querying the database: Server error: `ERROR 42000 (1226): User 'xxx' has exceeded the 'max_user_connections' resource (current value: 5)'
at RequestHandler.handleRequestError (/var/task/.next/server/chunks/7738.js:31215:19)
at RequestHandler.request (/var/task/.next/server/chunks/7738.js:31188:18)
at async PrismaClient._request (/var/task/.next/server/chunks/7738.js:32176:24)
at async havePermission (/var/task/.next/server/chunks/3433.js:49:40)
at async getServerData (/var/task/.next/server/pages/api/app/user/get/[column].js:181:34)
at async Object.apiResolver (/var/task/node_modules/next/dist/server/api-utils/node.js:366:9)
at async NextNodeServer.runApi (/var/task/node_modules/next/dist/server/next-server.js:469:9)
at async Object.fn (/var/task/node_modules/next/dist/server/next-server.js:719:37)
at async Router.execute (/var/task/node_modules/next/dist/server/router.js:247:36)
at async NextNodeServer.run (/var/task/node_modules/next/dist/server/base-server.js:346:29) {
clientVersion: '4.3.1',
errorCode: undefined
}
2022-10-27T20:58:32.501Z 07594f4a-727a-4e98-a4aa-260d060dc08b ERROR PrismaClientInitializationError:
Invalid `prisma.user.findUnique()` invocation:
Error querying the database: Server error: `ERROR 42000 (1226): User 'xxx' has exceeded the 'max_user_connections' resource (current value: 5)'
at RequestHandler.handleRequestError (/var/task/.next/server/chunks/7738.js:31215:19)
at RequestHandler.request (/var/task/.next/server/chunks/7738.js:31188:18)
at async PrismaClient._request (/var/task/.next/server/chunks/7738.js:32176:24)
at async havePermission (/var/task/.next/server/chunks/3433.js:49:40)
at async getServerData (/var/task/.next/server/pages/api/app/user/get/[column].js:181:34)
at async Object.apiResolver (/var/task/node_modules/next/dist/server/api-utils/node.js:366:9)
at async NextNodeServer.runApi (/var/task/node_modules/next/dist/server/next-server.js:469:9)
at async Object.fn (/var/task/node_modules/next/dist/server/next-server.js:719:37)
at async Router.execute (/var/task/node_modules/next/dist/server/router.js:247:36)
at async NextNodeServer.run (/var/task/node_modules/next/dist/server/base-server.js:346:29) {
clientVersion: '4.3.1',
errorCode: undefined
}
RequestId: 07594f4a-727a-4e98-a4aa-264d060dc08b Error: Runtime exited with error: exit status 1
Runtime.ExitError
After that it tries every second to make a GET request to the api with 500 response.
Vercel by default creates like 5 new connections to the database (maybe for the CDNs or something like that) and you need a larger connection limit.

Issue with Permissions for Google Cloud Functions

When one of my firebase cloud functions is triggered (cloud firestore trigger), I get a permissions error. I am unsure how to resolve this issue and there are few relevant resources. I have included the function itself as well as the error below.
I have tried reinitializing the app, disabling and reenabling the api, and deleting and redeploying the functions.
Function:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import {reportError} from "../logging";
import {chargeTypes} from "../constants/constants";
import {handleCreateTeam} from "./create-team";
import {handleJoinTeam} from "./join-team";
import {handleAcceptInvite} from "./accept-invite";
export async function handleNewJoinTeamDocument(event:
admin.firestore.DocumentSnapshot, context: functions.EventContext, db:
admin.firestore.Firestore) {
const todo = event.data();
if (todo === undefined) {
return reportError("Todo returned no data in handle new join team document", {user: context.params.id});
}
if (todo.processed) {
return {message: "Already processed this queue item"}
}
let result;
switch (todo.type) {
case chargeTypes.ACCEPT_INVITE:
result = handleAcceptInvite(todo, event, context, db);
break;
case chargeTypes.CREATE_TEAM:
result = handleCreateTeam(todo, event, context, db);
break;
case chargeTypes.JOIN_TEAM:
result = handleJoinTeam(todo, event, context, db);
break;
default:
break
}
return await result;
}
Error:
Error: 7 PERMISSION_DENIED: The caller does not have permission at
Object.exports.createStatusError
(/srv/node_modules/grpc/src/common.js:91:15) at
Object.onReceiveStatus
(/srv/node_modules/grpc/src/client_interceptors.js:1204:28) at
InterceptingListener._callNext
(/srv/node_modules/grpc/src/client_interceptors.js:568:42) at
InterceptingListener.onReceiveStatus
(/srv/node_modules/grpc/src/client_interceptors.js:618:8) at
callback
(/srv/node_modules/grpc/src/client_interceptors.js:845:24)
Log Details:
{
insertId: "000000-b7bc9521-25b8-4357-9301-a5c1df269ef4"
labels: {
execution_id: "767010698187131"
}
logName: "projects/snowballtesting-d70da/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
receiveTimestamp: "2019-09-29T16:38:47.207554787Z"
resource: {
labels: {…}
type: "cloud_function"
}
severity: "ERROR"
textPayload: "Error: 7 PERMISSION_DENIED: The caller does not have permission
at Object.exports.createStatusError (/srv/node_modules/grpc/src/common.js:91:15)
at Object.onReceiveStatus (/srv/node_modules/grpc/src/client_interceptors.js:1204:28)
at InterceptingListener._callNext (/srv/node_modules/grpc/src/client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (/srv/node_modules/grpc/src/client_interceptors.js:618:8)
at callback (/srv/node_modules/grpc/src/client_interceptors.js:845:24)"
timestamp: "2019-09-29T16:38:45.946Z"
trace: "projects/snowballtesting-d70da/traces/daf59e0d15388a1c4500bb4a88a7a084"
}

Firebase Cloud Messaging: Internal error encountered

I'm trying to send push notifications via a Firebase Cloud Function, but getting an internal error.
Error: Internal error encountered.
at FirebaseMessagingError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:88:28)
at new FirebaseMessagingError (/srv/node_modules/firebase-admin/lib/utils/error.js:253:16)
at Function.FirebaseMessagingError.fromServerError (/srv/node_modules/firebase-admin/lib/utils/error.js:283:16)
at Object.createFirebaseError (/srv/node_modules/firebase-admin/lib/messaging/messaging-errors.js:34:47)
at FirebaseMessagingRequestHandler.buildSendResponse (/srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:119:47)
at /srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:94:30
at Array.map (<anonymous>)
at /srv/node_modules/firebase-admin/lib/messaging/messaging-api-request.js:93:30
at <anonymous> errorInfo: [Object], codePrefix: 'messaging'
My function is simple enough:
sendPushNotification.js
const admin = require('firebase-admin');
const messaging = admin.messaging();
module.exports = function(title, deepLink, deviceTokens) {
var message = {
notification: {
title: title
},
data: {
deepLink: deepLink,
},
tokens: deviceTokens
};
console.log(`Sending notification ${title} with Deep Link ${deepLink} to ${deviceTokens.length} devices`);
console.log(deviceTokens);
return messaging.sendMulticast(message).then(response => {
console.log(`Success: ${response.successCount}, failure: ${response.failureCount}`);
if (response.failureCount > 0) {
console.log(response.responses)
}
});
}
The weird thing is that sometimes it does work, but maybe one in 10? The other times I get this less-than-helpful error. The APNs Authentication Key is uploaded in the Firebase Console in the project settings. The App Bundle ID is correct. I'm at a loss for what else could be going on.
(Yes, I am giving the function an array of valid deviceTokens.)
None of the other questions on StackOverflow seem to be related to this internal error, the answers on those questions don't apply here.

Firebase functions :ApiError: Not Found at Object.parseHttpRespBod : when removing from firebase storage

I'm trying to remove an item from my firebase storage by firebase cloud functions.
But its giving me this error..
Error { ApiError: Not Found
at Object.parseHttpRespBody (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:193:30)
at Object.handleResp (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:131:18)
at /user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/src/util.js:496:12
at Request.onResponse [as _callback] (/user_code/node_modules/firebase-admin/node_modules/#google-cloud/common/node_modules/retry-request/index.js:198:7)
at Request.self.callback (/user_code/node_modules/firebase-admin/node_modules/request/request.js:185:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/user_code/node_modules/firebase-admin/node_modules/request/request.js:1161:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
code: 404,
errors: [ { domain: 'global', reason: 'notFound', message: 'Not Found' } ],
response: undefined,
message: 'Not Found' }
And this is my code :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
var db = admin.firestore();
var storage = admin.storage().bucket('visa_cop');
exports.deletingVisaCop = functions.firestore.document('users/{user_Id}/info/visa_cop').onUpdate((change,context) =>{
var data = change.after.data().checked;
if(data === true)
{
return storage.delete().then(function(data) {
return console.log("DataIs",data);
}).catch(function(error){
return console.log("Error",error);
});
} else
{
}
});
And I added for Google APIs Service Agent and App Engine default service account storage admin roles from the I am & admin page.
Thank You.
the problem is here:
functions.firestore.document('users/{user_Id}/info/visa_cop').onUpdate((change,context)
at the moment, the function listens to a document called "visa_cop" in the folder "info". you need to add the token at the end, to tell the function to listen to update of any file in this folder (or you can specify a file if needed).
Just append e.g. /{visaId} after visa_cop, like so:
functions.firestore.document('users/{user_Id}/info/visa_cop/{visaId}').onUpdate((change,context)
Ps. "visaId" can be anything, however it must match the Document Path that you define at function deploy.
in your example, the function listens to any doc in "visa_cop" folder, so if you use:
Console:
Trigger is "Cloud Firestore"
Event Type is "update"
Document Path is "students/{studentId}/visa_cop/{visaId}"
CLI:
gcloud functions deploy [FUNCTION_NAME] \
--runtime [RUNTIME] \
--trigger-event providers/cloud.firestore/eventTypes/document.update \
--trigger-resource "projects/[PROJECT_ID]/databases/(default)/documents/users/{userId}/info/visa_cop/{visaId}"

Connection to Azure Cosmosdb failed using web socket

I have a script that connects to CosmosDB to make some operations, am using CosmosDB as graphDB, however, am using a node module called gremlin-secure which connects to cosmosDB through web sockets, however, recently, I could not connect to the Database as below error
events.js:160
throw er; // Unhandled 'error' event
^
Error: unexpected server response (200)
at ClientRequest._req.on (/Users/abshahin/dev/azure-cosmos-db-graph-nodejs-getting-started/node_modules/ws/lib/WebSocket.js:656:26)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:362:20)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at TLSSocket.Readable.push (_stream_readable.js:134:10)
my code looks like this
"use strict";
var Gremlin = require('gremlin-secure');
var config = require("./config");
const client = Gremlin.createClient(
443,
config.endpoint,
{
"session": false,
"ssl": true,
"user": `/dbs/${config.database}/colls/${config.collection}`,
"password": config.primaryKey
});
client.execute("g.addV('employee').property('id', 'abshahin')", { }, (err, results) => {
if (err) return console.error(err);
console.log(JSON.stringify(results));
});
and this is my config
var config = {}
config.endpoint = "xxxxxxxx.graphs.azure.com";
config.primaryKey = "super secret key";
config.database = "dbname"
config.collection = "collectionName"
module.exports = config;
I contacted Microsoft and they advised to post here, any help.
Check to make sure that the url of the db looks like xxx.graphs.azure.com the ulr displayed in the azure portal was not correct in my case.
This looks a bit similar to a problem I faced recently. Make sure you have latest OpenSSL version
openssl version -a
Azure CosmosDB enforces SSL/TLS 1.2 which is not supported by older versions of OpenSSL

Resources