Skip to content

Feature request: idempotent function wrapper #1305

Closed
@saragerion

Description

@saragerion

Use Case

Users who can't or don't use class-based decorators or Middy should be able to make arbitrary functions idempotent by using a function wrapper. This wrapper, also known in the industry as higher-order function should take the function to be made idempotent as first argument and an object with options and configs as second one.

Solution/User Experience

import { 
  makeFunctionIdempotent, 
  DynamoDBPersistenceLayer,
  IdempotencyConfig
} from '@aws-lambda-powertools/idempotency';

const config = new IdempotencyConfig({...});
const ddbPersistenceLayer = new DynamoDBPersistenceLayer({...});

 /**
 * Function to process a single record
 */
function processRecord(record: any) {
  /* ...Function logic here... */
  return result;
} 

/**
 * Higher-order function wrapper to process a single record
 */
const processIdempotently = makeFunctionIdempotent(
  processRecord, 
 {
    persistenceStore: ddbPersistenceLayer,
    dataArgument: 'record', 
    config,
 }  
);

export const handler = async (_event: any, _context: any): Promise<void> => {
    
  const records = /*..Extract SQS/DDB stream record, etc..*/

  const results = [];
  for (const record of records) {
    results.push(processIdempotently(record));
  }
  /* ...Format and return result... */
}

The makeFunctionIdempotent function wrapper should be able wrap both async and sync functions. It should accept the wrapped function (aka the function to be made idempotent) as first argument, and an object with mandatory persistenceStore and dataArgument, as well as an optional config one. The former should be an instance of any class that extends BasePersistenceLayer, the second should be a string that represents the argument to be used for idempotency (in the wrapped function), while the latter should be an instance of the class IdempotencyConfig.

Following the Powertools for Python implementation, the wrapper should:

  • return early if the POWERTOOLS_IDEMPOTENCY_DISABLED env variable has a truthy value (using EnvironmentVariableService)
  • use the provided config object or instantiate a new one if none is passed
  • register the Lambda context into the config object (used to manage timeouts)
  • instantiate an IdempotencyHandler
  • call & return the IdempotencyHandler.handle() method

This last step will ensure that the IdempotencyHandler will perform all the actions needed to make the function idempotent.

Alternative solutions

No response

Acknowledgment

Metadata

Metadata

Assignees

Labels

completedThis item is complete and has been merged/shippedfeature-requestThis item refers to a feature request for an existing or new utilityidempotencyThis item relates to the Idempotency Utility

Type

No type

Projects

Status

Shipped

Relationships

None yet

Development

No branches or pull requests

Issue actions