Development Guidelines
  • 25 Apr 2024
  • 3 Minutes To Read
  • Dark
    Light
  • PDF

Development Guidelines

  • Dark
    Light
  • PDF

Article Summary

You can follow the below development guidelines while working with Event Driven Functions.

Function handler

Your function should export a default async method which accepts two arguments and returns nothing (Promise<void>):

export default async function handle(events: StreamingEvent[], context: Context): Promise<void> {
    //process events here
}

First argument is a list of streaming events. StreamingEvent model corresponds to a Mambu Streaming API Event model which is documented in here

Second input parameter is Context which contains the following methods:

MethodDescription
getSecret(secretName: string): Promise<secret>Retrieves a secret value which was previously created via API or Mambu cli. Returned object (Secret) fields are 'name: string - name of the secret' and 'value: string - value of the secret'

Parallel processing

On each invocation your function will receive multiple events (a batch). Depending on your business use case, you will need to iterate over the batch and apply required business logic to each event. To achieve optimal performance, your code should process those events in parallel. Here is an example how parallel execution can be achieved:

export default async function handle(events: StreamingEvent[], context: Context): Promise<void> {
    const promises = events.map((event) => processEvent(event, context));
    await Promise.all(promises);
}

async function processEvent(event: StreamingEvent, context: Context): Promise<void> {
    //Process event.
}

Idempotency

Streaming Mambu Functions ensure at-least-once delivery guarantee. This means your function can be invoked multiple times for the same batch of events. This can happen in case of automatic retry mechanism is engaged. Your code should be able to gracefully handle duplicated events - this property is called idempotency. If your code is calling external APIs, those APIs should also be idempotent.

Streaming event field metadata.eid can be used to identify duplicate events. metadata.eid can also be used directly as Idempotency key when calling Mambu APIs.

Mambu APIs offer two ways to provide an idempotency key:

  • Provide a header Idempotency-Key: string as part of the request, more details can be found here.
  • Provide externalId in the request body. E.g. *Deposits “fee-transactions” API: { "amount": 0, "externalId": "string", "notes": "string", "predefinedFeeKey": "string" } * This is only supported for some of the APIs - please check Mambu API v2 reference.

It is recommended to use both as they cover different cases. Both are demonstrated in the example project (STREAMING_EVENTS template) in src/api.ts.

Example:

export async function applyFee(
    accountId: string,
    feeKey: string,
    feeAmount: Big,
    idempotencyKey: string,
    config: ApiConfiguration
): Promise<unknown> {
    const response = await fetch(`${config.apiUrl}/deposits/${accountId}/fee-transactions`, {
        headers: Object.assign({ 'Idempotency-Key': idempotencyKey }, config.headers),
        method: 'POST',
        body: JSON.stringify({ predefinedFeeKey: feeKey, amount: feeAmount, externalId: idempotencyKey })
    });

    if (!response.ok) {
        const error = await HttpError.fromResponse(response);

        const msg = String(error);
        if (msg.includes('EXTERNAL_ID_ALREADY_EXISTS')) {
            return;
        } else {
            throw error;
        }
    }

    return response.json();
}

Supported Web APIs

Your function should be transpiled to ECMAScript 2020 Language Specification. Only the following web APIs are supported:

APIDescription
fetchExecutes remote HTTP calls
console.log, console.info, console.debug, console.warn, console.errorCreate log entries. Logs can be fetched via Mambu CLI command mambu functions logs -n [function-name]. See Retrieving function logs section for more details.

Memory and time limitations

The following limits apply to Event Driven Functions:

Runtime memory is limited to 2048 MB: The system enforces a memory limit for each Function. A portion of this memory is reserved for the Function's runtime.

Execution timeout is limited to 10 minutes: The system enforces an execution timeout for any Function exceeding this duration.

Events ordering

Order in which events are sent to your function is not guaranteed to be the same as order in which events occurred. Please carefully consider whether this impacts your Event Driven Function use case.

Remote Destination API Inbound IP Address Whitelisting

Mambu Function requests to your endpoints will originate from a fixed set of IP addresses per Mambu region. These IP addresses can be whitelisted in your firewall. Any changes to IP addresses will be announced on our Status Page as well.

If you need to know the sender IP addresses for your environment, please contact us through Mambu Support.


Was this article helpful?