Realiza pruebas localmente con el emulador de Pub/Sub

Puedes probar funciones de forma local antes de implementarlas mediante Functions Framework junto con el emulador de Pub/Sub. En los ejemplos de esta página, se usa Cloud Functions (2nd gen).

Usa Functions Framework con el emulador de Pub/Sub

Puedes activar una función de forma local con un mensaje push desde el emulador de Pub/Sub.

Prueba esta función como se describe aquí. Ten en cuenta que es necesario que uses tres instancias de terminal independientes:

  1. Asegúrate de haber instalado la herramienta de pack y Docker.

  2. En la primera terminal, inicia el emulador de Pub/Sub en el puerto 8043 en un proyecto local:

    gcloud beta emulators pubsub start \
        --project=abc \
        --host-port='localhost:8043'
    
  3. En la segunda terminal, crea un tema y una suscripción de Pub/Sub:

    curl -s -X PUT 'http://localhost:8043/v1/projects/abc/topics/mytopic'
    

    Usa http://localhost:8080 como el extremo de la suscripción de envío.

    curl -s -X PUT 'http://localhost:8043/v1/projects/abc/subscriptions/mysub' \
        -H 'Content-Type: application/json' \
        --data '{"topic":"projects/abc/topics/mytopic","pushConfig":{"pushEndpoint":"http://localhost:8080/projects/abc/topics/mytopic"}}'
    
  4. En la tercera terminal, clona el repositorio de muestra en tu máquina local:

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo zip y extraerla.

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    De manera opcional, puedes descargar la muestra como un archivo zip y extraerla.

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    De manera opcional, puedes descargar la muestra como un archivo ZIP y extraerla.

    Ve al directorio que contiene el código de muestra de Cloud Functions, como sigue:

    Node.js

    cd nodejs-docs-samples/functions/v2/helloPubSub/

    Python

    cd python-docs-samples/functions/v2/pubsub/

    Go

    cd golang-samples/functions/functionsv2/hellopubsub/

    Observa el código de muestra:

    Node.js

    const functions = require('@google-cloud/functions-framework');
    
    // Register a CloudEvent callback with the Functions Framework that will
    // be executed when the Pub/Sub trigger topic receives a message.
    functions.cloudEvent('helloPubSub', cloudEvent => {
      // The Pub/Sub message is passed as the CloudEvent's data payload.
      const base64name = cloudEvent.data.message.data;
    
      const name = base64name
        ? Buffer.from(base64name, 'base64').toString()
        : 'World';
    
      console.log(`Hello, ${name}!`);
    });

    Python

    import base64
    
    from cloudevents.http import CloudEvent
    import functions_framework
    
    
    # Triggered from a message on a Cloud Pub/Sub topic.
    @functions_framework.cloud_event
    def subscribe(cloud_event: CloudEvent) -> None:
        # Print out the data from Pub/Sub, to prove that it worked
        print(
            "Hello, " + base64.b64decode(cloud_event.data["message"]["data"]).decode() + "!"
        )
    
    

    Go

    
    // Package helloworld provides a set of Cloud Functions samples.
    package helloworld
    
    import (
    	"context"
    	"fmt"
    	"log"
    
    	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
    	"github.com/cloudevents/sdk-go/v2/event"
    )
    
    func init() {
    	functions.CloudEvent("HelloPubSub", helloPubSub)
    }
    
    // MessagePublishedData contains the full Pub/Sub message
    // See the documentation for more details:
    // https://cloud.google.com/eventarc/docs/cloudevents#pubsub
    type MessagePublishedData struct {
    	Message PubSubMessage
    }
    
    // PubSubMessage is the payload of a Pub/Sub event.
    // See the documentation for more details:
    // https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
    type PubSubMessage struct {
    	Data []byte `json:"data"`
    }
    
    // helloPubSub consumes a CloudEvent message and extracts the Pub/Sub message.
    func helloPubSub(ctx context.Context, e event.Event) error {
    	var msg MessagePublishedData
    	if err := e.DataAs(&msg); err != nil {
    		return fmt.Errorf("event.DataAs: %w", err)
    	}
    
    	name := string(msg.Message.Data) // Automatically decoded from base64.
    	if name == "" {
    		name = "World"
    	}
    	log.Printf("Hello, %s!", name)
    	return nil
    }
    

    Crea el paquete de compilación (esto puede demorar unos minutos):

    Node.js

    pack build \
      --builder gcr.io/buildpacks/builder:v1 \
      --env GOOGLE_FUNCTION_SIGNATURE_TYPE=event \
      --env GOOGLE_FUNCTION_TARGET=helloPubSub \
      my-function
    

    Python

    pack build \
      --builder gcr.io/buildpacks/builder:v1 \
      --env GOOGLE_FUNCTION_SIGNATURE_TYPE=event \
      --env GOOGLE_FUNCTION_TARGET=subscribe \
      my-function
    

    Go

    pack build \
      --builder gcr.io/buildpacks/builder:v1 \
      --env GOOGLE_FUNCTION_SIGNATURE_TYPE=event \
      --env GOOGLE_FUNCTION_TARGET=HelloPubSub \
      my-function
    

    Inicia la función de Pub/Sub en el puerto 8080. Aquí es donde el emulador enviará mensajes push:

    docker run --rm -p 8080:8080 my-function
    
  5. En la segunda terminal, invoca la función mediante la publicación de un mensaje. Los datos del mensaje deben estar codificados en formato Base64. En este ejemplo, se usa la string codificada en Base64 {"foo":"bar"}.

    curl -s -X POST 'http://localhost:8043/v1/projects/abc/topics/mytopic:publish' \
        -H 'Content-Type: application/json' \
        --data '{"messages":[{"data":"eyJmb28iOiJiYXIifQ=="}]}'
    

    Deberías ver el resultado de la función en la tercera terminal.

    Presiona Ctrl+C para anular.