node.js - Google/Firebase 云功能的速率限制?

标签 node.js firebase express google-cloud-functions rate-limiting

我正在使用 Firebase 开发一个在内部使用 Cloud Functions 作为 REST API 的应用。我的问题是,是否有一种简单的方法来实现类似于 slack uses 的每 IP/每用户速率限制? ,除了基于每 IP每用户,而不是基于每应用(因为它都是一个应用)。对小突发的可选支持也是可取的。

示例代码(参见 //TODO: 注释):

exports.myCoolFunction = functions.https.onRequest((req, res) => {
        // TODO: implement IP rate-limiting here
        unpackToken(req).then((token) => { // unpackToken resolves with a response similar to verifyIdToken based on the "Authorization" header contents
                // TODO: implement user-based rate-limiting here (based on token.uid)
                if (!req.body) return res.status(400).end();
                if (typeof req.body.name !== "string") return res.status(400).end();
                if (typeof req.body.user !== "string") return res.status(400).end();

                // more input sanitization and function logic here

                return res.status(501).end(); // fallback in all requests, do not remove
        }).catch(() => res.status(403).end());
});

如果超过速率限制,我想简单地用 529 Too Many Requests 状态代码终止请求。这是为了防止应用程序错误充斥网络并防止滥用 REST API。

This should take into account Firebase spinning up/down server instances and having multiple instances running simultaneously.

I am also using a Firestore database and can use the legacy real-time database if necessary.

最佳答案

我制作了一个库来限制对 firebase 函数的调用: firebase-functions-rate-limiter 该库使用 realtimeDB 或 firestore(可配置)作为后端。它存储数据的方式与 Frank 描述的类似,但更经济。它不使用集合,而是使用每个限定符(例如用户 ID)的数组的单个文档。这意味着对于超出的调用只有一次读取,对于允许的调用只有一次读写。

$ npm i --save firebase-functions-rate-limiter

这是一个例子:

import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import { FirebaseFunctionsRateLimiter } from "firebase-functions-rate-limiter";

admin.initializeApp(functions.config().firebase);
const database = admin.database();

const limiter = FirebaseFunctionsRateLimiter.withRealtimeDbBackend(
    {
        name: "rate_limiter_collection",
        maxCalls: 2,
        periodSeconds: 15,
    },
    database,
);
exports.testRateLimiter = 
  functions.https.onRequest(async (req, res) => {
    await limiter.rejectOnQuotaExceeded(); // will throw HttpsException with proper warning

    res.send("Function called");
});

关于node.js - Google/Firebase 云功能的速率限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50741936/

相关文章:

java - SingleValueEvent 显示为空

firebase - 将 Firebase 导出到 Bigquery 数据集的生存时间

php websocket转发到nodejs

node.js - 在没有 SSL 证书的情况下通过 Nginx 转发 HTTPS 流量

android - Unity 应用程序因 Firebase SDK 而崩溃

node.js - Mongoose : using promises as parameters for other functions

javascript - 套接字 io Websocket 断开 Node js

node.js - 使用 Mustache 时模拟 Jade 的 'layout' 功能

javascript - Nodemailer 给出错误

node.js - 如何在 mean.io 中使用 MongoDB