Evita los reintentos infinitos en Cloud Functions
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En este ejemplo, se muestra cómo evitar los reintentos infinitos en Cloud Functions. Para ello, ejecuta solo un período determinado después del evento de activación.
Explora más
Para obtener documentación detallada en la que se incluye esta muestra de código, consulta lo siguiente:
Muestra de código
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis code demonstrates a method to prevent infinite retries in Cloud Functions by ensuring execution only occurs within a set timeframe after the triggering event.\u003c/p\u003e\n"],["\u003cp\u003eThe examples provided utilize event timestamps to determine the age of an event, allowing the function to ignore events that are older than a predefined threshold.\u003c/p\u003e\n"],["\u003cp\u003eThe logic for handling event timeouts and halting retries is implemented across multiple languages, including Go, Java, Node.js, and Python.\u003c/p\u003e\n"],["\u003cp\u003eTo avoid a retry loop, the functions check if the event's age exceeds a specific limit, such as 10 seconds, and if so, log a message and cease retries, thus preventing the function from continuously attempting to process an expired event.\u003c/p\u003e\n"],["\u003cp\u003eTo properly use Cloud Run functions, you must also set up Application Default Credentials.\u003c/p\u003e\n"]]],[],null,["# Avoid infinite retries in Cloud Functions\n\nThis sample demonstrates how to avoid infinite retries in Cloud Functions by only executing within a certain time period after the triggering event.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Enable event-driven function retries](/functions/docs/bestpractices/retries)\n- [Enable event-driven function retries](/run/docs/tips/function-retries)\n\nCode sample\n-----------\n\n### Go\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // Package tips contains tips for writing Cloud Functions in Go.\n package tips\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"log\"\n \t\"time\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n \t\"github.com/cloudevents/sdk-go/v2/event\"\n )\n\n func init() {\n \tfunctions.CloudEvent(\"FiniteRetryPubSub\", FiniteRetryPubSub)\n }\n\n // MessagePublishedData contains the full Pub/Sub message\n // See the documentation for more details:\n // https://cloud.google.com/eventarc/docs/cloudevents#pubsub\n type MessagePublishedData struct {\n \tMessage PubSubMessage\n }\n\n // PubSubMessage is the payload of a Pub/Sub event.\n // See the documentation for more details:\n // https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage\n type PubSubMessage struct {\n \tData []byte `json:\"data\"`\n }\n\n // FiniteRetryPubSub demonstrates how to avoid inifinite retries.\n func FiniteRetryPubSub(ctx context.Context, e event.Event) error {\n \tvar msg MessagePublishedData\n \tif err := e.DataAs(&msg); err != nil {\n \t\treturn fmt.Errorf(\"event.DataAs: %w\", err)\n \t}\n\n \t// Ignore events that are too old.\n \texpiration := e.Time().Add(10 * time.Second)\n \tif time.Now().After(expiration) {\n \t\tlog.Printf(\"event timeout: halting retries for expired event '%q'\", e.ID())\n \t\treturn nil\n \t}\n\n \t// Add your message processing logic.\n \treturn processTheMessage(msg)\n }\n\n### Java\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import com.google.cloud.functions.CloudEventsFunction;\n import io.cloudevents.CloudEvent;\n import java.time.Duration;\n import java.time.ZoneOffset;\n import java.time.ZonedDateTime;\n import java.util.logging.Logger;\n\n public class RetryTimeout implements CloudEventsFunction {\n private static final Logger logger = Logger.getLogger(RetryTimeout.class.getName());\n private static final long MAX_EVENT_AGE = 10_000;\n\n /**\n * Cloud Event Function that only executes within\n * a certain time period after the triggering event\n */\n @Override\n public void accept(CloudEvent event) throws Exception {\n ZonedDateTime utcNow = ZonedDateTime.now(ZoneOffset.UTC);\n ZonedDateTime timestamp = event.getTime().atZoneSameInstant(ZoneOffset.UTC);\n\n long eventAge = Duration.between(timestamp, utcNow).toMillis();\n\n // Ignore events that are too old\n if (eventAge \u003e MAX_EVENT_AGE) {\n logger.info(String.format(\"Dropping event with timestamp %s.\", timestamp));\n return;\n }\n\n // Process events that are recent enough\n // To retry this invocation, throw an exception here\n logger.info(String.format(\"Processing event with timestamp %s.\", timestamp));\n }\n }\n\n### Node.js\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const functions = require('@google-cloud/functions-framework');\n\n /**\n * Cloud Event Function that only executes within\n * a certain time period after the triggering event\n *\n * @param {object} event The Cloud Functions event.\n * @param {function} callback The callback function.\n */\n functions.cloudEvent('avoidInfiniteRetries', (event, callback) =\u003e {\n const eventAge = Date.now() - Date.parse(event.time);\n const eventMaxAge = 10000;\n\n // Ignore events that are too old\n if (eventAge \u003e eventMaxAge) {\n console.log(`Dropping event ${event} with age ${eventAge} ms.`);\n callback();\n return;\n }\n\n // Do what the function is supposed to do\n console.log(`Processing event ${event} with age ${eventAge} ms.`);\n\n // Retry failed function executions\n const failed = false;\n if (failed) {\n callback('some error');\n } else {\n callback();\n }\n });\n\n### Python\n\n\nTo authenticate to Cloud Run functions, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n from datetime import datetime, timezone\n\n # The 'python-dateutil' package must be included in requirements.txt.\n from dateutil import parser\n\n import functions_framework\n\n\n @functions_framework.cloud_event\n def avoid_infinite_retries(cloud_event):\n \"\"\"Cloud Event Function that only executes within a certain\n time period after the triggering event.\n\n Args:\n cloud_event: The cloud event associated with the current trigger\n Returns:\n None; output is written to Stackdriver Logging\n \"\"\"\n timestamp = cloud_event[\"time\"]\n\n event_time = parser.parse(timestamp)\n event_age = (datetime.now(timezone.utc) - event_time).total_seconds()\n event_age_ms = event_age * 1000\n\n # Ignore events that are too old\n max_age_ms = 10000\n if event_age_ms \u003e max_age_ms:\n print(\"Dropped {} (age {}ms)\".format(cloud_event[\"id\"], event_age_ms))\n return \"Timeout\"\n\n # Do what the function is supposed to do\n print(\"Processed {} (age {}ms)\".format(cloud_event[\"id\"], event_age_ms))\n return # To retry the execution, raise an exception here\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=functions)."]]