GCP Pub/SubのメッセージはCloud Functionsへどう届くか


概要

GCP Pub/SubをTriggerにしたCloud Functionは、メッセージをどう受け取るのか調べてみました。

実験

試しに次のようにメッセージをPublishしてみます。



すると、次のようになりました。
attributesにメッセージ属性が入り、dataにメッセージ本文が入ってくるようです。

exports.test = (pubSubEvent, context) => {
  console.log(pubSubEvent)
};

// -> {"@type":"type.googleapis.com/google.pubsub.v1.PubsubMessage","attributes":{"key":"value"},"data":"bWVzc2FnZQ=="}

しかしメッセージ本文はbase64で格納されているため、使える形にするにはデコードする必要があります。

The payload of the PubsubMessage object, the data published to the topic, is stored as a base64-encoded string in the data attribute of the PubsubMessage. To extract the payload of the PubsubMessage object, you may need to decode the data attribute as shown in the examples below.

ref) https://cloud.google.com/functions/docs/calling/pubsub#event_structure

exports.test = (pubSubEvent, context, callback) => {
  console.log(Buffer.from(pubSubEvent.data, 'base64').toString())
};

// -> message

Cloud Schedulerの場合

Cloud SchedulerでPub/SubをPublishするとき、payloadを指定できます。


このpayloadは、dataの中に入ってくるようです。
attributesを指定するには、gcloudコマンド経由でジョブを作成すると良いようです。

ref) Cloud Schedulerのジョブにattributesを設定する

Context

ちなみにcontextの中身は、こちらに記載されていました。
TypeScriptで書くとこんな感じ

type Context = {
    eventId: string,
    timestamp: string,
    eventType: string,
    resource: string
}