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.71k stars 2.22k forks source link

[πŸ›][πŸ”₯] HttpsCallable returning NOT_FOUND on Android only #6001

Closed evil0sheep closed 2 years ago

evil0sheep commented 2 years ago

Issue

this is using the firebase emulator, haven't tested in production

This is where i initialize functions:

if (__DEV__) {
   console.log('Running in __DEV__ mode');
  const emulatorUrl = Platform.OS === "android" ? 'http://10.0.2.2' : 'http://localhost';
  const authPort = ':9099';
  const functionsPort = ':5001'
  const authUrl = emulatorUrl + authPort
  const funcUrl = emulatorUrl + functionsPort
  console.log(`auth().useEmulator(${authUrl});`);
  console.log(`functions().useFunctionsEmulator(${funcUrl});`);

  auth().useEmulator(authUrl);
  functions().useFunctionsEmulator(funcUrl);
 }

This is where i make the call:

 functions().httpsCallable('getOffsetCostParams')()
  .then((response) => setOffsetCostParams(response.data))
  .catch((error) => {
    console.error(error); // Prints Error: NOT_FOUND on android only
  });

Project Files


Javascript

Click To Expand

#### `package.json`: ```json { "name": "decarbify", "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 ." }, "dependencies": { "@react-native-community/slider": "^4.1.12", "@react-native-firebase/app": "^14.2.1", "@react-native-firebase/auth": "^14.2.1", "@react-native-firebase/functions": "14.2.1", "jsesc": "^3.0.2", "react": "17.0.2", "react-dom": "17.0.1", "react-native": "^0.66.4", "react-native-camera": "^4.2.1", "react-native-stripe-checkout-webview": "^0.0.13", "react-native-view-shot": "^3.1.2", "react-native-web": "0.17.1", "react-native-webview": "11.13.0", "regjsparser": "^0.8.2" }, "devDependencies": { "@babel/core": "^7.12.9", "@babel/runtime": "^7.12.5", "@react-native-community/eslint-config": "^2.0.0", "babel-jest": "^26.6.3", "eslint": "^7.32.0", "jest": "^26.6.3", "metro-config": "^0.66.2", "metro-react-native-babel-preset": "^0.66.2", "react-test-renderer": "17.0.2" }, "jest": { "preset": "react-native" } } ``` #### `firebase.json` for react-native-firebase v6: ```json # N/A ```

iOS

Click To Expand

#### `ios/Podfile`: - [ ] I'm not using Pods - [x] I'm using Pods and my Podfile looks like: ```ruby require_relative '../node_modules/react-native/scripts/react_native_pods' require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' platform :ios, '11.0' target 'decarbify' do config = use_native_modules! use_react_native!( :path => config[:reactNativePath], # to enable hermes on iOS, change `false` to `true` and then install pods :hermes_enabled => false ) target 'decarbifyTests' do inherit! :complete # Pods for testing end # Enables Flipper. # # Note that if you have use_frameworks! enabled, Flipper will not work and # you should disable the next line. use_flipper!() post_install do |installer| react_native_post_install(installer) __apply_Xcode_12_5_M1_post_install_workaround(installer) end end ``` #### `AppDelegate.m`: ```objc // N/A ```


Android

Click To Expand

#### Have you converted to AndroidX? - [x] my application is an AndroidX application? - [x] 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 // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext { buildToolsVersion = "30.0.2" minSdkVersion = 21 compileSdkVersion = 30 targetSdkVersion = 30 ndkVersion = "21.4.7075529" } repositories { google() mavenCentral() } dependencies { classpath("com.android.tools.build:gradle:4.2.2") // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath 'com.google.gms:google-services:4.3.10' // Google Services plugin } } allprojects { repositories { mavenCentral() mavenLocal() 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") } google() maven { url 'https://www.jitpack.io' } } } ``` #### `android/app/build.gradle`: ```groovy apply plugin: "com.android.application" apply plugin: 'com.google.gms.google-services' // Google Services plugin 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 mirrored 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 in debug. */ def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures") android { ndkVersion rootProject.ext.ndkVersion compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { applicationId "com.decarbify" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 1 versionName "1.0" // https://github.com/react-native-camera/react-native-camera/blob/master/docs/installation.md#android---other-required-steps missingDimensionStrategy 'react-native-camera', 'general' // <--- insert this line } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } } buildTypes { debug { signingConfig signingConfigs.debug if (nativeArchitectures) { ndk { abiFilters nativeArchitectures.split(',') } } } 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) { def hermesPath = "../../node_modules/hermes-engine/android/"; debugImplementation files(hermesPath + "hermes-debug.aar") releaseImplementation files(hermesPath + "hermes-release.aar") } else { implementation jscFlavor } // ... // Import the Firebase BoM implementation platform('com.google.firebase:firebase-bom:29.0.3') // When using the BoM, you don't specify versions in Firebase library dependencies // Declare the dependency for the Firebase SDK for Google Analytics implementation 'com.google.firebase:firebase-analytics' // Declare the dependencies for any other desired Firebase products // For example, declare the dependencies for Firebase Authentication and Cloud Firestore implementation 'com.google.firebase:firebase-auth' implementation 'com.google.firebase:firebase-firestore' } // 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) ``` #### `android/settings.gradle`: ```groovy rootProject.name = 'decarbify' apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings) include ':app' ``` #### `MainApplication.java`: ```java // N/A ``` #### `AndroidManifest.xml`: ```xml ```


Environment

Click To Expand

**`react-native info` output:** ``` info Fetching system and libraries information... System: OS: macOS 11.2.1 CPU: (8) x64 Intel(R) Core(TM) i7-7920HQ CPU @ 3.10GHz Memory: 501.66 MB / 16.00 GB Shell: 3.2.57 - /bin/bash Binaries: Node: 12.16.2 - /usr/local/bin/node Yarn: 1.22.10 - /usr/local/bin/yarn npm: 6.14.4 - /usr/local/bin/npm Watchman: 4.9.0 - /usr/local/bin/watchman Managers: CocoaPods: 1.11.2 - /usr/local/bin/pod SDKs: iOS SDK: Platforms: iOS 14.5, DriverKit 20.4, macOS 11.3, tvOS 14.5, watchOS 7.4 Android SDK: API Levels: 29, 30 Build Tools: 30.0.2, 30.0.3 System Images: android-29 | Intel x86 Atom, android-29 | Intel x86 Atom_64, android-29 | Google APIs Intel x86 Atom, android-29 | Google APIs Intel x86 Atom_64, android-29 | Google Play Intel x86 Atom, android-29 | Google Play Intel x86 Atom_64, android-30 | Google APIs Intel x86 Atom Android NDK: Not Found IDEs: Android Studio: 2020.3 AI-203.7717.56.2031.7935034 Xcode: 12.5.1/12E507 - /usr/bin/xcodebuild Languages: Java: 1.8.0_312 - /usr/bin/javac npmPackages: @react-native-community/cli: Not Found react: 17.0.2 => 17.0.2 react-native: ^0.66.4 => 0.66.4 react-native-macos: Not Found npmGlobalPackages: *react-native*: Not Found ``` - **Platform that you're experiencing the issue on**: - [ ] iOS - [x] Android - [ ] **iOS** but have not tested behavior on Android - [ ] **Android** but have not tested behavior on iOS - [ ] Both - **`react-native-firebase` version you're using that has this issue:** - `14.2.1` - **`Firebase` module(s) you're using that has the issue:** - `@react-native-firebase/functions` - **Are you using `TypeScript`?** - `N`


mikehardy commented 2 years ago

Hi there! Your emulator usage calls look buggy to me, with unbalanced interpolation backticks, also you don't have to do the 10.0.2.2/localhost mapping we do that as a DX convenience internally. Why not just do what we do in our e2e test harness which uses the functions emulator successfully since I introduced #5945 ?

https://github.com/invertase/react-native-firebase/blob/f6b90531c5e705d62e8905e519810bac2f76bb22/tests/app.js#L54

The functions emulator works for us here in our e2e ci tests plus on my local projects correctly both ios and android, curious if just simply calling it the way we do will work for you?

evil0sheep commented 2 years ago

Hi Mike,

Thanks for the prompt reply! Changing it to 'http://localhost:5001' on android does not solve the problem for me, but good to know that i can do that :) I don't understand what youre saying about string interpolation, the backticks look matched to me and I'm only using interpolation for the log statements anyway, the string passed to useFunctionsEmulator is concatenated, but just to be sure I hardcoded 'http://localhost:5001' as per the example you gave but no dice.

Its not surprising to me that this works on your CI, I kindof suspect some sort of configuration error or package versioning error on my side. I know its not completely local to my machine because my friend whos working on this project with me was able to reproduce the issue on his machine, so the problem is in some file in our git repository.

I was wondering if you could shed some light on what this error represents and where it would originate from so I can try to dig into it further on my machine? I see that NOT_FOUND is a valid FirebaseFunctionException Code does that mean this is originating from inside the android firebase library? If so do you know where in RNFirebase that error would be returned so i can start debugging there? I'm a little unclear about how the javascript HttpsCallable wires up to the android stuff.

Another question: what differences are there between the way auth connects to the emulator vs how functions connect to the emulator? it seems really weird to me that auth is working but functions are not. Do i need special permissions for these different ports or something?

I know you probably cant debug this for me without reproducing it but I was wondering if you could point me in the right direction at least? or if I provide you with a zip archive of our source can you attempt to reproduce it?

Thanks so much!

mikehardy commented 2 years ago

I'm sorry, I just don't know what could be causing this. I can only debug problems that are demonstrably in the module, for example following the general philosophy of https://stackoverflow.com/help/minimal-reproducible-example and I provide this https://github.com/mikehardy/rnfbdemo/blob/master/make-demo.sh as a scaffolding builder for folks so they can just create one simple tiny App.js (+ index.js if needed) and if they say it runs in a scaffold built from my demo creation script, I know I can debug.

The code isn't too hard to follow in node_modules if you dig in, I encourage you to try that as a next step

evil0sheep commented 2 years ago

Ok I understand. While shotgunning logs into java files in my node_modules the android build gave me this:

ReactNativeFirebase WARNING: NPM package '@react-native-firebase/functions' depends on '@react-native-firebase/app' v14.2.1 but found v14.2.2, this might cause build issues or runtime crashes.

which looks mighty suspicious. All rnfirebase packages are set to 14.2.1 in my pakcges.json. I tried removing my node_modules and yarn start --reset-cache but the error persists. Have you ever run across anything like this before?

evil0sheep commented 2 years ago

hm bumped all packages to 14.2.2 and the dependency error went away but original problem persists so looks unrelated

evil0sheep commented 2 years ago

Ok so i finally figured this out and wanted to post for posterity in case someone else ran across this. The problem was that i had overwritten my android/app/google-services.json to point at a new firebase project, but for some reason the old app string was persisting in some generated artifacts in my android/app/build, and I had to rm -rf android/app/build and redo npx react-native run-android in order for it to work.

I found this by watching the firebase emulator log while i triggered the failing function with tail -f firebase/firebase-debug.log (where firebase/functions is the directory where the cloud functions live) which showed me the following:

[debug] [2022-01-10T04:44:22.741Z] Functions emulator received unknown request at path /test-project-c85d7/us-central1/getOffsetCostParams

Where test-project-c85d7 was the name of the project in the android/app/google-services.json I had overwritten. Grepping my project with grep -r "test-project-c85d7" . returned multiple hits in android/app/build, despite no hits outside that directory. rm -rf android/app/build and then restarting everything fixed the issue for me.

mikehardy commented 2 years ago

Oh that is subtle, how frustrating!! Thanks for posting it. This may help you in the future - I use npx react-native-clean-project as part of my CI process because it does what it says it does (including cleaning android build). Also, when I run in to problems that are just weird like this, I use it (it is is built in to one of my package.json run scirpts) because even though it is expensive to destroy all the local caching, it's cheaper than pursuing an issue with a library or something, so it's a first step before opening an issue, for me. Saves my time quite a bit! Glad you got it figured out and good luck with your project