Write event-driven Cloud Run functions (original) (raw)

In Cloud Run functions, you write an event-driven function when you want a function to be triggered directly in response to events within your Google Cloud project, such as messages on a Pub/Sub topic or changes in a Cloud Storage bucket.

Implement event-driven handler functions

Event-driven functions are based onCloudEvents, an industry-standard specification for describing event data in a common way. You can learn more about the CloudEvents specification at theCloudEvents GitHub repository. The CloudEvents project also provides a set ofCloudEvents SDKsto help work with CloudEvents objects in your code.

The following example shows an event-driven function source file for each runtime. SeeSource directory structurefor information about where to locate your source code.

Node.js

ES module

  import { cloudEvent } from "@google-cloud/functions-framework";
  cloudEvent('myCloudEventFunction', cloudEvent => {
    // Your code here
    // Access the CloudEvent data payload using cloudEvent.data
  });

Add the following dependencies, including "type": "module" in yourpackage.json file:

  {
    "dependencies": {
      "@google-cloud/functions-framework": "^3.0.0"
    },
    "type": "module"
  }

CommonJS module

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 using cloudEvent.data
});

Add the following dependencies in your package.json file:

  {
    "dependencies": {
      "@google-cloud/functions-framework": "^3.0.0"
    }
  }

In Node.js, you register a CloudEvent handler function with theFunctions Framework for Node.js. Your handler function must accept aCloudEventobject as an argument.

Thefunction entry pointis the name with which the handler is registered with the Functions Framework. In this example, the entry point is 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

In Python, you register a CloudEvent handler function with theFunctions Framework for Python. Your handler function must accept aCloudEventobject as an argument.

Thefunction entry pointis the name of the handler function registered with the Functions Framework. In this example, the entry point is 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 using e.Data() or e.DataAs(...)

    // Returning an error causes its message to be logged.
    // Example:
    err := myInternalFunction() // may return an error
    if err != nil {
        // Append error message to log
        return err
    }

    // Return nil if no error occurred
    return nil
}

In Go, you register a CloudEvent handler function with theFunctions Framework for Go. Your handler function must accept a CloudEventsevent.Eventobject as an argument.

Thefunction entry pointis the name with which the handler is registered with the Functions Framework. In this example, the entry point is 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 using event.getData()
    // To get the data payload as a JSON string, use:
    // new String(event.getData().toBytes())
  }
}

In Java, you use theFunctions Framework Java APIto implement a CloudEvent handler class with theCloudEventsFunctioninterface. The accept() method must accept aCloudEventobject as an argument and perform any processing on the event.

Thefunction entry pointis the fully-qualified name of the CloudEvent handler class, including the package name. In this example, the entry point ismycloudeventfunction.MyCloudEventFunction.

.NET

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

namespace MyProject { // Define a class that implements the ICloudEventFunction interface public class MyCloudEventFunction : ICloudEventFunction { // 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;
  }

} }

In .NET runtimes, you use theFunctions Framework for .NETto implement a CloudEvent handler class with theICloudEventFunctioninterface. The HandleAsync() method accepts aCloudEventobject and the associated CloudEvent data payload as arguments.

The type of the CloudEvent data payload argument, shown in the example code asCloudEventDataType, must correspond to the type of event the function handles. TheGoogle CloudEvents .NET libraryprovides data types for the various events supported by Google.

Thefunction entry pointis the fully-qualified name of the CloudEvent handler class, including the namespace. In this example, the entry point is 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

In Ruby, you register a CloudEvent handler function with theFunctions Framework for Ruby. Your handler function must accept a CloudEventsEventobject as an argument.

Thefunction entry pointis the name with which the handler is registered with the Functions Framework. In this example, the entry point is 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 using $event->getData()
}

In PHP, you register a CloudEvent handler function with theFunctions Framework for PHP. Your handler function must accept an argument that conforms to theCloudEventInterfaceinterface.

Thefunction entry pointis the name with which the handler is registered with the Functions Framework. In this example, the entry point is myCloudEventFunction.

For event-driven functions, event data is passed to your function in theCloudEvents format, with a CloudEvent data payload corresponding to the event type that triggers your function. SeeFunction triggers for information about supported triggers, event types, and associated event data formats.

TheGoogle Eventsrepository contains resources for working with CloudEvents issued by Google.

Function termination

Cloud Run considers event-driven function execution complete when the function returns. If the function creates background tasks (such as with threads, futures, JavaScript Promise objects, callbacks, or system processes), you must terminate or otherwise resolve these tasks before returning from your function. Any tasks not terminated before the function returns might not be completed, and might cause undefined behavior.

Automatic retries

Event-driven functions can be configured to automatically retry failed invocations. See Retrying event-driven functionsfor more information.

What's next