Éviter les tentatives répétées à l'infini dans Cloud Functions
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cet exemple montre comment éviter les tentatives répétées à l'infini dans Cloud Functions en limitant l'exécution à une période fixée après l'événement déclencheur.
En savoir plus
Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","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)."]]