Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Atlas App Services

Enviar eventos de activadores a AWS EventBridge

MongoDB offers an AWS Eventbridge partner event source that lets you send Atlas Trigger events to an event bus instead of calling an Atlas Function. You can configure any Trigger type to send events to EventBridge. Database Triggers also support custom error handling, to reduce trigger suspensions due to non-critical errors.

Todo lo que necesitas para enviar eventos de activador a EventBridge es un ID de cuenta de AWS. Esta guía recorre cómo encontrar tu ID de cuenta, configurar el activador, asociar la fuente del evento del activador con un bus de eventos y configurar la gestión personalizada de errores.

Nota

Guía oficial de fuente de eventos asociados de AWS

Esta guía se basa en la documentación de Amazon Recepción de eventos de un proveedor SaaS.

Nota

The AWS put entry for an EventBridge trigger event must be smaller than 256 KB.

Learn how to reduce the size of your PutEvents entry in the Performance Optimization section.

1

Para enviar eventos activadores a AWS EventBridge, necesitas el AWS account ID de la cuenta que debe recibir los eventos. Abra la consola de Amazon EventBridge y Partner event sources haga clic en en el menú de navegación. Busque la fuente de eventos del MongoDB socio y haga clic Set up en.

On the MongoDB partner event source page, click Copy to copy your AWS account ID to the clipboard.

2

Once you have the AWS account ID, you can configure a trigger to send events to EventBridge.

In the App Services UI, create and configure a new database trigger, authentication trigger, or scheduled trigger and select the EventBridge event type.

Paste in the AWS Account ID that you copied from EventBridge and select an AWS Region to send the trigger events to.

Opcionalmente, puedes configurar una función para manejar errores de activación. La gestión de errores personalizada solo es válida para activadores de base de datos. Para más detalles, consulta la sección Gestión de errores personalizada en esta página.

The EventBridge input boxes in the trigger configuration.

By default, triggers convert the BSON types in event objects into standard JSON types. To preserve BSON type information, you can serialize event objects into Extended JSON format instead. Extended JSON preserves type information at the expense of readability and interoperability.

To enable Extended JSON, click the Enable Extended JSON toggle in the Advanced (Optional) section.

Create a trigger configuration file in the /triggers directory. Omit the function_name field and define an AWS_EVENTBRIDGE event processor.

Set the account_id field to the AWS Account ID that you copied from EventBridge and set the region field to an AWS Region.

By default, triggers convert the BSON types in event objects into standard JSON types. To preserve BSON type information, you can serialize event objects into Extended JSON format instead. Extended JSON preserves type information at the expense of readability and interoperability.

To enable Extended JSON, set the extended_json_enabled field to true.

Opcionalmente, puedes configurar una función para manejar errores de activación. La gestión de errores personalizada solo es válida para activadores de base de datos. Para más detalles, consulta la sección Gestión de errores personalizada en esta página.

The trigger configuration file should resemble the following:

{
"name": "...",
"type": "...",
"event_processors": {
"AWS_EVENTBRIDGE": {
"config": {
"account_id": "<AWS Account ID>",
"region": "<AWS Region>",
"extended_json_enabled": <boolean>
}
}
}
}

Nota

Regiones de AWS compatibles

Para obtener una lista completa de las regiones de AWS compatibles, consulte la guía de Amazon Recibiendo eventos de un socio SaaS.

3

Go back to the EventBridge console and choose Partner event sources in the navigation pane. In the Partner event sources table, find and select the Pending trigger source and then click Associate with event bus.

En la pantalla Associate with event bus, define los permisos de acceso que se requieran para otras cuentas y organizaciones, y luego haz clic en Associate.

Once confirmed, the status of the trigger event source changes from Pending to Active, and the name of the event bus updates to match the event source name. You can now start creating rules that trigger on events from that partner event source. For more information, see Creating a Rule That Triggers on a SaaS Partner Event.

Nota

Only Database Triggers Support Custom Error Handlers

Currently, only database triggers support custom error handling. Authentication triggers and scheduled triggers do not support custom error handling at this time.

You can create an error handler to be executed on a trigger failure, when retry does not succeed. Custom error handling allows you to determine whether an error from AWS EventBridge is critical enough to suspend the Trigger, or if it is acceptable to ignore the error and continue processing other events. For more information on suspended database triggers, refer to Suspended Triggers.

Puedes crear la nueva función directamente en la página Crear un activador, como se muestra a continuación, o desde la pestaña Funciones. Para obtener más información sobre cómo definir funciones en App Services, consulta Definir una función.

The EventBridge custom error handling configuration in the UI.
1

En la sección Configure Error Function, seleccione + New Function.

You can also select an existing Function, if one is already defined, from the dropdown.

2

Escribe un nombre único e identificador para la función en el campo Name. Este nombre debe ser diferente al de todas las demás funciones de la aplicación.

3

In the Function section, write the JavaScript code directly in the function editor. The function editor contains a default function that you can edit as needed. For more information on creating functions, refer to the Functions documentation.

4

In the Testing Console tab beneath the function editor, you can test the function by passing in example values to the error and changeEvent parameters, as shown in the comments of the testing console.

Para obtener más información sobre estos parámetros, consulte la sección Parámetros del controlador de errores en esta página.

Click Run to run the test.

5

Once you are satisfied with the custom error handler, click Save.

In order to update your trigger's configuration with an error handler, follow these steps to Update an App. When you update your configuration files in Step 3, do the following:

1

Follow the steps in Define a Function to write your error handler source code and configuration file.

For the error handler source code, see the following template error handler:

<functionName>.js
exports = async function(error, changeEvent) {
// This sample function will log additional details if the error is not
// a DOCUMENT_TOO_LARGE error
if (error.code === 'DOCUMENT_TOO_LARGE') {
console.log('Document too large error');
// Comment out the line below in order to skip this event and not suspend the Trigger
throw new Error(`Encountered error: ${error.code}`);
}
console.log('Error sending event to EventBridge');
console.log(`DB: ${changeEvent.ns.db}`);
console.log(`Collection: ${changeEvent.ns.coll}`);
console.log(`Operation type: ${changeEvent.operationType}`);
// Throw an error in your function to suspend the trigger and stop processing additional events
throw new Error(`Encountered error: ${error.message}`);
};
2

Add an error_handler attribute to your trigger configuration file in the Triggers folder. The trigger configuration file should resemble the following:

<triggerName>.json
{
"name": "...",
"type": "DATABASE",
"event_processors": {
"AWS_EVENTBRIDGE": {
"config": {
"account_id": "<AWS Account ID>",
"region": "<AWS Region>",
"extended_json_enabled": <boolean>
}
}
},
"error_handler": {
"config": {
"enabled": <boolean>,
"function_name": "<Error Handler Function Name>"
}
}
}

For more information on trigger configuration files, see Trigger Configuration Files.

1

Call the admin user authentication endpoint with your MongoDB Atlas API key pair:

curl -X POST \
https://services.cloud.mongodb.com/api/admin/v3.0/auth/providers/mongodb-cloud/login \
-H 'Content-Type: application/json' \
-H 'Accept: application/json' \
-d '{
"username": "<Public API Key>",
"apiKey": "<Private API Key>"
}'

If authentication succeeds, the response body contains a JSON object with an access_token value:

{
"access_token": "<access_token>",
"refresh_token": "<refresh_token>",
"user_id": "<user_id>",
"device_id": "<device_id>"
}

El access_token concede acceso a la API de Administración de App Services. Debe incluirlo como un token Bearer en el encabezado Authorization para todas las solicitudes a la API de administración.

Tip

2

A draft represents a group of application changes that you can deploy or discard as a single unit. If you don't create a draft, updates automatically deploy individually.

To create a draft, send a POST request with no body to the Create a Deployment Draft endpoint:

curl -X POST 'https://services.cloud.mongodb.com/api/admin/v3.0/groups/{groupId}/apps/{appId}/drafts' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <access_token>'
3

Create the function to handle errors for a failed AWS EventBridge trigger via a POST request to the Create a new Function endpoint.

curl -X POST \
https://services.cloud.mongodb.com/api/admin/v3.0/groups/{groupId}/apps/{appId}/functions \
-H 'Authorization: Bearer <access_token>' \
-d '{
"name": "string",
"private": true,
"source": "string",
"run_as_system": true
}'
4

Create the AWS EventBridge Trigger with error handling enabled via a POST request to the Create a Trigger endpoint.

curl -X POST \
https://services.cloud.mongodb.com/api/admin/v3.0/groups/{groupId}/apps/{appId}/triggers \
-H 'Authorization: Bearer <access_token>' \
-d '{
"name": "string",
"type": "DATABASE",
"config": {
"service_id": "string",
"database": "string",
"collection": "string",
"operation_types": {
"string"
},
"match": ,
"full_document": false,
"full_document_before_change": false,
"unordered": true
},
"event_processors": {
"AWS_EVENTBRIDGE": {
"account_id": "string",
"region": "string",
"extended_json_enabled": false
},
},
"error_handler": {
"enabled": true,
"function_id": "string"
}
}'
5

If you created a draft, you can deploy all changes in the draft by sending a POST request with no body to the Deploy a deployment draft endpoint. If you did not create a draft as a first step, the individual function and trigger requests deployed automatically.

curl -X POST \
'https://services.cloud.mongodb.com/api/admin/v3.0/groups/{groupId}/apps/{appId}/drafts/{draftId}/deployment' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <access_token>' \

The default error handler has two parameters: error and changeEvent.

Tiene los siguientes dos atributos:

  • code: el código para la solicitud de registro con error de EventBridge. Para obtener una lista de los códigos de error utilizados por el controlador de errores, consulta la sección a continuación.

  • message: El mensaje de error no filtrado de una solicitud fallida de EventBridge put.

The requested change to your data made by EventBridge. For more information on types of change events and their configurations, see Change Event Types.

If an error was recevied from EventBridge, the event processor will parse the error as either DOCUMENT_TOO_LARGE or OTHER. This parsed error is passed to the error handler function through the error parameter.

If the put entry for an EventBridge trigger event is larger than 256 KB, EventBridge will throw an error. The error will contain either:

Para obtener más información sobre cómo reducir el tamaño de entrada, consulta la sección a continuación de Optimización de rendimiento.

The default bucket for all other errors.

Tip

Optimiza el manejo de errores para los errores con código OTHER

You can make special error handling cases for your most common error messages to optimize your error handling for errors with an OTHER code. To determine which errors need special cases, we recommended keeping track of the most common error messages you receive in error.message.

You can view Trigger Error Handler logs for your EventBridge Trigger error handler in the application logs.

  1. Click Logs in the left navigation of the App Services UI.

  2. Click the Filter by Type dropdown and select Triggers Error Handlers to view all error handler logs for the App.

Pasa el valor trigger_error_handler a la bandera --type para ver todos los registros del manejador de errores de la aplicación.

appservices logs list --type=trigger_error_handler

Recupera registros de tipo TRIGGER_ERROR_HANDLER a través de una solicitud GET al extremo Recuperar registros de Servicios de aplicación:

curl -X GET 'https://services.cloud.mongodb.com/api/admin/v3.0/groups/{groupId}/apps/{appId}/logs' \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <access_token>'
-d '{
"type": "TRIGGER_ERROR_HANDLER"
}'

To learn more about viewing application logs, see View Application Logs.

El siguiente objeto configura un activador para enviar eventos a AWS Eventbridge y gestionar errores:

"event_processors": {
"AWS_EVENTBRIDGE": {
"config": {
"account_id": "012345678901",
"region": "us-east-1"
}
}
},
"error_handler": {
"config": {
"enabled": true,
"function_name": "myErrorHandler.js"
}
}

The AWS put entry for an EventBridge trigger event must be smaller than 256 KB.

Para obtener más información, consulta la Documentación de AWS para calcular el tamaño de entrada del evento Amazon PutEvents.

When using Database Triggers, the Project Expression can be useful reduce the document size before sending messages to EventBridge. This expression lets you include only specified fields, reducing document size.

Learn more in the Database Trigger Project Expression documentation.

Next

¿Qué son los servicios de aplicación Atlas?

En esta página