NextJS API route error for firestore: Deadline exceeded [duplicate] - firebase

This question already has answers here:
Firebase Cloud Functions: "4 DEADLINE_EXCEEDED: Deadline exceeded"
(1 answer)
google-cloud/firestore: Error: 4 DEADLINE_EXCEEDED: Deadline Exceeded while creating document
(1 answer)
Closed last month.
I am trying to write to firestore database, but no success.
I am using firebase-admin version 11.3.0
I can read and write into firebase realtime database, but I can only read documents from firestore.
The nextJS API function is as below. As can be seen, I am trying to write 1 document with just a timestamp field.
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const timestamp = Date.now()
const result = await admin.firestore().collection("Test").doc("doctest").set({timestamp: timestamp})
console.log("AWAIT: ", result.data())
return res.status(500).end()
}
The error I am getting is below:
error - Error: 4 DEADLINE_EXCEEDED: Deadline exceeded
at Object.callErrorFromStatus (/home/node/app/node_modules/#grpc/grpc-js/build/src/call.js:31:19)
at Object.onReceiveStatus (/home/node/app/node_modules/#grpc/grpc-js/build/src/client.js:195:52)
at Object.onReceiveStatus (/home/node/app/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:365:141)
at Object.onReceiveStatus (/home/node/app/node_modules/#grpc/grpc-js/build/src/client-interceptors.js:328:181)
at /home/node/app/node_modules/#grpc/grpc-js/build/src/call-stream.js:188:78
at processTicksAndRejections (node:internal/process/task_queues:78:11)
for call at
at ServiceClientImpl.makeUnaryRequest (/home/node/app/node_modules/#grpc/grpc-js/build/src/client.js:163:34)
at ServiceClientImpl.<anonymous> (/home/node/app/node_modules/#grpc/grpc-js/build/src/make-client.js:105:19)
at /home/node/app/node_modules/#google-cloud/firestore/build/src/v1/firestore_client.js:225:29
at /home/node/app/node_modules/google-gax/build/src/normalCalls/timeout.js:44:16
at repeat (/home/node/app/node_modules/google-gax/build/src/normalCalls/retries.js:80:25)
at /home/node/app/node_modules/google-gax/build/src/normalCalls/retries.js:118:13
at OngoingCallPromise.call (/home/node/app/node_modules/google-gax/build/src/call.js:67:27)
at NormalApiCaller.call (/home/node/app/node_modules/google-gax/build/src/normalCalls/normalApiCaller.js:34:19)
at /home/node/app/node_modules/google-gax/build/src/createApiCall.js:84:30
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Caused by: Error
at WriteBatch.commit (/home/node/app/node_modules/#google-cloud/firestore/build/src/write-batch.js:433:23)
at DocumentReference.set (/home/node/app/node_modules/#google-cloud/firestore/build/src/reference.js:391:27)
at handler (webpack-internal:///(api)/./pages/api/store/[storeid]/department/[depid]/product/[prodid].ts:51:132)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.apiResolver (/home/node/app/node_modules/next/dist/server/api-utils/node.js:367:9)
at async DevServer.runApi (/home/node/app/node_modules/next/dist/server/next-server.js:476:9)
at async Object.fn (/home/node/app/node_modules/next/dist/server/next-server.js:738:37)
at async Router.execute (/home/node/app/node_modules/next/dist/server/router.js:252:36)
at async DevServer.run (/home/node/app/node_modules/next/dist/server/base-server.js:381:29)
at async DevServer.run (/home/node/app/node_modules/next/dist/server/dev/next-dev-server.js:732:20) {
code: 4,
details: 'Deadline exceeded',
metadata: Metadata { internalRepr: Map(0) {}, options: {} },
note: 'Exception occurred in retry method that was not classified as transient',
page: '/api/store/[storeid]/department/[depid]/product/[prodid]'
}
I haven't exceeded the limits of read and write. Actually, I have used less than 1% of read and write quota.
I could not say for sure that is the poor internet connection, because I can read and write into firebase realtime database. In addition, I can read documents from firestore.
How to overcome this issue?

Related

Login attempt with GoogleProvider in next-auth returns OAUTH_CALLBACK_ERROR and message: checks.state argument is missing

I'm on a project for my JS FullStack course and I'm running into some issues with Google Provider of next-auth (version 4.18.8).
Everything worked fine ONE SINGLE TIME this morning. After successfuly login with google provider and use "useSession()" to get the Google credentials in a console.log, I committed everything and went to the gym. After I get back (and took a shower, of course), I was going to get those google credentials to show the user name on the page's header, but to my surprise I started getting this callback error.
FYI, env.local is correcty setup with GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET. I even deleted my credentials on Google and created another one to test, but no luck.
When trying to login, I get this error:
[next-auth][error][OAUTH_CALLBACK_ERROR]
https://next-auth.js.org/errors#oauth_callback_error checks.state argument is missing {
error: TypeError: checks.state argument is missing
at Client.callback (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\openid-client\lib\client.js:387:13)
at oAuthCallback (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\core\lib\oauth\callback.js:127:29)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.callback (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\core\routes\callback.js:52:11)
at async AuthHandler (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\core\index.js:201:28)
at async NextAuthHandler (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\next\index.js:23:19)
at async C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next-auth\next\index.js:59:32
at async Object.apiResolver (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\api-utils\node.js:363:9)
at async DevServer.runApi (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\next-server.js:487:9)
at async Object.fn (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\next-server.js:749:37)
at async Router.execute (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\router.js:253:36)
at async DevServer.run (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\base-server.js:384:29)
at async DevServer.run (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\dev\next-dev-server.js:741:20)
at async DevServer.handleRequest (C:\João\Dropbox\Pessoal\Projetos Webdesign\trading-center\node_modules\next\dist\server\base-server.js:322:20) {
name: 'OAuthCallbackError',
code: undefined
},
providerId: 'google',
message: 'checks.state argument is missing'
There are some things I noticed after clicking in my Google account, on Network tab of my DevTools:
First, it will make a request that returns status code 302 on "consent?authuser=0&part=......."
After that, another request to "google?state=......" returns 302 also.
Then I get an error on request to http://127.0.0.1:3000/api/auth/error?error=OAuthCallback also with 302 status code.
Finally, I get an error on request to http://127.0.0.1:3000/api/auth/signin?error=OAuthCallback that returns 404
I don't understand this very much, but I'm pretty sure I was not meant to get a 302 error on those requests.
Here's my code.
I have a button that calls this function:
const handleGoogleLogin = async () => {
await signIn('google', {
redirect: true,
callbackUrl: 'http://127.0.0.1:3000/user/dashboard'
})
}
My [...nextauth].js file:
export const authOptions = {
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET
})
],
session: {
strategy: "jwt",
},
jwt: {
secret: process.env.JWT_TOKEN
},
adapter: MongooseAdapter(process.env.MONGODB_URI),
}
export default NextAuth(authOptions)
See entire code in my GitHub.
Feel free to ask me any more questions if you feel the need.
Greatly appreciated.
João Textor
Fixed.
callbackUrl should not be like this 'http://127.0.0.1:3000/user/dashboard, but like this: '/user/dashboard'
Simple fix, simple mistake, A LOT OF HEADACHE!

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.

NOT_FOUND when adding tasks to Google Cloud Tasks

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
}
}

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 auth().createUser - Error while making request: timeout of 10000ms exceede

I'm trying to include a list of users (more than 50) through a specific function in Firebase. Here's my code:
Object.keys(newUsers).forEach((key) => {
console.log(newUsers[key]['name']);
admin.auth().createUser({
uid: key,
email: newUsers[key]['email']
password: newUsers[key]['InitialPwd'],
disabled: false,
emailVerified: false,
displayName: newUsers[key]['name'],
}).then((userRecord) => {
return console.log('Success');
}).catch(function(error) {
console.log("Error:", error);
});
});
And the error is (for each record):
{ Error: Error while making request: timeout of 10000ms exceeded.
at FirebaseAppError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseAppError (/srv/node_modules/firebase-admin/lib/utils/error.js:119:28)
at /srv/node_modules/firebase-admin/lib/utils/api-request.js:117:23
at
at process._tickDomainCallback (internal/process/next_tick.js:228:7) errorInfo: { code:
'app/network-timeout',
message: 'Error while making request: timeout of 10000ms exceeded.' }, codePrefix: 'app' }
How can I solve this?
Cloud Functions are set to run for a short period of time. If you are doing lots of work in a Cloud Function, it may time out before it is complete. There are a few solutions to this that I would suggest:
1.Change your Cloud Functions timeout. In the Cloud console, check at the top to make sure your current project is selected, and then in the middle you'll find your list of functions. Click on your function. You should be in function details now. Click "Edit". Right above the "save" button is "more". Select "more" and you'll see an option for upping the timeout. This can modify how long the function stays alive.
2.Change the batch size so you're creating fewer users at a time.
3.Make sure your promises are working as expected. If you don't return the call to createUser, the resulting UserRecord won't be accessible.
Object.keys(newUsers).forEach((key) => {
console.log(newUsers[key]['name']);
return admin.auth().createUser({
uid: key,
email: newUsers[key]['email']
password: newUsers[key]['InitialPwd'],
disabled: false,
emailVerified: false,
displayName: newUsers[key]['name'],
}).then((userRecord) => {
return console.log('Success');
}).catch(function(error) {
console.log("Error:", error);
});
});
4.I may be incorrect about this point, but it appears that the users are created one after another rather than concurrently. This could be a good case to look into using Promise.all so that all of the users can be created simultaneously, rather than waiting for one to complete before starting the next.

Resources