You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Firebase Cloud Function程序化查询当日Firestore配额数据?

程序化查询Firestore配额使用量,控制维护任务执行

可以通过Google Cloud Monitoring API实现这个需求,Firestore的读写删操作数据会同步到Cloud Monitoring,你可以用API拉取当日的使用量,再判断是否执行批量维护。

实现步骤

1. 调用Cloud Monitoring API获取配额数据

使用timeSeries.list接口查询当日的操作统计,关键参数和示例代码如下:

核心指标对应关系

  • 读操作:firestore.googleapis.com/database/read_count
  • 写操作:firestore.googleapis.com/database/write_count
  • 删除操作:firestore.googleapis.com/database/delete_count

Node.js示例(适配Cloud Functions环境)

const {MonitoringServiceClient} = require('@google-cloud/monitoring');

async function checkQuotaUsage() {
  const client = new MonitoringServiceClient();
  const projectId = process.env.GCLOUD_PROJECT;
  const today = new Date();
  const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate());

  const request = {
    name: `projects/${projectId}`,
    filter: `resource.type="firestore_database" AND resource.labels.database_id="(default)"`,
    interval: {
      startTime: { seconds: Math.floor(startOfDay.getTime() / 1000) },
      endTime: { seconds: Math.floor(Date.now() / 1000) }
    },
    aggregation: {
      alignmentPeriod: { seconds: 3600 },
      crossSeriesReducer: 'REDUCE_SUM',
      groupByFields: ['metric.type']
    }
  };

  const [response] = await client.listTimeSeries(request);
  const usage = { read: 0, write: 0, delete: 0 };

  response.forEach(series => {
    const lastValue = series.points.at(-1).value;
    const count = lastValue.int64Value || lastValue.doubleValue;
    if (series.metric.type.includes('read_count')) usage.read = count;
    else if (series.metric.type.includes('write_count')) usage.write = count;
    else if (series.metric.type.includes('delete_count')) usage.delete = count;
  });

  // 免费层级限额(请以官方最新数值为准)
  const freeLimits = { read: 50000, write: 20000, delete: 20000 };
  return Object.entries(freeLimits).every(([op, limit]) => usage[op] < limit);
}

// 调度函数入口
exports.runDailyMaintenance = async () => {
  const canProceed = await checkQuotaUsage();
  if (canProceed) {
    console.log('配额未达免费上限,执行维护任务');
    // 这里写你的批量维护逻辑
  } else {
    console.log('当日配额已接近或达到免费限额,跳过维护');
  }
};

2. 配置必要权限

确保Cloud Function的服务账号拥有Monitoring Viewer角色(或直接授予monitoring.timeSeries.list权限),否则无法调用Monitoring API。你可以在Cloud Console的IAM页面给函数对应的服务账号添加该角色。

3. 注意事项

  • 免费层级的配额可能会更新,建议定期确认官方最新数值;
  • Monitoring API的数据有几分钟延迟,对实时性要求极高的场景需注意;
  • 调用Monitoring API本身会产生少量请求费用,但免费层级内的调用量通常不会额外收费。

内容的提问来源于stack exchange,提问作者Fernando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:42:03