如何在 Firebase Functions 第二代中删除 x 分钟后重试的事件

问题描述 投票:0回答:1

我正在将一些 Firebase Functions 代码从第一代迁移到第二代。在我的第一代函数中,我使用一个

shouldDropEvent
帮助程序,它查看上下文的时间戳,并决定在重试 x 分钟后删除该事件。

对于第二代,我不知道在哪里可以找到这个时间戳。

另外,我想配置重试行为,但我认为当前的 API 不可能实现。

pubSendNotificationToUserToken
是我用于 pubsub 的一种抽象,它将主题和处理程序放在一个地方。请忽略它。

import { pubSendNotificationToUserToken } from "@repo/core/notifications";
import type { EventContext } from "firebase-functions";
import functions from "firebase-functions";
import { onMessagePublished } from "firebase-functions/v2/pubsub";

const MINUTE_MS = 60 * 1000;
export const retryEventMaxAgeMs = 20 * MINUTE_MS;

export const sendNotificationToUserToken_1stGen = functions
  .runWith({
    failurePolicy: true,
  })
  .pubsub.topic(pubSendNotificationToUserToken.topic)
  .onPublish(async (message, context) => {
    if (shouldDropEvent(context, MINUTE_MS * 5)) {
      return;
    }

    await pubSendNotificationToUserToken.handle(message.json);
  });

export const sendNotificationToUserToken_2ndGen = onMessagePublished(
  {
    topic: pubSendNotificationToUserToken.topic,
    retry: true,
  },
  async (event) => {
    await pubSendNotificationToUserToken.handle(event.data.message.json);
  }
);

/**
 * Check if max age has been reached. Timestamp should be in RFC 3339 format to
 * match cloud functions context event timestamp.
 */
function shouldDropEvent(
  context: EventContext<unknown>,
  maxAgeMs = retryEventMaxAgeMs
) {
  const eventAge = Date.now() - Date.parse(context.timestamp);

  if (eventAge > maxAgeMs) {
    console.error(
      new Error(
        `Dropping event ${context.eventType} for ${context.resource.name} because max age was reached.`
      )
    );
    return true;
  }

  return false;
}
javascript firebase google-cloud-functions google-cloud-pubsub
1个回答
0
投票

onMessagePublished 事件处理程序接收单个 CloudEvent 类型参数,该参数具有 time 属性。

export const sendNotificationToUserToken_2ndGen = onMessagePublished(
  {
    topic: pubSendNotificationToUserToken.topic,
    retry: true,
  },
  async (event) => {
    // event.time contains the time of the CloudEvent argument
  }
);
© www.soinside.com 2019 - 2024. All rights reserved.