I have asked a similar question Here.The new problem is that, after the internet address lookup('connected' is printed), but while the transaction is being run if the network is disconnected or when the network is very slow I get a timed out error exception which causes the app to crash.
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
print('connected');
Firestore.instance.runTransaction((transactionshere)async{
DocumentReference reference =
Firestore.instance.collection('One').document('two').collection('three').document('all_').collection('cur').document();
await reference.setData(dataToSend,merge: true);
});
}
} on SocketException catch (_) {
print('not connected');
_scafoldKey.currentState.showSnackBar(
SnackBar(content: Text("There was a problem check your connection"),duration: Duration(seconds: 4),),
);
}
error output:
I/flutter (24149): connected
W/Firestore(24149): (0.6.6-dev) [Firestore]: The behavior for java.util.Date objects stored in Firestore is going to change AND YOUR APP MAY BREAK.
W/Firestore(24149): To hide this warning and ensure your app does not break, you need to add the following code to your app before calling any other Cloud Firestore methods:
W/Firestore(24149):
W/Firestore(24149): FirebaseFirestore firestore = FirebaseFirestore.getInstance();
W/Firestore(24149): FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
W/Firestore(24149): .setTimestampsInSnapshotsEnabled(true)
W/Firestore(24149): .build();
W/Firestore(24149): firestore.setFirestoreSettings(settings);
W/Firestore(24149):
W/Firestore(24149): With this change, timestamps stored in Cloud Firestore will be read back as com.google.firebase.Timestamp objects instead of as system java.util.Date objects. So you will also need to update code expecting a java.util.Date to instead expect a Timestamp. For example:
W/Firestore(24149):
W/Firestore(24149): // Old:
W/Firestore(24149): java.util.Date date = snapshot.getDate("created_at");
W/Firestore(24149): // New:
W/Firestore(24149): Timestamp timestamp = snapshot.getTimestamp("created_at");
W/Firestore(24149): java.util.Date date = timestamp.toDate();
W/Firestore(24149):
W/Firestore(24149): Please audit all existing usages of java.util.Date when you enable the new behavior. In a future release, the behavior will be changed to the new behavior, so if you do not follow these steps, YOUR APP MAY BREAK.
I/zygote (24149): The ClassLoaderContext is a special shared library.
I/zygote (24149): The ClassLoaderContext is a special shared library.
V/NativeCrypto(24149): Registering com/google/android/gms/org/conscrypt/NativeCrypto's 287 native methods...
D/NetworkSecurityConfig(24149): No Network Security Config specified, using platform default
I/ProviderInstaller(24149): Installed default security provider GmsCore_OpenSSL
W/System (24149): ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
I/System.out(24149): e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp
W/System (24149): ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
I/System.out(24149): e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp
W/System (24149): ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
I/System.out(24149): e:java.lang.ClassNotFoundException: com.mediatek.cta.CtaHttp
W/System (24149): ClassLoader referenced unknown path: system/framework/mediatek-cta.jar
Related
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?
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.
Overview
I'm using Flutter with Firebase. After the phone/app enters Doze Mode, Firebase needs a few minutes (too long!) to reconnect. It took me weeks to find how to reproduce this issue.
Steps to reproduce:
Open a Flutter app and select a screen where you can call Firebase with a click of a button
Enter Androids' Doze Mode (Lock the screen, run adb shell dumpsys battery unplug, and then run adb shell dumpsys deviceidle force-idle)
After a few seconds/minutes, under the "Run" tab, the following will appear:
Stream closed with status: Status{code=UNAVAILABLE, description=Keepalive failed. The connection is likely gone, cause=null}.
and
[{0}] Failed to resolve name. status={1}
Now, unlock your phone and try to make a Firebase query
For me, the following error appears 8 out of 10 times. The connection will re-establish after hitting the "Retry" button, but only after a few minutes which is, of course, too late.
W/XXX.XXXXXXX(14214): Accessing
hidden method Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J
(greylist,core-platform-api, linking, allowed)
W/XXX.XXXXXXX(14214): Accessing hidden method
Lsun/misc/Unsafe;->putObject(Ljava/lang/Object;JLjava/lang/Object;)V
(greylist, linking, allowed) W/Firestore(14214): (22.0.1)
[WatchStream]: (72436f2) Stream closed with status:
Status{code=UNAVAILABLE, description=Unable to resolve host
firestore.googleapis.com, cause=java.lang.RuntimeException:
java.net.UnknownHostException: Unable to resolve host
"firestore.googleapis.com": No address associated with hostname
W/Firestore(14214): at
io.grpc.internal.DnsNameResolver.resolveAll(DnsNameResolver.java:436)
W/Firestore(14214): at
io.grpc.internal.DnsNameResolver$Resolve.resolveInternal(DnsNameResolver.java:272)
W/Firestore(14214): at
io.grpc.internal.DnsNameResolver$Resolve.run(DnsNameResolver.java:228)
W/Firestore(14214): at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/Firestore(14214): at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/Firestore(14214): at java.lang.Thread.run(Thread.java:919)
W/Firestore(14214): Caused by: java.net.UnknownHostException: Unable
to resolve host "firestore.googleapis.com": No address associated with
hostname W/Firestore(14214): at
java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:156)
W/Firestore(14214): at
java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
W/Firestore(14214): at
java.net.InetAddress.getAllByName(InetAddress.java:1152)
W/Firestore(14214): at
io.grpc.internal.DnsNameResolver$JdkAddressResolver.resolveAddress(DnsNameResolver.java:646)
W/Firestore(14214): at
io.grpc.internal.DnsNameResolver.resolveAll(DnsNameResolver.java:404)
W/Firestore(14214): ... 5 more W/Firestore(14214): Caused by:
android.system.GaiException: android_getaddrinfo failed: EAI_NODATA
(No address associated with hostname) W/Firestore(14214): at
libcore.io.Linux.android_getaddrinfo(Native Method)
W/Firestore(14214): at
libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
W/Firestore(14214): at
libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:200)
W/Firestore(14214): at
libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
W/Firestore(14214): at
java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:135)
W/Firestore(14214): ... 9 more W/Firestore(14214): }.
W/XXX.XXXXXXX(14214): Accessing hidden method
Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J
(greylist,core-platform-api, linking, allowed) I/flutter (14214):
MyDatabase | getDatabaselData |
[cloud_firestore/unavailable] The service is currently unavailable.
This is a most likely a transient condition and may be corrected by
retrying with a backoff.
The caught exception is: MyDatabase | getDatabaselData | [cloud_firestore/unavailable] The service is currently unavailable.
Pubspec.yaml
cloud_firestore: ^0.14.1+3
firebase_storage: ^4.0.1
firebase_core: ^0.5.0+1
firebase_auth: ^0.18.3
Edit 2: At the moment of writing this edit, there is a commit pending on FlutterFire git (but not yet published). So the solution will be to update to the latest Firebase_Core. It is also possible to fix it manually in Firebase_Core package > gradle.properties > change FirebaseSDKVersion=28.0.1 to FirebaseSDKVersion=28.1.0.
Edit: The issue still persists if the phone enters the state naturally (6 hours of complete inactivity). It seems this issue must be fixed inside FirebaseSDK and so far it hasn't been: https://github.com/FirebaseExtended/flutterfire/issues/4305
Old answer:
I see many people strugling with this, and I have finally found the solution.
It seems Firebase is mostly wasting time on the previous (dis)connection rather than the new connection. So what I did, is disconnecting Firebase whenever the app goes to the background, and reconnecting it upon resuming. In this case, a new connection is established within seconds.
Here is the code; create a life cycle manager class (observer) and wrap it around your MaterialApp. Try-Catch is probably not necessary, but I will be pushing to production tomorrow so it's just a precaution.
lifecycle_manager.dart
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class LifecycleManager extends StatefulWidget {
final Widget child;
LifecycleManager({Key key, this.child}) : super(key: key);
#override
_LifecycleManagerState createState() => _LifecycleManagerState();
}
class _LifecycleManagerState extends State<LifecycleManager> with WidgetsBindingObserver {
#override
Widget build(BuildContext context) {
return widget.child;
}
#override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
#override
void dispose() {
super.dispose();
WidgetsBinding.instance.removeObserver(this);
}
#override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
try {
if (state != AppLifecycleState.resumed) FirebaseFirestore.instance.disableNetwork();
else FirebaseFirestore.instance.enableNetwork();
} catch (error) {
print('LifecycleManager | didChangeAppLifecycleState | ' + error.toString());
}
}
}
main.dart
import 'lifecycle_manager.dart';
LifecycleManager(child: MaterialApp());
(I have also updated all my dependencies, but that didn't solve the problem)
Delete the application from the emulator.
Install the application.
Delete collection from firebase.
Run the code again.
This solved my problem without any changes to my versions.
Pubspec.yaml
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
get_it: ^1.0.3+2
provider: ^5.0.0
cloud_firestore: ^0.12.9+4
firebase_auth: 0.14.0+5
Usage
class MainPage extends StatefulWidget {
const MainPage({Key key}) : super(key: key);
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
final Firestore _firestore = Firestore.instance;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("First Page"),
),
body: Center(
child: Column(
children: [
RaisedButton(
child: Text("Add Data"),
color: Colors.deepPurple,
onPressed: _addData,
)
],
),
),
);
}
void _addData() {
Map<String, dynamic> addUser = Map();
addUser["name"] = "name1";
addUser["surname"] = "surname1";
_firestore
.collection("users")
.document("nameandsurname")
.setData(addUser)
.then((value) => debugPrint("user added"));
}
}
I have to integrate firebase remote config to my flutter app. From the searches in various sites, I couldn't find the complete solution.
class RemoteConfigurartion{
Future<RemoteConfig> setupRemoteConfig() async {
String value =null;
final RemoteConfig remoteConfig = await RemoteConfig.instance;
remoteConfig.setConfigSettings(RemoteConfigSettings(debugMode: false));
remoteConfig.setDefaults(<String, dynamic>{
'riddle': "off",
});
try {
// Using default duration to force fetching from remote server.
await remoteConfig.fetch(expiration: const Duration(seconds: 0));
await remoteConfig.activateFetched();
} on FetchThrottledException catch (exception) {
// Fetch throttled.
print(exception);
} catch (exception) {
print(
'Unable to fetch remote config. Cached or default values will be '
'used');
}
return remoteConfig;
}
}
This is what I found already. This the result I'm getting:
No implementation found for method RemoteConfig#instance on channel plugins.flutter.io/firebase_remote_config
But I have added all the plugins in the pubspec.yaml and in android gradle folder
Can anyone help me to find out a complete solution to integrate remote config to a flutter app?
Make sure that firebase_core is initialized, and for Android, google-services.json should be in the app folder. Aside from that, there doesn't seem to be any issues on your code. You might've missed some steps during set up.
If you've just added the plugins, it's best to run the app using restart instead of hot reload to ensure that all recently added plugins is included in the build.
I am trying to login with Twitter when i used dependency firebase_auth:^0.6.6 it was working perfactly and i fetch the user's Profile picture and the Code was
final TwitterLoginResult result = await twitterLogin.authorize();
switch (result.status)
{
case TwitterLoginStatus.loggedIn:
var session = result.session;
FirebaseUser user = await _auth.signInWithTwitter(
authToken: session.token, authTokenSecret: session.secret);
img=user.photoUrl;
}
but i migrated the app to AndroidX and this dependency was not compatible so i used firebase_auth: ^0.14.0+5 and this code was not working so i change the code to
final TwitterLoginResult result = await twitterLogin.authorize();
switch (result.status) {
case TwitterLoginStatus.loggedIn:
var session = result.session;
final AuthCredential credential =
TwitterAuthProvider.getCredential(authToken: session.token,
authTokenSecret: session.secret);
FirebaseUser user = (await _auth.signInWithCredential(credential)).user;
and this code is not working app is Crashing and showing the error
W/BiChannelGoogleApi(18829): [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzak#70a4ccf
W/InputMethodManager(18829): startInputReason = 1
D/FirebaseAuth(18829): Notifying id token listeners about user ( D71yiiEX7ubSon4xxcddKlSydn72 ).
D/FirebaseAuth(18829): Notifying auth state listeners about user ( D71yiiEXccccccccKlSydn72 ).
I/zygote64(18829): Do full code cache collection, code=124KB, data=91KB
I/zygote64(18829): After code cache collection, code=123KB, data=68KB
I/zygote64(18829): Do partial code cache collection, code=123KB, data=68KB
I/zygote64(18829): After code cache collection, code=123KB, data=68KB
I/zygote64(18829): Increasing code cache capacity to 512KB
D/AndroidRuntime(18829): Shutting down VM
E/AndroidRuntime(18829): FATAL EXCEPTION: main
E/AndroidRuntime(18829): Process: com.example.login_app, PID: 18829
E/AndroidRuntime(18829): java.lang.IllegalArgumentException: Unsupported value: null
E/AndroidRuntime(18829): at io.flutter.plugin.common.StandardMessageCodec.writeValue(StandardMessageCodec.java:294)
E/AndroidRuntime(18829): at io.flutter.plugin.common.StandardMessageCodec.writeValue(StandardMessageCodec.java:291)
E/AndroidRuntime(18829): at io.flutter.plugin.common.StandardMessageCodec.writeValue(StandardMessageCodec.java:291)
E/AndroidRuntime(18829): at io.flutter.plugin.common.StandardMessageCodec.writeValue(StandardMessageCodec.java:291)
E/AndroidRuntime(18829): at io.flutter.plugin.common.StandardMethodCodec.encodeSuccessEnvelope(StandardMethodCodec.java:57)
E/AndroidRuntime(18829): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler$1.success(MethodChannel.java:225)
E/AndroidRuntime(18829): at io.flutter.plugins.firebaseauth.FirebaseAuthPlugin$SignInCompleteListener.onComplete(FirebaseAuthPlugin.java:691)
E/AndroidRuntime(18829): at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
E/AndroidRuntime(18829): at android.os.Handler.handleCallback(Handler.java:808)
E/AndroidRuntime(18829): at android.os.Handler.dispatchMessage(Handler.java:101)
E/AndroidRuntime(18829): at android.os.Looper.loop(Looper.java:166)
E/AndroidRuntime(18829): at android.app.ActivityThread.main(ActivityThread.java:7529)
E/AndroidRuntime(18829): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(18829): at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
E/AndroidRuntime(18829): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
I/Process (18829): Sending signal. PID: 18829 SIG: 9
Lost connection to device.
Please can someone explain to me how to resolve this problem?
Problem is with login task AND Androidx twitter_login_issue
Add this dependency in your pubspec.yaml file and let me know this working or not?
flutter_twitter_login:
git: git://github.com/eudangeld/flutter_twitter_login.git
Same issue (question) login_issue