LoginSignup
3
2

More than 5 years have passed since last update.

Firebase RealtimeDatabaseに大量データ投入 - その3 -

Last updated at Posted at 2018-07-11

GYAOのtsです。

経緯

前回の投稿でデータの投入、更新はできるようになたので、お掃除jobであるcleanExpiredMessageを作ってみる。GAEのcronつかってもいいのだが、面白そうなのでAzure LogicAppsと連携してみる。GUIで直感的だし。なんかエンジニアじゃなくても起動時間とか変えられそうだし。

やりたいこと

  • httpsリクエストで起動
  • messagesの中のexpiredDate(unix timestamp)が過去のものを検索して、すべてdeleteする。

Cloud Functions

index.js
'use strict';

const rcloadenv = require('@google-cloud/rcloadenv');
rcloadenv.getAndApply('functionConfig');

/**
 * job that cleans expired messages.
 *
 * @param {!Object} req Cloud Function request context.
 * @param {!Object} res Cloud Function response context.
 */
exports.cleanExpiredMessage = (req, res) => {
    const key = req.query.key;
    if (!module.exports.authenticate(key)) {
        res.status(403).send('Security key does not match.');
    }
    else {
        console.log('invoke clean-expired-message Job.');
        const now = Math.floor( new Date().getTime() / 1000 );
        const messageRef = db.ref("messages");
        const updates = {};
        messageRef.orderByChild("expireDate").endAt(now).once('value', function(snapshot) {
            snapshot.forEach(function(child) {
                console.log(child.key);
                if (child.val().expireDate === undefined) {
                    console.log('expireDate is undefined.');
                    //do nothing.
                }
                else {
                    console.log(child.key + ' added to the delete list.');
                    updates[child.key] = null;
                }
            });
        }).then(() => {
            console.log('clean-expired-message ended.');
            return messageRef.update(updates);
        }).catch((e) => {
            console.error(e);
            throw e;
        });
        res.status(200).send('Success');
    }
};

/**
 * authentication method.
 *
 * @param key CRON_KEY
 * @returns {boolean} authenticated or not.
 */
exports.authenticate = function(key) {
    const secureCompare = require('secure-compare');
    if (!secureCompare(key, process.env.CRON_KEY)) {
        console.log('The key provided in the request does not match ' +
            'the key set in the environment. Check that', key,
            'matches the CRON_KEY');
        return false;
    }
    else {
        console.log('authenticated.');
        return true;
    }
}
  • upsertするときと同様、multi-location updates を使用する。
    • Realtime databaseはnullでupdateするとremoveになるのでそれを利用。
  • expireDateがないメッセージも引っ張ってくるため、undefinedの場合はremove対象には入れない。
  • jobの起動認証はRuntime Configを使用する。こちらで詳しく説明されている。

    • コンフィグ ’functionConfig’ に 下記のコマンドでCRON_KEYを設定する。
    $ gcloud beta runtime-config configs create functionConfig
    
    $ gcloud beta runtime-config configs variables set \
    CRON_KEY hogehoge \
    --is-text --config-name functionConfig
    
    

    これで uri?key=hogehogeで起動できる。

Azure Logic Apps

Azure LogicAppsで起動してみる。

  • Azure Portalからロジックアプリ作成
    スクリーンショット 2018-07-11 14.24.50.png

  • 下記のように構築。今回は起動結果(statusコード等をslackに送信するように設定)
    スクリーンショット 2018-07-11 14.31.13.png

  • さらにslackアクションの設定で失敗時にも結果がslackに送られるように設定
    スクリーンショット 2018-07-11 14.36.38.png

Slack, Cloud loggingで確認

  • Slack スクリーンショット 2018-07-11 14.37.53.png
  • Cloud logging スクリーンショット 2018-07-11 14.39.10.png

問題なし。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2