invertase / react-native-firebase

🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
https://rnfirebase.io
Other
11.68k stars 2.21k forks source link

[🐛] Functions Emulator not working with real android device :fire: #6475

Closed Fri3ndlymushroom closed 1 year ago

Fri3ndlymushroom commented 2 years ago

Issue

I am trying to set up the Firebase functions emulator for React Native. But I can't reach the functions emulator. When trying it without the emulator everything went smoothly.

Client

import functions from '@react-native-firebase/functions';

const DEV = true
if (DEV) {
  functions().useEmulator("192.168.x.x", 5001);
}

const sayHelloWorld = () =>{
  functions()
    .httpsCallable('helloWorld')()
        .then(response => {
            console.log(response.data)
        });
}

sayHelloWorld()

Backend Function

exports.helloWorld = functions.https.onRequest((request, response) => {
    response.status(200).send({"data":"Say hello world"});
});

I am using the useEmulator function to switch to the emulator running on port 5001. I am not using useFunctionEmulator as shown in the documentation (https://rnfirebase.io/functions/usage) because it appears to be outdated, but I tried it, and it doesn't work as well. I am using my local IP address for the host because I am running a physical android device. I have no issue running the app, but as soon as I execute the function request nothing happens and after one minute I get the following error message:

Possible Unhandled Promise Rejection (id: 0):     
Error: DEADLINE_EXCEEDED
Error: DEADLINE_EXCEEDED
callFirebaseFunctions@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:116187:60
_performTransitionSideEffects@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:65273:22       
_receiveSignal@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:65215:45
onResponderRelease@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:65055:34
invokeGuardedCallbackProd@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:3940:21
invokeGuardedCallback@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4044:42
invokeGuardedCallbackAndCatchFirstError@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4048:36
executeDispatch@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4124:48
executeDispatchesInOrder@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:4144:26
executeDispatchesAndRelease@http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.mmm.sophia&modulesOnly=false&runModule=true:5493:35
forEach@[native code]

The emulator logs do not show any activity.


Project Files

Javascript

Click To Expand

#### `package.json`: ```json { "name": "sophia", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "start": "react-native start", "test": "jest", "lint": "eslint . --ext .js,.jsx,.ts,.tsx" }, "dependencies": { "@react-native-firebase/app": "^15.2.0", "@react-native-firebase/auth": "^15.2.0", "@react-native-firebase/functions": "^15.2.0", "@react-navigation/bottom-tabs": "^6.3.2", "@react-navigation/material-top-tabs": "^6.2.2", "@react-navigation/native": "^6.0.11", "react": "18.0.0", "react-native": "0.69.3", "react-native-pager-view": "^5.4.25", "react-native-safe-area-context": "^4.3.1", "react-native-screens": "^3.15.0", "react-native-tab-view": "^3.1.1" }, "devDependencies": { "@babel/core": "^7.12.9", "@babel/runtime": "^7.12.5", "@react-native-community/eslint-config": "^2.0.0", "@tsconfig/react-native": "^2.0.2", "@types/jest": "^26.0.23", "@types/react-native": "^0.69.3", "@types/react-test-renderer": "^18.0.0", "@typescript-eslint/eslint-plugin": "^5.29.0", "@typescript-eslint/parser": "^5.29.0", "babel-jest": "^26.6.3", "eslint": "^7.32.0", "jest": "^26.6.3", "metro-react-native-babel-preset": "^0.70.3", "react-test-renderer": "18.0.0", "typescript": "^4.4.4" }, "jest": { "preset": "react-native", "moduleFileExtensions": [ "ts", "tsx", "js", "jsx", "json", "node" ] } } ``` #### `firebase.json` for react-native-firebase v6: ```json { "firestore": { "rules": "firestore.rules", "indexes": "firestore.indexes.json" }, "functions": { "predeploy": [], "source": "functions" }, "storage": { "rules": "storage.rules" }, "emulators": { "functions": { "port": 5001 }, "firestore": { "port": 8080 }, "storage": { "port": 9199 }, "ui": { "enabled": true }, "database": { "port": 9000 } } } ```

Android

Click To Expand

#### Have you converted to AndroidX? - [ ] my application is an AndroidX application? - [ ] I am using `android/gradle.settings` `jetifier=true` for Android compatibility? - [ ] I am using the NPM package `jetifier` for react-native compatibility? #### `android/build.gradle`: ```groovy import org.apache.tools.ant.taskdefs.condition.Os // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { buildToolsVersion = "31.0.0" minSdkVersion = 21 compileSdkVersion = 31 targetSdkVersion = 31 if (System.properties['os.arch'] == "aarch64") { // For M1 Users we need to use the NDK 24 which added support for aarch64 ndkVersion = "24.0.8215888" } else { // Otherwise we default to the side-by-side NDK version from AGP. ndkVersion = "21.4.7075529" } } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle:7.1.1") classpath("com.facebook.react:react-native-gradle-plugin") classpath("de.undercouch:gradle-download-task:5.0.1") classpath 'com.google.gms:google-services:4.3.13' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { maven { // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm url("$rootDir/../node_modules/react-native/android") } maven { // Android JSC is installed from npm url("$rootDir/../node_modules/jsc-android/dist") } mavenCentral { // We don't want to fetch react-native from Maven Central as there are // older versions over there. content { excludeGroup "com.facebook.react" } } google() maven { url 'https://www.jitpack.io' } } } ``` #### `android/app/build.gradle`: ```groovy apply plugin: "com.android.application" apply plugin: 'com.google.gms.google-services' import com.android.build.OutputFile /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation. If none specified and * // "index.android.js" exists, it will be used. Otherwise "index.js" is * // default. Can be overridden with ENTRY_FILE environment variable. * entryFile: "index.android.js", * * // https://reactnative.dev/docs/performance#enable-the-ram-format * bundleCommand: "ram-bundle", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ project.ext.react = [ enableHermes: false, // clean and rebuild if changing ] apply from: "../../node_modules/react-native/react.gradle" /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'org.webkit:android-jsc:+' /** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and that value will be read here. If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */ def enableHermes = project.ext.react.get("enableHermes", false); /** * Architectures to build native code for. */ def reactNativeArchitectures() { def value = project.getProperties().get("reactNativeArchitectures") return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"] } android { ndkVersion rootProject.ext.ndkVersion compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { applicationId "com.mmm.sophia" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString() if (isNewArchitectureEnabled()) { // We configure the NDK build only if you decide to opt-in for the New Architecture. externalNativeBuild { ndkBuild { arguments "APP_PLATFORM=android-21", "APP_STL=c++_shared", "NDK_TOOLCHAIN_VERSION=clang", "GENERATED_SRC_DIR=$buildDir/generated/source", "PROJECT_BUILD_DIR=$buildDir", "REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid", "REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build", "NODE_MODULES_DIR=$rootDir/../node_modules" cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1" cppFlags "-std=c++17" // Make sure this target name is the same you specify inside the // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable. targets "sophia_appmodules" } } if (!enableSeparateBuildPerCPUArchitecture) { ndk { abiFilters (*reactNativeArchitectures()) } } } } if (isNewArchitectureEnabled()) { // We configure the NDK build only if you decide to opt-in for the New Architecture. externalNativeBuild { ndkBuild { path "$projectDir/src/main/jni/Android.mk" } } def reactAndroidProjectDir = project(':ReactAndroid').projectDir def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) { dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck") from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib") into("$buildDir/react-ndk/exported") } def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) { dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck") from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib") into("$buildDir/react-ndk/exported") } afterEvaluate { // If you wish to add a custom TurboModule or component locally, // you should uncomment this line. // preBuild.dependsOn("generateCodegenArtifactsFromSchema") preDebugBuild.dependsOn(packageReactNdkDebugLibs) preReleaseBuild.dependsOn(packageReactNdkReleaseLibs) // Due to a bug inside AGP, we have to explicitly set a dependency // between configureNdkBuild* tasks and the preBuild tasks. // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732 configureNdkBuildRelease.dependsOn(preReleaseBuild) configureNdkBuildDebug.dependsOn(preDebugBuild) reactNativeArchitectures().each { architecture -> tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure { dependsOn("preDebugBuild") } tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure { dependsOn("preReleaseBuild") } } } } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include (*reactNativeArchitectures()) } } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.debug } release { // Caution! In production, you need to generate your own keystore file. // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // https://developer.android.com/studio/build/configure-apk-splits.html // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc. def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = defaultConfig.versionCode * 1000 + versionCodes.get(abi) } } } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) //noinspection GradleDynamicVersion implementation "com.facebook.react:react-native:+" // From node_modules implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { exclude group:'com.facebook.fbjni' } debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' exclude group:'com.squareup.okhttp3', module:'okhttp' } debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' } if (enableHermes) { //noinspection GradleDynamicVersion implementation("com.facebook.react:hermes-engine:+") { // From node_modules exclude group:'com.facebook.fbjni' } } else { implementation jscFlavor } } if (isNewArchitectureEnabled()) { // If new architecture is enabled, we let you build RN from source // Otherwise we fallback to a prebuilt .aar bundled in the NPM package. // This will be applied to all the imported transtitive dependency. configurations.all { resolutionStrategy.dependencySubstitution { substitute(module("com.facebook.react:react-native")) .using(project(":ReactAndroid")) .because("On New Architecture we're building React Native from source") substitute(module("com.facebook.react:hermes-engine")) .using(project(":ReactAndroid:hermes-engine")) .because("On New Architecture we're building Hermes from source") } } } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.implementation into 'libs' } apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) def isNewArchitectureEnabled() { // To opt-in for the New Architecture, you can either: // - Set `newArchEnabled` to true inside the `gradle.properties` file // - Invoke gradle with `-newArchEnabled=true` // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true` return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true" } ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'sophia' apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' includeBuild('../node_modules/react-native-gradle-plugin') if (settings.hasProperty("newArchEnabled") && settings.newArchEnabled == "true") { include(":ReactAndroid") project(":ReactAndroid").projectDir = file('../node_modules/react-native/ReactAndroid') include(":ReactAndroid:hermes-engine") project(":ReactAndroid:hermes-engine").projectDir = file('../node_modules/react-native/ReactAndroid/hermes-engine') } ``` #### `MainApplication.java`: ```java package com.mmm.sophia; import android.app.Application; import android.content.Context; import com.facebook.react.PackageList; import com.facebook.react.ReactApplication; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactNativeHost; import com.facebook.react.ReactPackage; import com.facebook.react.config.ReactFeatureFlags; import com.facebook.soloader.SoLoader; import com.mmm.sophia.newarchitecture.MainApplicationReactNativeHost; import java.lang.reflect.InvocationTargetException; import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) { @Override public boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } @Override protected List getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for example: // packages.add(new MyReactNativePackage()); return packages; } @Override protected String getJSMainModuleName() { return "index"; } }; private final ReactNativeHost mNewArchitectureNativeHost = new MainApplicationReactNativeHost(this); @Override public ReactNativeHost getReactNativeHost() { if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { return mNewArchitectureNativeHost; } else { return mReactNativeHost; } } @Override public void onCreate() { super.onCreate(); // If you opted-in for the New Architecture, we enable the TurboModule system ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED; SoLoader.init(this, /* native exopackage */ false); initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); } /** * Loads Flipper in React Native templates. Call this in the onCreate method with something like * initializeFlipper(this, getReactNativeHost().getReactInstanceManager()); * * @param context * @param reactInstanceManager */ private static void initializeFlipper( Context context, ReactInstanceManager reactInstanceManager) { if (BuildConfig.DEBUG) { try { /* We use reflection here to pick up the class that initializes Flipper, since Flipper library is not available in release mode */ Class aClass = Class.forName("com.mmm.sophia.ReactNativeFlipper"); aClass .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class) .invoke(null, context, reactInstanceManager); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } } ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` System: OS: Windows 10 10.0.22000 CPU: (8) x64 11th Gen Intel(R) Core(TM) i7-11390H @ 3.40GHz Memory: 14.96 GB / 31.75 GB Binaries: Node: 16.16.0 - C:\Program Files\nodejs\node.EXE Yarn: Not Found npm: 8.16.0 - C:\Program Files\nodejs\npm.CMD Watchman: Not Found SDKs: Android SDK: Not Found Windows SDK: Not Found IDEs: Android Studio: AI-212.5712.43.2112.8815526 Visual Studio: Not Found Languages: Java: 18.0.1.1 - /c/Program Files/Common Files/Oracle/Java/javapath/javac npmPackages: @react-native-community/cli: Not Found react: 18.0.0 => 18.0.0 react-native: 0.69.3 => 0.69.3 react-native-windows: Not Found npmGlobalPackages: *react-native*: Not Found ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [ ] Android - [ ] **iOS** but have not tested behavior on Android - [x ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `15.2.0` - **`Firebase` module(s) you're using that has the issue:** - `functions` - **Are you using `TypeScript`?** - `Yes` & `4.4.4`


mikehardy commented 2 years ago

Hmm - what happens if you try against the android emulator? The goal with that question is to isolate if this is due to the rewrite we do for localhost (which you seem to be aware of, based on your comments...)

That definitely works for us, we exercise it in our e2e all the time (it ran as recently as yesterday I think? At most a couple days ago) - https://github.com/invertase/react-native-firebase/blob/dc7464325a315091a74027e150de1ba77190e0dd/tests/app.js#L49

(the old API, to exercise it, but both should work...)

What happens if you do adb reverse tcp:5001 tcp:5001 and leave it as localhost (or some other similar combination, to forward a port (does not have to be 5001) from the android device on to the laptop and connect it to the emulator that way?

Basically just trying to isolate network problems by hacking around it and testing other ways as I think that's going to be the heart of it

I'm certain the emulator APIs are working and turning on the emulator connection is working as I've worked with it a lot, but I do not normally work in the real-device scenario on android so I may be unaware of some networking subtlety there

Hope something in hear either helps directly or helps get you a path to an answer

victorrik commented 2 years ago

Backend Function

exports.helloWorld = functions.https.onRequest((request, response) => {
    response.status(200).send({"data":"Say hello world"});
});

you should use functions.https.onCall if you want to use the firebase library otherwise if you want to personally manage your api you can still use onRequest

mikehardy commented 2 years ago

I think the actual function source in our test suites was written 5-6 years ago and has never been modernized, I wouldn't consider it a gold standard. I use onCall in my work projects though, including with functions emulator, it does work

Fri3ndlymushroom commented 2 years ago

I have tried adb reverse tcp:5001 tcp:5001 but it doesn't seem to change anything. The android emulator actually works fine, so it must be a problem with the connection to a physical device. I still have no idea what the problem might be.

Fri3ndlymushroom commented 2 years ago

@mikehardy

Basically just trying to isolate network problems by hacking around it and testing other ways as I think that's going to be the heart of it

One thing I overlooked until now was that my metro console outputted the following:

Mapping firestore host to "10.0.2.2" for android emulators. Use real IP on real devices. You can bypass this behaviour with "android_bypass_emulator_url_remap" flag.

Is this relevant for this issue and if yes how do I use this flag?

Fri3ndlymushroom commented 2 years ago

I have now found a way to work around it.

  1. I've set the android_bypass_emulator_url_map flag to true:
    
    {
    "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
    },
    "functions": {
    "predeploy": [],
    "source": "functions"
    },
    "storage": {
    "rules": "storage.rules"
    },
    "emulators": {
    "functions": {
      "port": 5001
    },
    "firestore": {
      "port": 8080
    },
    "storage": {
      "port": 9199
    },
    "ui": {
      "enabled": true
    },
    "database": {
      "port": 9000
    }
    },
    "react-native":{
    "android_bypass_emulator_url_remap": true
    }
    }
2. I've run `adb reverse tcp:5001 tcp:5001`
3. I initialize the emulator like this:

const DEV = true

if (DEV) { functions().useEmulator("localhost", 5001); }


But is that the way it is supposed to work? Or am I missing something?
Thanks for the help until this point.

I've also changed my package.json run android script so I don't have to run `adb reverse tcp:5001 tcp:5001` every time:

"scripts": { "android": "adb reverse tcp:5001 tcp:5001 && react-native run-android", },

mikehardy commented 2 years ago

Honestly, your case of initializing to the URL of your local computer (where the functions emulator is running) like so:

functions().useEmulator("192.168.x.x", 5001);

...should have been working.

The combination you have of doing a forward, then forcing real localhost IP usage but without the remap is kind of a "brute force" workaround but is also a supported use of each of the things you are using, so it should be stable.

Why the original thing does not work, I don't know honestly - it's really surprising. But your workaround is valid

I believe the action remaining here is for someone else (could be me, as/if I have time, hopefully I will but cannot guarantee) to test on a real device to see if it reproduces and shows a real bug vs a project-specific / environment-specific issue - I'll leave it open for that

Fri3ndlymushroom commented 2 years ago

I just found out that I have a similar problem with the Auth emulator. But I can solve it as well with adb reverse.

When I type the command adb reverse --list all adb reverses are listed. What is interesting, is that by default only the firestore emulator port is reversed, and I have to reverse functions- and auth-emulators by myself. I think someone found the issue I am having for the firestore emulator and fixed it there by reversing that port, but it was not fixed for the other emulators.

mikehardy commented 2 years ago

This issue is going stale, but I wonder if it is that the emulator is not listening on 0.0.0.0? By default it does not bind to all interfaces, so tunneling is required to hit the correct interface ?

github-actions[bot] commented 1 year ago

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

Cruzor-Blade commented 1 year ago

I had a similar problem and I spent 3 days on it. I was finally able to connect the emulator to the physical device by assigning to each emulator the ip address of my computer as host. Using Ubuntu, my local ip address given by ip address command was "192.168.43.65". Edit: seems that you also need to bypass the url remap by setting android_bypass_emulator_url_remap flag to true My firebase.json file looks like

{
    ...,

    "emulators": {
        "auth": {
            "host":"192.168.43.65",
            "port": 9099
        },
        "functions": {
            "host":"192.168.43.65",
            "port": 5001
        },
        "firestore": {
            "host":"192.168.43.65",
            "port": 8080
       },
       "storage": {
            "host":"192.168.43.65",
            "port": 9199
       },
       "ui": {
          "enabled": true
       },
       "singleProjectMode": true
   },
   "react-native":{
       "android_bypass_emulator_url_remap": true
   }
}

And then, i initialized the emulators like this:

import firebaseAuth from '@react-native-firebase/auth';
import firebaseFunctions from '@react-native-firebase/functions';

const auth = firebaseAuth();
const functions = firebaseFunctions();

const deviceIp = "192.168.43.65";
auth.useEmulator(`http://${deviceIp}:9099`);
functions.useEmulator(deviceIp, 5001);

export {auth, functions};
AmitDigga commented 1 year ago

No luck @Cruzor-Blade . When i am logging in with phone, no otp codes are displayed on firebase emulator. This login flow was working fine on android emulator.

React Native

if (__DEV__) {
    const deviceIp = "172.20.10.5";
    firebase.database().useEmulator(deviceIp, 9000);
    firebase.firestore().useEmulator(deviceIp, 8080);
    firebase.auth().useEmulator(`http://${deviceIp}:9099`);
    firebase.functions().useEmulator(deviceIp, 5001);
    firebase.storage().useEmulator(deviceIp, 9199);
}

firebase.json

"emulators": {
    "auth": {
      "host": "172.20.10.5",
      "port": 9099
    },
    "functions": {
      "host": "172.20.10.5",
      "port": 5001
    },
    "firestore": {
      "host": "172.20.10.5",
      "port": 8080
    },
    "database": {
      "host": "172.20.10.5",
      "port": 9000
    },
    "storage": {
      "host": "172.20.10.5",
      "port": 9199
    },
    "eventarc": {
      "host": "172.20.10.5",
      "port": 9299
    },
    "pubsub": {
      "host": "172.20.10.5",
      "port": 8085
    },
    "ui": {
      "enabled": true
    },
    "singleProjectMode": true
  },
  "react-native": {
    "android_bypass_emulator_url_remap": true
  },
  "remoteconfig": {
    "template": "remoteconfig.template.json"
  }
HERYORDEJY commented 1 year ago

@AmitDigga have you been able to make it work on a physical device?

AmitDigga commented 1 year ago

@HERYORDEJY-DEV No, i gave up after trying full day.

mikehardy commented 1 year ago

Not sure if this helps but currently I'm running most of my testing (including the firebase emulator) in an OSX-KVM VM, with port forwards back and forth from that to an android emulator running on my bare metal host. This may be roughly analogous to the solution desired here as there are multiple network hops in the way, but it does work for me.

I use these aliases in order to forward things back and forth, localhost port 2023 on the bare metal host (which has the emulator) is an SSH session that forwards to the OSX-KVM instance where the firebase emulator is running.

This note is what I refer to bring things up after a reboot or whatever, with explanation as well as the aliases I use and what they contain:


1. start "standard-Xconfig.xlaunch" from windows desktop

2. allow OSX-KVM to be accessed through WSL by host
  - on osxvm run `sshmitm`
  - osxkvm bash alias for `ssh -R 2023:localhost:22 10.0.2.2` (or similar) so you can use VSCode remote-ssh to localhost:2023 and connect to it

3. Get ADB working from macOS to host android emulator
  - on host run `Connect-ADB-OSX`
  - host powershell alias for `adb kill-server` and `adb -a -P 5037 nodaemon server start`

4. start an emulator
  -  on host run `Start-Andemu`
  - host powershell alias for `emulator -avd TestingAVD`)
  - run adb devices -l to make sure control port is 5554 like other aliases expect. It should be if you only have one emulator up
  - If you need a new ADB key, `telnet.exe localhost 5554` to generate the control port auth token
  - copy the auth token via `scp -p 2023 ${env:HOMEPATH}\.emulator_console_auth_token localhost:`

5. Forward emulator ports (react-native packager, detox control port, ADB ports) for testing
  - on host run `Connect-Andemu-OSX`
  - host powershell alias for `ssh -R -L 60994:localhost:60994 -L 8081:localhost:8081 5037:127.0.0.1:5037 -R 5554:127.0.0.1:5554 -p 2023 localhost`
  - in OSX-KVM `adb devices -l` should now list android host emulator

6.  Forward firebase emulator ports
  - on host run `Connect-Firebase-Emulator-OSX`
  - host powershell alias for `ssh -L 4000:localhost:4000 -L 4400:localhost:4400 -L 4500:localhost:4500 -L 5001:localhost:5001 -L 8080:localhost:8080 -L 9000:localhost:9000 -L 9099:localhost:9099 -L 9150:localhost:9150 -L 9199:localhost:9199 -p 2023 localhost`
  - ```
AkbarBakhshi commented 9 months ago

I had a similar problem and I spent 3 days on it. I was finally able to connect the emulator to the physical device by assigning to each emulator the ip address of my computer as host. Using Ubuntu, my local ip address given by ip address command was "192.168.43.65". Edit: seems that you also need to bypass the url remap by setting android_bypass_emulator_url_remap flag to true My firebase.json file looks like

{
    ...,

    "emulators": {
        "auth": {
            "host":"192.168.43.65",
            "port": 9099
        },
        "functions": {
            "host":"192.168.43.65",
            "port": 5001
        },
        "firestore": {
            "host":"192.168.43.65",
            "port": 8080
       },
       "storage": {
            "host":"192.168.43.65",
            "port": 9199
       },
       "ui": {
          "enabled": true
       },
       "singleProjectMode": true
   },
   "react-native":{
       "android_bypass_emulator_url_remap": true
   }
}

And then, i initialized the emulators like this:

import firebaseAuth from '@react-native-firebase/auth';
import firebaseFunctions from '@react-native-firebase/functions';

const auth = firebaseAuth();
const functions = firebaseFunctions();

const deviceIp = "192.168.43.65";
auth.useEmulator(`http://${deviceIp}:9099`);
functions.useEmulator(deviceIp, 5001);

export {auth, functions};

Hey. I tried your way and it is working now on my physical iOS device. Just to be sure, after I am done with testing locally and about to push my firebase functions to the cloud, should I revert the changes I made to the firebase.json file (adding host ip and "android_bypass_emulator_url_remap": true ?

SethCram commented 8 months ago

This post was a lifesaver. I couldn't get the emulator connected even to my device in Android Simulator before hardcoding my personal ip address.

SethCram commented 6 months ago

Nevermind, my public ip address has now changed and the hardcoded ip method no longer works with the new one