Firebase cloud functions / One works, other (same function) not works - google-cloud-functions

I am very nervous.. I can't test normally firebase cloud functions, because a lot of things don't work. I tested it, I copied same function with a different name, the new function don't work.
Why????
Why working helloworld and why not working tryhello???
cloud functions nodejs index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
exports.tryHello = functions.https.onCall((data, context) => {
let dataexample = {
name: 'examplename',
state: 'examplestate',
country: 'examplecountry'
};
let setDoc = db.collection('newexample').doc(data.text).set(dataexample);
return { text : "success. uid:" + context.auth.uid }
});
exports.helloWorld = functions.https.onCall((data, context) => {
let dataexample = {
name: 'examplename',
state: 'examplestate',
country: 'examplecountry'
};
let setDoc = db.collection('newexample').doc(data.text).set(dataexample);
return { text : "success. uid:" + context.auth.uid }
});
Unity C#:
public void testbutton()
{
var data = new Dictionary<string, object>();
data["text"] = "example";
//I tested "tryHello" and helloWorld"
FirebaseFunctions.DefaultInstance.GetHttpsCallable("tryHello")
.CallAsync(data).ContinueWith((task) =>
{
if (task.IsFaulted)
{
// Handle the error...
print("error");
}
else if (task.IsCompleted)
{
IDictionary snapshot = (IDictionary)task.Result.Data;
print("Result: " + snapshot["text"]);
}
}
Result:
1. First, I write unity: GetHttpsCallable("helloWorld") and save.
I start game, login, then I click testbutton.
result: firebase console: success create example collection, example document, country:examplecountry, name:examplename, state:examplestate. Ok good.
unity log:
1. User signed in successfully: Jane Q. User (qQC3wEOU95eDFw8UuBjb0O1o20G2)
UnityEngine.Debug:LogFormat(String, Object[])
loginfire:b__10_0(Task1) (at Assets/loginfire.cs:155)
2. Result: success. uid:qQC3wEOU95eDFw8UuBjb0O1o20G2
UnityEngine.MonoBehaviour:print(Object)
<>c:<testbutton>b__16_0(Task1) (at Assets/loginfire.cs:411)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()
cloud functions "helloWorld" log:
Function execution started
Function execution took 3020 ms, finished with status code: 200
Ok. I delete "example" collection in firebase console.
2. Second, I write unity: GetHttpsCallable("tryHello") and save.
I start game, login, then I click testbutton.
result: not create collection.
unity log:
*1. User signed in successfully: Jane Q. User (qQC3wEOU95eDFw8UuBjb0O1o20G2)
UnityEngine.Debug:LogFormat(String, Object[])
loginfire:b__10_0(Task`1) (at Assets/loginfire.cs:155)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()
error
UnityEngine.MonoBehaviour:print(Object)
<>c:b__16_0(Task`1) (at Assets/loginfire.cs:396)
System.Threading._ThreadPoolWaitCallback:PerformWaitCallback()*
cloud functions "tryHello" log:
nothing...
Why?
I don't understand. same, only the name is different!
And.. in many cases it show success but still does not update the database. or just much later. why? Lately, "helloWorld" also often writes an error, if I don't press the testbutton immediately after logging in, it can't read the uid.
I start to get tired of the system right from the start.
Thanks..

Solved!
I needed it configured to cloud console "tryHello" permission settings. (Not same helloworld settings.)
Lately, "helloWorld" also often writes an error, if I don't press the testbutton immediately after logging in, it can't read the uid.
-> I needed declared Firebasauth within testbutton().
Sorry for the question, thanks.

Related

Github Actions: Build Failing for NEXT JS PWA App

I have set up Unit tests to be run before pushing to the main branch via GitHub-actions. All the Unit tests are running successfully but for some reason during the build:
Ran all test suites.
info - Checking validity of types...
info - Creating an optimized production build...
warn - using beta Middleware (not covered by semver)
After this step, it fails with the error:
> Build error occurred
Error: Service account object must contain a string "project_id" property.
This error comes from the Firebase Admin SDK Configuration file as shown below:
import admin from 'firebase-admin';
const keyString = process.env.FB_ADMIN_PRIVATE_KEY ?? '{"privateKey": ""}';
const { privateKey } = JSON.parse(keyString);
if (privateKey === '') {
console.log('FIREBASE_PRIVATE_KEY is not set');
if (process.env.NODE_ENV === 'development')
throw new Error('FIREBASE_PRIVATE_KEY is not set');
else console.log('Firebase Private Key Error');
}
if (admin.apps.length === 0)
admin.initializeApp({
credential: admin.credential.cert({
clientEmail: process.env.FB_ADMIN_CLIENT_EMAIL,
privateKey: privateKey,
projectId: process.env.NEXT_PUBLIC_FB_CLIENT_PROJECT_ID,
}),
databaseURL: process.env.FB_ADMIN_RTDB_URL,
});
const db = admin.firestore();
const auth = admin.auth();
const storage = admin.storage();
const rdb = admin.database();
const Server = { auth, db, storage, rdb };
export default Server;
However, I am not sure why is this method even called? Since I have my .env secrets stored in the local, the build seems to succeed there and fail in Github actions. What should I do to resolve this error?
Since NEXT JS Generates static pages and so I was using Admin SDK to fetch some metadata at the server-side and that's why the function was triggered causing it to fail in Github Actions, seems like the only way out here will be to somehow mock the data in order for the actions to run smoothly.

Throwing newUserError in getData() function

I am currently building a data connector but would like to throw and error out to the user if the date range they have provided is not supported by my API endpoint (we don't have data for more than 90 days). I looked through the documentation and found this: https://developers.google.com/datastudio/connector/error-handling#user-facing-errors
And copied the code example exactly and tried to run it but my project still isn't showing the error dialog box back to the user.
I've also taken a look at how other people implement this in this repository (https://github.com/googledatastudio/community-connectors) but still can't see an issue with what I wrote.
function getData(request) {
try {
var dataSchema = getDataSchema(request);
var data = lookupRequestData(request, dataSchema);
} catch (e) {
console.log('pre throw');
// throw Error('some error!');
cc.newUserError()
.setDebugText('Error fetching data from API. Exception details: ' + e)
.setText('There was an error communicating with the service. Try again later, or file an issue if this error persists.')
.throwException();
console.log('post throw');
}
return {
schema: dataSchema,
rows: data
};
}
I can see both the pre throw and post throw strings in my log but there is still no error message being displayed. Just wondering if someone might be able to offer a bit of advice for other things to try.
Thanks

Cloud Functions for Firebase Could not handle the request after a successful request

TLDR: After writing a JSON (successfully) to my Firestore, the next request will give me Internal Server Error (500). I have a suspicion that the problem is that inserting is not yet complete.
So basically, I have this code:
const jsonToDb = express();
exports.jsondb = functions.region('europe-west1').https.onRequest(jsonToDb);
jsonToDb.post('', (req, res) => {
let doc;
try {
doc = JSON.parse(req.body);
} catch(error) {
res.status(400).send(error.toString()).end();
return;
}
myDbFuncs.saveMyDoc(doc);
res.status(201).send("OK").end();
}
The database functions are in another JS file.
module.exports.saveMyDoc = function (myDoc) {
let newDoc = db.collection('insertedDocs').doc(new Date().toISOString());
newDoc.set(myDoc).then().catch();
return;
};
So I have several theories, maybe one of them is not wrong, but please help me with this. (Also if I made some mistakes in this little snippet, just tell me.)
Reproduction:
I send the first request => everything is OK, Json in the database.
I send a second request after the first request give me OK status => it does not do anything for a few secs, then 500: Internal Server Error.
Logs: Function execution took 4345 ms, finished with status: 'connection error'.
I just don't understand. Let's imagine I'm using this as an API, several requests simultaneously. Can't it handle? (I suppose it can handle, just I do something stupid.) Deliberately, I'm sending the second request after the first has finished and this occurs.
Should I make the saveMyDoc async?
saveMyDoc isn't returning a promise that resolves when all the async work is complete. If you lose track of a promise, Cloud Functions will shut down the work and clean up before the work is complete, making it look like it simply doesn't work. You should only send a response from an HTTP type function after all the work is fully complete.
Minimally, it should look more like this:
module.exports.saveMyDoc = function (myDoc) {
let newDoc = db.collection('insertedDocs').doc(new Date().toISOString());
return newDoc.set(myDoc);
};
Then you would use the promise in your main function:
myDbFuncs.saveMyDoc(doc).then(() => {
res.status(201).send("OK").end();
}
See how the response is only sent after the data is saved.
Read more about async programming in Cloud Functions in the documentation. Also watch this video series that talks about working with promises in Cloud Functions.

web3.eth.accounts.create method doesn't actually create new account

I try to create an eth account via RPC in private network.
What I have done so far are:
launch geth node and create private network.
create simple javascript program using web3 1.0.0, typescript
run and get result as below but the account isn't created
Code:
const result = await web3.eth.personal.unlockAccount(senderId, senderPassword, duration)
if (result === true) {
// const newAccountResult = await web3.eth.personal.newAccount('password')
const newAccountResult = await web3.eth.accounts.create('user01')
console.log(newAccountResult)
}
Result:
web3.eth.accounts.create returns the following result
{ address: '0xf10105f862C1cB10550F4EeB38697308c7A290Fc',
privateKey: '0x5cba6b397fc8a96d006988388553ec17a000f7da9783d906979a2e1c482e7fcb',
signTransaction: [Function: signTransaction],
sign: [Function: sign],
encrypt: [Function: encrypt] }
But web3.eth.getAccounts method returns only 1 account.
[ '0xaf0034c41928Db81E570061c58c249f61CFF57f2' ]
Seems web3.eth.accounts.create method has succeeded as the result includes account address and private key.
But I don't understand why web3.eth.getAccounts method doesn't include the created account.
I also checked geth via console, the result is same.
> eth.accounts
["0xaf0034c41928db81e570061c58c249f61cff57f2"]
And eth.personal.newAccount didn't work.
Do I need to do something after web3.eth.accounts.create?
I appreciate any help.
If i got it right, web.eth.accounts.create is a way to create accounts without storing them on the local node, so its basically a way to get a valid keypair on-the-fly without storing anything on the keystore)
web3.eth.personal.newAccount() should be availabel if you have the personal-API activated on your geth node (which is default behavior for ganache, with geth you need to activate it via geth --dev/testnet --rpc --rpcapi eth,web3,personal (note: of course you should be very careful with allowing personal-API on mainnet, make sure that RPC access is restricted so only you/privileged users can access it)
(async () => {
let newAccount = await web3.eth.personal.newAccount();
console.log(newAccount);
let accounts = await web3.eth.getAccounts();
console.log(accounts);
})();
Should give something like
0xb71DCf0191E2B90efCD2638781DE40797895De66
[
...
'0xb71DCf0191E2B90efCD2638781DE40797895De66' ]
Refs https://medium.com/#andthentherewere0/should-i-use-web3-eth-accounts-or-web3-eth-personal-for-account-creation-15eded74d0eb

RxSwift observable error stops chain - Web services with Rx, how to recover?

obviously I am new to RxSwift and though I consumed a lot of documentations and speeches, I think I am missing some fundamental concepts.
In my app I have a RESTful web service to load various resources but the base url of the web service is unknown at build/start time. Instead I have a "URL resolver" web service which I can call with my apps bundle, version and possible environment ("production", "debug" or any custom string entered in the apps debug settings) to obtain the base url I then use for the actual service.
My thinking was that I would create 2 services, one for the URL resolver and one for the actual web service which gives me my resources. The URL resolver would have a Variable and a Observable. I use the variable to signal the need to refresh the base url via a web service call to the URL resolver. I do this by observing the variable and filter only for true values. A function in the service class set the variables value to true (initially it is false) and inside an observer of the filtered variable, I make the web service call in another Observable (this example uses a dummy JSON web service):
import Foundation
import RxSwift
import Alamofire
struct BaseURL: Codable {
let title: String
}
struct URLService {
private static var counter = 0
private static let urlVariable: Variable<Bool> = Variable(false)
static let urlObservable: Observable<BaseURL> = urlVariable.asObservable()
.filter { counter += 1; return $0 }
.flatMap { _ in
return Observable.create { observer in
let url = counter < 5 ? "https://jsonplaceholder.typicode.com/posts" : ""
let requestReference = Alamofire.request(url).responseJSON { response in
do {
let items = try JSONDecoder().decode([BaseURL].self, from: response.data!)
observer.onNext(items[0])
} catch {
observer.onError(error)
}
}
return Disposables.create() {
requestReference.cancel()
}
}
}
static func getBaseUrl() {
urlVariable.value = true;
}
static func reset() {
counter = 0;
}
}
Now the problem is that sometimes it can happen that a web service call fails and I would need to show the error to the user so a retry can be made. I thought that the onError was useful for this but it seems to kills all the subscribers forever.
I could put the subscribing in its own function and inside the error handler of the Observer, I could show a alert and then call the subscribe function again like so:
func subscribe() {
URLService.urlObservable.subscribe(onNext: { (baseURL) in
let alert = UIAlertController(title: "Success in Web Service", message: "Base URL is \(baseURL.title)", preferredStyle: .alert)
let actionYes = UIAlertAction(title: "Try again!", style: .default, handler: { action in
URLService.getBaseUrl()
})
alert.addAction(actionYes)
DispatchQueue.main.async {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1;
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert, animated: true, completion: nil)
}
}, onError: { error in
let alert = UIAlertController(title: "Error in Web Service", message: "Something went wrong: \(error.localizedDescription)", preferredStyle: .alert)
let actionYes = UIAlertAction(title: "Yes", style: .default, handler: { action in
URLService.reset()
self.subscribe()
})
alert.addAction(actionYes)
DispatchQueue.main.async {
VesselService.reset()
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1;
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(alert, animated: true, completion: nil)
}
}).disposed(by: disposeBag)
}
Then in my AppDelegate I would call
subscribe()
URLService.getBaseUrl()
The problem is that all other observers get killed on an error as well but since the the only other observer on the URLService.urlObservable is my other web service class, I guess I could implement the same style subscribe function in there as well.
I read that some people suggest to return a Result enum which has 2 cases: the actual result (.success(result: T)) or an error (.error(error: Error)).
So what is the better way of handling errors web service errors in Rx? I cant wrap my head around this problem and I'm trying for 2 days to understand it. Any ideas or suggestions?
Update
It just came to my mind that I could ignore errors from the web service calls completely and instead post any error to a global "error" variable which my app delegate could observe to show alerts. The "error" could reference the function which initially caused it so a retry could be made. I'm still confused and not sure what I should do. :/
Update 2
I think I might found a working solution. As I am still a beginner to Rx and RxSwift, I'm happy to take improvement suggestions. As I was writing the actual code, I splitted my call chain in two parts:
The part where I make the web service calls
The part where I click a button and process the result of the web service, whether it is an error or a success
In the part where I click the button and process the result, I use catchError and retry as suggested in the comments. The code looks like this:
let userObservable = URLService
.getBaseUrl(environment: UserDefaults.standard.environment) //Get base url from web service 1
.flatMap({ [unowned self] baseURL -> Observable<User> in
UserService.getUser(baseURL: baseURL,
email: self.usernameTextField.text!,
password: self.passwordTextField.text!) //Get user from web service 2 using the base url from webservice 1
})
signInButton
.rx
.tap
.throttle(0.5, scheduler: MainScheduler.instance)
.flatMap({ [unowned self] () -> Observable<()> in
Observable.create { observable in
let hud = MBProgressHUD.present(withTitle: "Signing in...");
self.hud = hud
observable.onNext(())
return Disposables.create {
hud?.dismiss()
}
}
})
.flatMap({ () -> Observable<User> in
return userObservable
})
.catchError({ [unowned self] error -> Observable<User> in
self.hud?.dismiss()
self.handleError(error)
return userObservable
})
.retry()
.subscribe(onNext: { [unowned self] (user) in
UserDefaults.standard.accessToken = user.accessToken
UserDefaults.standard.tokenType = user.tokenType
self.hud?.dismiss()
})
.disposed(by: disposeBag)
The trick was to move the call to the two web services out of the cain into their own variable so I can re-call it at any time. When I now return the "userObservable" and an error happens during the web service call, I can show the error in the catchError and return the same "userObservable" for the next retry.
At the moment this only properly handles errors when they occur in the web service call chain so I think I should make the button tap a driver.
Okay so for everyone who comes here, you probably have a lack of understanding or a misconception of how the Rx world is supposed to work. I still find it sometimes confusing but I found a way better solution than what I posted in my original question.
In Rx, a error "kills" or rather completes all observers in the chain and that is actually a good thing. If there are expected errors like API error in web service calls, you should either try to handle them where they occur or treat them like expected values.
For example, your observer could return a optional type and subscribers could filter for the existence of values. If an error in the API call occurs, return nil. Other "error handlers" could filter for nil values to display error messages to the user.
Also viable is to return a Result enum with two cases: .success(value: T) and .error(error: Error). You treat the error as a acceptable result and the observer is responsible for checking if it should display a error message or the success result value.
Yet another option, which surely is not the best as well but works it to simply nest the call which you expect to fail inside the subscriber of the call which must not be affected. In my case that is a button tap which causes a call to a web service.
The "Update 2" of my original post would become:
signInButton.rx.tap.throttle(0.5, scheduler: MainScheduler.instance)
.subscribe(onNext: { [unowned self] () in
log.debug("Trying to sign user in. Presenting HUD")
self.hud = MBProgressHUD.present(withTitle: "Signing in...");
self.viewModel.signIn()
.subscribe(onNext: { [unowned self] user in
log.debug("User signed in successfully. Dismissing HUD")
self.hud?.dismiss()
}, onError: { [unowned self] error in
log.error("Failed to sign user in. Dismissing HUD and presenting error: \(error)")
self.hud?.dismiss()
self.handleError(error)
}).disposed(by: self.disposeBag)
}).disposed(by: self.disposeBag)
The MVVM view model makes the calls to the web serivces like so:
func signIn() -> Observable<User> {
log.debug("HUD presented. Loading BaseURL to sign in User")
return URLService.getBaseUrl(environment: UserDefaults.standard.environment)
.flatMap { [unowned self] baseURL -> Observable<BaseURL> in
log.debug("BaseURL loaded. Checking if special env is used.")
if let specialEnv = baseURL.users[self.username.value] {
log.debug("Special env is used. Reloading BaseURL")
UserDefaults.standard.environment = specialEnv
return URLService.getBaseUrl(environment: specialEnv)
} else {
log.debug("Current env is used. Returning BaseURL")
return Observable.just(baseURL)
}
}
.flatMap { [unowned self] baseURL -> Observable<User> in
log.debug("BaseURL to use is: \(baseURL.url). Now signing in User.")
let getUser = UserService.getUser(baseURL: baseURL.url, email: self.username.value, password: self.password.value).share()
getUser.subscribe(onError: { error in
UserDefaults.standard.environment = nil
}).disposed(by: self.disposeBag)
return getUser
}
.map{ user in
UserDefaults.standard.accessToken = user.accessToken
UserDefaults.standard.tokenType = user.tokenType
return user
}
}
First I was thinking to only call the view models signIn() function when pressing the button but since there should be no UI code in the view model, I figured that presenting and dismissing the HUD is the responsibility of the ViewController.
I think this design is now pretty solid. The button observer never completes and can continue to send events forever. Earlier, if there was a second error, it might happen that the button observer died and my logs showed that the userObservable was executed twice, which must also not be happen.
I just wonder if there is a better way then nesting the subscribers.