イベント ドリブン関数を作成する

Cloud Functions では、クラウド環境で発生したイベントに応じて関数を自動的に呼び出す場合に、イベント ドリブン関数を使用します。

イベント ドリブン関数を実装する方法は 2 つあります。その方法は、選択した言語ランタイムと Cloud Functions の世代(第 1 世代か第 2 世代)によって異なります。

  • Cloud Functions(第 2 世代)の場合、すべてのランタイムで CloudEvent 関数を使用します。
  • Cloud Functions(第 1 世代)の場合:

CloudEvent 関数

CloudEvent 関数は、イベントデータを一般的な方法で記述するための業界標準である CloudEvents をベースにしています。CloudEvents 仕様の詳細については、CloudEvents GitHub リポジトリをご覧ください。CloudEvents プロジェクトには、コード内の CloudEvents オブジェクトを操作するための一連の CloudEvents SDK も用意されています。

以下に、各ランタイムの基本的な CloudEvent 関数のソースファイルを示します。ソースコードの場所については、ソース ディレクトリ構造をご覧ください。

Node.js

const functions = require('@google-cloud/functions-framework');

// Register a CloudEvent function with the Functions Framework
functions.cloudEvent('myCloudEventFunction', cloudEvent => {
  // Your code here
  // Access the CloudEvent data payload via cloudEvent.data
});

Node.js では、CloudEvent ハンドラ関数を Functions Framework for Node.js で登録します。ハンドラ関数は、CloudEvent オブジェクトを引数として受け入れる必要があります。

関数のエントリ ポイントは、ハンドラを Functions Framework に登録したときに使用した名前です。この例では、エントリ ポイントは myCloudEventFunction です。

Python

import functions_framework

# Register a CloudEvent function with the Functions Framework
@functions_framework.cloud_event
def my_cloudevent_function(cloud_event):
  # Your code here
  # Access the CloudEvent data payload via cloud_event.data

Python では、CloudEvent ハンドラ関数を Functions Framework for Python に登録します。ハンドラ関数は、CloudEvent オブジェクトを引数として受け入れる必要があります。

関数のエントリ ポイントは、Functions Framework に登録されたハンドラ関数の名前です。この例では、エントリ ポイントは my_cloudevent_function です。

Go

package mycloudeventfunction

import (
    "context"

    "github.com/GoogleCloudPlatform/functions-framework-go/functions"
    "github.com/cloudevents/sdk-go/v2/event"
)

func init() {
    // Register a CloudEvent function with the Functions Framework
    functions.CloudEvent("MyCloudEventFunction", myCloudEventFunction)
}

// Function myCloudEventFunction accepts and handles a CloudEvent object
func myCloudEventFunction(ctx context.Context, e event.Event) error {
    // Your code here
    // Access the CloudEvent data payload via e.Data() or e.DataAs(...)

    // Return nil if no error occurred
    return nil
}

Go では、CloudEvent ハンドラ関数を Functions Framework for Go に登録します。ハンドラ関数は、CloudEvents event.Event オブジェクトを引数として受け入れる必要があります。

関数のエントリ ポイントは、ハンドラを Functions Framework に登録したときに使用した名前です。この例では、エントリ ポイントは MyCloudEventFunction です。

Java

package mycloudeventfunction;

import com.google.cloud.functions.CloudEventsFunction;
import io.cloudevents.CloudEvent;

// Define a class that implements the CloudEventsFunction interface
public class MyCloudEventFunction implements CloudEventsFunction {
  // Implement the accept() method to handle CloudEvents
  @Override
  public void accept(CloudEvent event) {
    // Your code here
    // Access the CloudEvent data payload via event.getData()
    // To get the data payload as a JSON string, use:
    // new String(event.getData().toBytes())
  }
}

Java では、Functions Framework Java API を使用して、CloudEventsFunction インターフェースを持つ CloudEvent ハンドラクラスを実装します。accept() メソッドは、CloudEvent オブジェクトを引数として受け取り、イベントに対する処理を行う必要があります。

関数のエントリ ポイントは、パッケージ名を含む CloudEvent ハンドラクラスの完全修飾名です。この例では、エントリ ポイントは mycloudeventfunction.MyCloudEventFunction です。

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using System.Threading;
using System.Threading.Tasks;

namespace MyProject
{
    // Define a class that implements the ICloudEventFunction<T> interface
    public class MyCloudEventFunction : ICloudEventFunction<CloudEventDataType>
    {
        // Implement the HandleAsync() method to handle CloudEvents
        public Task HandleAsync(CloudEvent cloudEvent, CloudEventDataType data, CancellationToken cancellationToken)
        {
            // Your code here
            // The data argument represents the CloudEvent data payload

            // Signal function completion
            return Task.CompletedTask;
        }
    }
}

.NET ランタイムでは、Functions Framework for .NET を使用して、ICloudEventFunction<T> インターフェースを持つ CloudEvent ハンドラクラスを実装します。HandleAsync() メソッドは、引数として CloudEvent オブジェクトとそれに関連する CloudEvent データ ペイロードを受け取ります。

CloudEvent データ ペイロード引数の型(上記の例では CloudEventDataType)は、関数が処理するイベントのタイプに対応している必要があります。Google CloudEvents .NET ライブラリには、Google でサポートされているさまざまなイベントのデータ型が用意されています。

関数のエントリ ポイントは、CloudEvent ハンドラクラスの完全修飾名(名前空間を含む)です。この例では、エントリ ポイントは MyProject.MyCloudEventFunction です。

Ruby

require "functions_framework"

# Register a CloudEvent function with the Functions Framework
FunctionsFramework.cloud_event "my_cloudevent_function" do |cloud_event|
  # Your code here
  # Access the CloudEvent data payload via cloud_event.data
end

Ruby では、CloudEvent ハンドラ関数を Functions Framework for Ruby に登録します。ハンドラ関数は、CloudEvents Event オブジェクトを引数として受け入れる必要があります。

関数のエントリ ポイントは、ハンドラを Functions Framework に登録したときに使用した名前です。この例では、エントリ ポイントは my_cloudevent_function です。

PHP

<?php

use CloudEvents\V1\CloudEventInterface;
use Google\CloudFunctions\FunctionsFramework;

// Register a CloudEvent function with the Functions Framework
FunctionsFramework::cloudEvent('myCloudEventFunction', 'myCloudEventHandler');

// Define your CloudEvent handler
function myCloudEventHandler(CloudEventInterface $event): void
{
    // Your code here
    // Access the CloudEvent data payload via $event->getData()
}

PHP では、CloudEvent ハンドラ関数を Functions Framework for PHP に登録します。ハンドラ関数は、CloudEventInterface インターフェースに適合する引数を受け入れる必要があります。

関数のエントリ ポイントは、ハンドラを Functions Framework に登録したときに使用した名前です。この例では、エントリ ポイントは myCloudEventFunction です。

CloudEvent 関数の場合、イベントデータは CloudEvents 形式で関数に渡されます。CloudEvent データ ペイロードは、関数をトリガーするイベントタイプに対応します。サポートされているトリガー、イベントタイプ、関連するイベントデータの形式については、Cloud Functions の関数のトリガーをご覧ください。

Google イベント リポジトリには、Google が発行する CloudEvents を使用するためのリソースが含まれています。

バックグラウンド関数

Cloud Functions(第 1 世代)の Node.js、Python、Go、Java ランタイムのイベント ドリブン関数は、CloudEvent 関数とは異なる引数を使用します。この古いスタイルのイベント ドリブン関数は、バックグラウンド関数と呼ばれます。

以下に、各ランタイムの基本的なバックグラウンド関数のソースファイルを示します。ソースコードの場所については、ソース ディレクトリ構造をご覧ください。

Node.js

// Define and export an event handler
exports.myBackgroundFunction = (eventData, context, callback) => {
  // Your code here
  // The eventData argument represents the event data payload

  // Optionally signal function completion:
  callback();
};

Node.js では、イベントデータを処理する関数を定義してエクスポートします。Cloud Functions は、ハンドラ関数に次の引数を渡します。

  • eventData: イベントデータ ペイロードを表すオブジェクト。形式はイベントによって異なります。
  • context: イベントに関するメタデータを含むオブジェクト。
  • callback: 完了を通知するために呼び出すオプションの関数。このコールバックの最初の引数は、エラーのシグナルとして解釈されます。成功を通知するには、引数なしで渡すか、最初の引数である null を渡します。

関数のエントリ ポイントは、エクスポートされたイベント ハンドラの名前です。この例では、エントリ ポイントは myBackgroundFunction です。

Python

# Define an event handler
def my_background_function(event_data, context):
  # Your code here
  # The event_data argument represents the event data payload

Python では、イベントデータを処理する関数を定義します。Cloud Functions は、ハンドラ関数に次の引数を渡します。

  • event_data: イベントデータ ペイロードを表す辞書。形式はイベントによって異なります。
  • context: イベントに関するメタデータを含むオブジェクト。

関数のエントリ ポイントは、ハンドラ関数の名前です。この例では、エントリ ポイントは my_background_function です。

Go

package mybackgroundfunction

import (
    "context"
)

// Function MyBackgroundFunction accepts and handles event data
func MyBackgroundFunction(ctx context.Context, e EventDataType) error {
    // Your code here
    // The argument e represents the event data payload

    // Return nil if no error occurred
    return nil
}

Go では、イベントデータを処理するエクスポート済み関数を定義します。Cloud Functions は、ハンドラ関数に次の引数を渡します。

  • ctx: イベントに関するメタデータを含む context.Context オブジェクト。メタデータは、cloud.google.com/go/functions/metadata パッケージで取得できます。
  • e: イベントデータ ペイロードを表すオブジェクト。上記の例では、型が EventDataType になっています。このため、関数の処理するイベントタイプに対応する構造体を使用する必要があります。イベントデータ ペイロードは、json.Unmarshal() を使用して構造体にマーシャリング解除されます。

関数のエントリ ポイントは、エクスポートされたイベント ハンドラの名前です。この例では、エントリ ポイントは MyBackgroundFunction です。

Java

package mybackgroundfunction;

import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;

// Define a class that implements the BackgroundFunction<T> interface
public class MyBackgroundFunction implements BackgroundFunction<EventDataType> {
  // Implement the accept() method to handle events
  @Override
  public void accept(EventDataType eventData, Context context) {
    // Your code here
    // The eventData argument represents the event data payload
  }
}

Java では、Functions Framework Java API を使用して、BackgroundFunction<T> インターフェースを持つイベント ハンドラ クラスを実装します。accept() メソッドは、イベント データ ペイロードと、イベントに関するメタデータを含む Context オブジェクトを引数として受け取ります。

イベント データ ペイロードの引数の型(上記の例では EventDataType)は、関数が処理するイベントのタイプに対応している必要があります。イベント データ ペイロードは、Gson.fromJson() を使用してシリアル化解除され、このクラスのインスタンスになります。

関数のエントリ ポイントは、イベント ハンドラクラスの完全修飾名(パッケージ名を含む)です。この例では、エントリ ポイントは mybackgroundfunction.MyBackgroundFunction です。

バックグラウンド関数の場合、イベント データ ペイロードは、関数をトリガーするイベントタイプに対応する形式で関数に直接渡されます。サポートされているトリガー、イベントタイプ、関連するイベントデータの形式については、Cloud Functions(第 1 世代)でサポートされているトリガーをご覧ください。

関数の終了

関数から制御が戻ると、Cloud Functions はイベント ドリブン関数の実行が終了したと判断します。関数によってバックグラウンド タスク(スレッド、Future、JavaScript Promise オブジェクト、コールバック、システム プロセスなど)が作成される場合は、関数から制御が戻る前に、これらのタスクを終了します。あるいは、他の方法で問題を解決する必要があります。関数が返される前に終了しなかったタスクは完了しません。未定義の動作が行われる可能性があります。

自動再試行

失敗した呼び出しを自動的に再試行するように、イベント ドリブン関数を構成できます。詳細については、イベント ドリブン関数の再試行をご覧ください。

次のステップ