facebook twitter hatena line email

「Gcp/Firebase/CloudFunctions/基本」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(Blaze 従量プラン)
(authenticationのログイン日取得)
 
(同じ利用者による、間の44版が非表示)
行8: 行8:
 
[[Javascript/nodejs/インストール/nvm]] [ショートカット]
 
[[Javascript/nodejs/インストール/nvm]] [ショートカット]
  
===firebaseログイン===
+
===firebaseツールインストール===
 
  $ npm install -g firebase-tools
 
  $ npm install -g firebase-tools
 
  $ firebase --version
 
  $ firebase --version
 
  6.10.0
 
  6.10.0
 +
 +
インストールに失敗したときは、一度削除してからやり直す。
 +
16 vulnerabilities (4 moderate, 12 critical)
 +
$ npm uninstall  -g firebase-tools
 +
$ npm install -g firebase-tools
 +
 +
===firebaseログイン===
 
  $ firebase login
 
  $ firebase login
 
ブラウザが開くので、firebaseコンソールに繋がるgoogleアカウントでログインする。
 
ブラウザが開くので、firebaseコンソールに繋がるgoogleアカウントでログインする。
行43: 行50:
 
  ttps://us-central1-unity-xxxxx.cloudfunctions.net/helloWorld
 
  ttps://us-central1-unity-xxxxx.cloudfunctions.net/helloWorld
 
メソッドをコメントアウトしたままだと公開用urlは出てこない
 
メソッドをコメントアウトしたままだと公開用urlは出てこない
 +
 +
===not found. Billing must be enabled for activation of serviceとなる場合===
 +
以下エラーが出る場合
 +
<pre>
 +
Error: HTTP Error: 400, Billing account for project '***********' is not found. Billing must be enabled for activation of service(s) 'cloudbuild.googleapis.com,containerregistry.googleapis.com' to proceed.
 +
</pre>
 +
以下手順で請求先アカウントをリンクする
 +
#Google Cloud Console ( https://console.cloud.google.com/home/dashboard )にログインします。
 +
#Cloud Console にログインする
 +
#Google Cloud Console ページの上部にある [プロジェクト] プルダウン(︙)で、プロジェクトを選択します。
 +
#Console のナビゲーション メニュー(menu)を開き、[お支払い] を選択します。
 +
#プロジェクトを選択し、請求先アカウントをリンクする
 +
 +
==="error cleaning up build~"なエラーが出る場合===
 +
エラー詳細
 +
⚠  functions: Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at ~/gcf-artifacts
 +
一度リンク先に行ってファイルを削除して、再度deploy実行すれば良い。
 +
 +
==現在のデフォルトプロジェクト確認==
 +
$ firebase projects:list
 +
│ Name                      │ Project ID / Instance      │ Permissions │
 +
│ unitysample (current)      │ unitysample-31353          │ Owner      │
 +
│ unity-fabric-project      │ unity-android-demo        │ Owner      │
 +
 +
===現在のデフォルトプロジェクト変更===
 +
$ firebase use [project id]
 +
 +
====恒久設定====
 +
.firebasercファイルに以下のようなプロジェクトID記述
 +
"default": "hogehoge-21847"
 +
 +
===プロジェクト指定===
 +
$ firebase deploy --only functions --project hogeproject-12341
  
 
===Error: Error parsing triggers: Cannot find module 'firebase-functions'エラーが出る場合===
 
===Error: Error parsing triggers: Cannot find module 'firebase-functions'エラーが出る場合===
 +
npm install実行前に、そのdirにpackage.jsonがあることを確認。
 
  cd functions
 
  cd functions
 
  npm install
 
  npm install
 +
 +
===特定functionのみ===
 +
firebase deploy --only functions:addMessage
  
 
==httpアクセス==
 
==httpアクセス==
行52: 行96:
  
 
最初のアクセスだけgoogle認証が必要?2回目からは別のブラウザからでも認証画面が出てこなかった。
 
最初のアクセスだけgoogle認証が必要?2回目からは別のブラウザからでも認証画面が出てこなかった。
 +
 +
==東京リージョン指定==
 +
const functions = require('firebase-functions');
 +
exports.helloWorld = functions.region('asia-northeast1').https.onRequest((request, response) => {
 +
    response.send("Hello from Firebase! asia-northeast1");
 +
});
 +
既に別の場所にdeployしてる場合は、その場所のfunctionsは削除され、東京に新たに作られる。
 +
 +
hostingから連携してた場合は、us-central1以外へアクセスすると"Your client does not have permission to get URL /helloWorld from this server."エラーとなる。
  
 
==log==
 
==log==
行65: 行118:
  
 
\nで改行にできる。ただし、文字列が多い場合のみ
 
\nで改行にできる。ただし、文字列が多い場合のみ
 +
 +
logに表示されるのは丁度5000文字まででした。5000文字以上は特にエラーなくカットされてた。
 +
 +
==errorlog==
 +
以下記述よってグラフ反映に違いがある。
 +
console.error(new Error('message')); // エラーグラフに反映される
 +
console.error('message'); // エラーグラフに反映されない。がjavaエラーのStackLogなフォーマットな感じだと記録されるっぽい。
 +
Stackdriver Error Reporting にエラーを送信したい場合も。
 +
 +
参考:https://cloud.google.com/functions/docs/monitoring/error-reporting?hl=ja
 +
 +
===errorlogをメールアラート設定===
 +
新しく起こったerrorlogをメールするには
 +
stackdriverのサイト https://console.cloud.google.com/errors へ行って、
 +
設定から新しいエラーが起こったときに通知するように設定する。
 +
 +
既存エラーでピークが発生した際は設定がないので自力でやる?
  
 
===log割り当て制限===
 
===log割り当て制限===
行80: 行150:
 
</pre>
 
</pre>
  
==Stackdriver Error Reporting にエラーを送信==
+
==Spark無料枠==
console.error(new Error('message'));
+
 
+
参考:https://cloud.google.com/functions/docs/monitoring/error-reporting?hl=ja
+
 
+
==spark無料枠==
+
 
  呼び出し125K/month
 
  呼び出し125K/month
 
  GB 秒 40K/month
 
  GB 秒 40K/month
行102: 行167:
 
請求先アカウントを登録する
 
請求先アカウントを登録する
  
==参考==
+
==" functions: You are using an old version of firebase-functions SDK (3.8.0). Please update firebase-functions SDK to >=3.20.0"エラーが出た場合==
https://devlog.hassaku.blue/2019/03/unity-firebase-firebase.html
+
以下を3.8.0を3.20.0に変更
 +
$ vi functions/package.json
 +
バージョンを反映
 +
$ cd functions
 +
$ npm install
 +
 
 +
==一定数のリクエストを超えると==
 +
speakプランで、呼び出し125K/monthを超えた後でもstatus_code:200が返ってきた。
 +
70回/分を超えると以下のようになったが・・。
 +
status_code=429
 +
message=Too Many Requests
 +
 
 +
==存在しないエンドポイントにアクセスすると==
 +
Error: Forbidden
 +
Your client does not have permission to get URL /dummyendpoint from this server.
 +
ステータスコード403となる
 +
 
 +
==ファイル容量が大きい場合==
 +
以下エラーが出る
 +
Your proposed upload is larger than the maximum object size specified in your Policy Document.
 +
 
 +
一例として
 +
*ソース用に 100 MB(圧縮)
 +
*ソースとモジュール用に 500 MB(非圧縮)
 +
 
 +
公式:https://cloud.google.com/functions/quotas
 +
 
 +
==authenticationのログイン日取得==
 +
https://firebase.google.com/docs/reference/node/firebase.auth.UserMetadata#lastsignintime
 +
 
 +
firebase.auth.UserMetadata.lastSignInTime
 +
 
 +
https://www.memory-lovers.blog/entry/2020/03/20/120000
 +
 
 +
let listUsersResult = await admin.auth().listUsers(1000);
 +
result.push(...listUsersResult.users);
 +
 
 +
未検証だが、ここらへんでいける?

2023年2月10日 (金) 02:44時点における最新版

CloudFunctionsとは

  • サーバーレスアーキテクチャ。関数処理をしてくれるもの。awsのLambdaと同じ。
  • nodeで動く

CloudFunction準備

nvmインストール

Javascript/nodejs/インストール/nvm [ショートカット]

firebaseツールインストール

$ npm install -g firebase-tools
$ firebase --version
6.10.0

インストールに失敗したときは、一度削除してからやり直す。

16 vulnerabilities (4 moderate, 12 critical)
$ npm uninstall  -g firebase-tools
$ npm install -g firebase-tools

firebaseログイン

$ firebase login

ブラウザが開くので、firebaseコンソールに繋がるgoogleアカウントでログインする。

firebaseログアウト

$ firebase logout

functionsを新規作成

$ firebase init functions
? What language would you like to use to write Cloud Functions? JavaScript
? Do you want to use ESLint to catch probable bugs and enforce style? No
✔  Wrote functions/package.json
✔  Wrote functions/index.js
✔  Wrote functions/.gitignore
? Do you want to install dependencies with npm now? Yes
  1. プロジェクトを選択
  2. JavaScriptとTypeScriptを選択、とりあえずJavaScriptを選択
  3. ESLintはデフォルトoffだったので、offで作成
  4. npmの依存パッケージはデフォルトyesだったので、yesで作成

スクリプト修正

functions/index.js

exports.helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello from Firebase!");
});

コメントを外す

deploy

$ firebase deploy --only functions
ttps://us-central1-unity-xxxxx.cloudfunctions.net/helloWorld

メソッドをコメントアウトしたままだと公開用urlは出てこない

not found. Billing must be enabled for activation of serviceとなる場合

以下エラーが出る場合

Error: HTTP Error: 400, Billing account for project '***********' is not found. Billing must be enabled for activation of service(s) 'cloudbuild.googleapis.com,containerregistry.googleapis.com' to proceed.

以下手順で請求先アカウントをリンクする

  1. Google Cloud Console ( https://console.cloud.google.com/home/dashboard )にログインします。
  2. Cloud Console にログインする
  3. Google Cloud Console ページの上部にある [プロジェクト] プルダウン(︙)で、プロジェクトを選択します。
  4. Console のナビゲーション メニュー(menu)を開き、[お支払い] を選択します。
  5. プロジェクトを選択し、請求先アカウントをリンクする

"error cleaning up build~"なエラーが出る場合

エラー詳細

⚠  functions: Unhandled error cleaning up build images. This could result in a small monthly bill if not corrected. You can attempt to delete these images by redeploying or you can delete them manually at ~/gcf-artifacts

一度リンク先に行ってファイルを削除して、再度deploy実行すれば良い。

現在のデフォルトプロジェクト確認

$ firebase projects:list
│ Name                       │ Project ID / Instance      │ Permissions │
│ unitysample (current)      │ unitysample-31353          │ Owner       │
│ unity-fabric-project       │ unity-android-demo         │ Owner       │

現在のデフォルトプロジェクト変更

$ firebase use [project id]

恒久設定

.firebasercファイルに以下のようなプロジェクトID記述

"default": "hogehoge-21847"

プロジェクト指定

$ firebase deploy --only functions --project hogeproject-12341

Error: Error parsing triggers: Cannot find module 'firebase-functions'エラーが出る場合

npm install実行前に、そのdirにpackage.jsonがあることを確認。

cd functions
npm install

特定functionのみ

firebase deploy --only functions:addMessage

httpアクセス

Hello from Firebase!

最初のアクセスだけgoogle認証が必要?2回目からは別のブラウザからでも認証画面が出てこなかった。

東京リージョン指定

const functions = require('firebase-functions');
exports.helloWorld = functions.region('asia-northeast1').https.onRequest((request, response) => {
    response.send("Hello from Firebase! asia-northeast1");
});

既に別の場所にdeployしてる場合は、その場所のfunctionsは削除され、東京に新たに作られる。

hostingから連携してた場合は、us-central1以外へアクセスすると"Your client does not have permission to get URL /helloWorld from this server."エラーとなる。

log

console.log('I am a log entry!');
  • console.log() INFO ログレベル
  • console.error() ERROR ログレベル
  • 内部システム DEBUG ログレベル

以下のような感じで表示される

時刻arrow_downward	レベル	関数	イベント メッセージ
1:57:06.117 午前 info	helloWorld I am aa log entry!
1:56:20.007 午前 warning	helloWorld2 error2

\nで改行にできる。ただし、文字列が多い場合のみ

logに表示されるのは丁度5000文字まででした。5000文字以上は特にエラーなくカットされてた。

errorlog

以下記述よってグラフ反映に違いがある。

console.error(new Error('message')); // エラーグラフに反映される
console.error('message'); // エラーグラフに反映されない。がjavaエラーのStackLogなフォーマットな感じだと記録されるっぽい。

Stackdriver Error Reporting にエラーを送信したい場合も。

参考:https://cloud.google.com/functions/docs/monitoring/error-reporting?hl=ja

errorlogをメールアラート設定

新しく起こったerrorlogをメールするには stackdriverのサイト https://console.cloud.google.com/errors へ行って、 設定から新しいエラーが起こったときに通知するように設定する。

既存エラーでピークが発生した際は設定がないので自力でやる?

log割り当て制限

https://cloud.google.com/logging/quota-policy

ログエントリのサイズ	100 KB*
entries.write リクエストのサイズ	5 MB*
entries.write API 呼び出しの数	1 プロジェクトあたり 1,000 回/秒
entries.list API 呼び出しの数	1 プロジェクトあたり 1 回/秒
ログエントリの保持期間	30 日(プレミアム階層)
7 日(基本階層)
ユーザー定義のログベースの指標	1 プロジェクトあたり 500 件
API からのページトークンの有効期間	24 時間

Spark無料枠

呼び出し125K/month
GB 秒 40K/month
CPU 秒 40K/month
アウトバウンド ネットワーキング Google services only

https://firebase.google.com/pricing/?hl=ja

Blaze 従量プラン

呼び出し $0.40/百万
GB 秒 $0.0025/千
CPU 秒 $0.01/千
アウトバウンド ネットワーキング $0.12/GB

Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictionsが出る場合

請求先アカウントを登録する

" functions: You are using an old version of firebase-functions SDK (3.8.0). Please update firebase-functions SDK to >=3.20.0"エラーが出た場合

以下を3.8.0を3.20.0に変更

$ vi functions/package.json

バージョンを反映

$ cd functions
$ npm install

一定数のリクエストを超えると

speakプランで、呼び出し125K/monthを超えた後でもstatus_code:200が返ってきた。 70回/分を超えると以下のようになったが・・。

status_code=429
message=Too Many Requests

存在しないエンドポイントにアクセスすると

Error: Forbidden
Your client does not have permission to get URL /dummyendpoint from this server.

ステータスコード403となる

ファイル容量が大きい場合

以下エラーが出る

Your proposed upload is larger than the maximum object size specified in your Policy Document.

一例として

  • ソース用に 100 MB(圧縮)
  • ソースとモジュール用に 500 MB(非圧縮)

公式:https://cloud.google.com/functions/quotas

authenticationのログイン日取得

https://firebase.google.com/docs/reference/node/firebase.auth.UserMetadata#lastsignintime

firebase.auth.UserMetadata.lastSignInTime

https://www.memory-lovers.blog/entry/2020/03/20/120000

let listUsersResult = await admin.auth().listUsers(1000);
result.push(...listUsersResult.users);

未検証だが、ここらへんでいける?