CloudEvent Functions

CloudEvent functions are functions that are invoked indirectly in response to events, such as a message on a Pub/Sub topic, a change in a Cloud Storage bucket, or a Firebase event.

CloudEvent functions are conceptually similar to background functions. The principal difference between the two is that CloudEvent functions use an industry-standard event format known as CloudEvents. Another such difference is that Cloud Functions itself invokes CloudEvent functions using HTTP requests, which can be reproduced elsewhere. Taken together, these differences enable CloudEvent functions to be moved seamlessly between compute platforms.

Supporting runtimes

The following runtimes support CloudEvent functions:

Language Version(s)
C# Beta All
Ruby Beta All

Function parameters

CloudEvent functions are passed a single cloudEvent argument that holds properties and metadata associated with the event that triggered the function's execution. Incoming CloudEvents are then converted into the language-specific representations shown below using the Functions Framework libraries.

C#

The cloudEvent parameter is passed in to your function as a CloudEvent object that contains the following properties:

Property Type Description
cloudEvent.Id String The event's unique ID.
cloudEvent.Source uri The Google Cloud entity affected by the event, in the format /[SERVICE_DOMAIN_NAME]/[RESOURCE]/.
cloudEvent.Type String The CloudEvent type of the received event.
cloudEvent.Time DateTime A timestamp of when the event occurred.
cloudEvent.SpecVersion CloudEventsSpecVersion The CloudEvents specification version used to create the event.
cloudEvent.data Object An object containing event-type specific data.
cloudEvent.subject Nullable String If the underlying event refers to a Cloud Storage object, this will be set to the object's location, in the format objects/path/to/object. If the underlying event does not refer to such an object, this property will be null.

Ruby

The cloudEvent parameter is passed in to your function as a CloudEvents::Event::V1 object that contains the following properties:

Property Type Description
cloudEvent.id String The event's unique ID.
cloudEvent.source URI The Google Cloud entity affected by the event, in the format /[SERVICE_DOMAIN_NAME]/[RESOURCE]/.
cloudEvent.type String The CloudEvent type of the received event.
cloudEvent.time DateTime A timestamp of when the event occurred.
cloudEvent.specversion String The CloudEvents specification version used to create the event.
cloudEvent.data Hash A Hash containing event-type specific data.
cloudEvent.subject String or Nil If the underlying event refers to a Cloud Storage object, this will be set to the object's location, in the format objects/path/to/object. If the underlying event does not refer to such an object, this property will be Nil. Cloud Storage events

Sample usage

The examples below show how to process events from Pub/Sub and Cloud Storage. For more information about handling events from different sources, see Calling Cloud Functions.

Pub/Sub example

This example shows a CloudEvent function triggered by Pub/Sub events. Every time a message is published to a Pub/Sub topic, the function is invoked, and a greeting using data derived from the message is written to the log.

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.PubSub.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace HelloPubSub
{
    public class Function : ICloudEventFunction<MessagePublishedData>
    {
        private readonly ILogger _logger;

        public Function(ILogger<Function> logger) =>
            _logger = logger;

        public Task HandleAsync(CloudEvent cloudEvent, MessagePublishedData data, CancellationToken cancellationToken)
        {
            string nameFromMessage = data.Message?.TextData;
            string name = string.IsNullOrEmpty(nameFromMessage) ? "world" : nameFromMessage;
            _logger.LogInformation("Hello {name}", name);
            return Task.CompletedTask;
        }
    }
}

Ruby

require "functions_framework"
require "base64"

FunctionsFramework.cloud_event "hello_pubsub" do |event|
  # The event parameter is a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  name = Base64.decode64 event.data["message"]["data"] rescue "World"

  # A cloud_event function does not return a response, but you can log messages
  # or cause side effects such as sending additional events.
  logger.info "Hello, #{name}!"
end

For more information about deploying Cloud Functions triggered by Pub/Sub events, see Pub/Sub Triggers and Pub/Sub Tutorial.

Cloud Storage example

This example shows a CloudEvent function triggered by Cloud Storage events. Every time an object is created in a Cloud Storage bucket, the function is invoked, and a message about the change is written to the log.

C#

using CloudNative.CloudEvents;
using Google.Cloud.Functions.Framework;
using Google.Events.Protobuf.Cloud.Storage.V1;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;

namespace HelloGcs
{
    public class Function : ICloudEventFunction<StorageObjectData>
    {
        private readonly ILogger _logger;

        public Function(ILogger<Function> logger) =>
            _logger = logger;

        public Task HandleAsync(CloudEvent cloudEvent, StorageObjectData data, CancellationToken cancellationToken)
        {
            _logger.LogInformation("Event: {event}", cloudEvent.Id);
            _logger.LogInformation("Event Type: {type}", cloudEvent.Type);
            _logger.LogInformation("Bucket: {bucket}", data.Bucket);
            _logger.LogInformation("File: {file}", data.Name);
            _logger.LogInformation("Metageneration: {metageneration}", data.Metageneration);
            _logger.LogInformation("Created: {created:s}", data.TimeCreated?.ToDateTimeOffset());
            _logger.LogInformation("Updated: {updated:s}", data.Updated?.ToDateTimeOffset());
            return Task.CompletedTask;
        }
    }
}

Ruby

require "functions_framework"

FunctionsFramework.cloud_event "hello_gcs" do |event|
  # The event parameter is a CloudEvents::Event::V1 object.
  # See https://cloudevents.github.io/sdk-ruby/latest/CloudEvents/Event/V1.html
  payload = event.data

  logger.info "Event: #{event.id}"
  logger.info "Event Type: #{event.type}"
  logger.info "Bucket: #{payload['bucket']}"
  logger.info "File: #{payload['name']}"
  logger.info "Metageneration: #{payload['metageneration']}"
  logger.info "Created: #{payload['timeCreated']}"
  logger.info "Updated: #{payload['updated']}"
end

For more information about deploying CloudEvent functions triggered by Cloud Storage events, see Cloud Storage Triggers and Cloud Storage Tutorial.

Tips and tricks

Event logging

Event contents are not automatically logged, as they might contain confidential information. If you want to log event contents, you must do so explicitly as described in Writing, Viewing, and Responding to Logs.

Terminating CloudEvent functions

If a CloudEvent function creates background tasks, you must resolve these tasks before returning from your function to avoid errors and/or undefined behavior.

Automatic retries

CloudEvent functions can be configured to automatically retry failed invocations. See Retrying Event-Driven Functions for more information.

Next steps