Heim  >  Artikel  >  Web-Frontend  >  Middleware für Schrittfunktionen: Payloads automatisch aus Amazon S3 speichern und laden

Middleware für Schrittfunktionen: Payloads automatisch aus Amazon S3 speichern und laden

王林
王林Original
2024-08-21 06:18:36701Durchsuche

Ich möchte Middy-Store vorstellen, eine neue Bibliothek, die ich in den letzten Monaten aufgebaut habe. Ich habe eine Weile über diese Idee nachgedacht und bin auf diese Funktionsanfrage zurückgekommen, die ich vor mehr als einem Jahr gestellt habe. middy-store ist eine Middleware für Middy, die Nutzlasten automatisch von und zu einem Store wie Amazon S3 oder möglicherweise anderen Diensten speichert und lädt.

Motivation

AWS-Dienste unterliegen bestimmten Grenzen, die man beachten muss. AWS Lambda hat beispielsweise ein Nutzlastlimit von 6 MB für synchrone Aufrufe und 256 KB für asynchrone Aufrufe. AWS Step Functions ermöglicht eine maximale Eingabe- oder Ausgabegröße von 256 KB an Daten als UTF-8-codierte Zeichenfolge. Wenn Sie dieses Limit bei der Rückgabe von Daten überschreiten, wird die berüchtigte States.DataLimitExceeded-Ausnahme auftreten.

Middleware for Step Functions: Automatically Store and Load Payloads from Amazon S3

Die übliche Problemumgehung für diese Einschränkung besteht darin, die Größe Ihrer Nutzlast zu überprüfen und sie vorübergehend in einem dauerhaften Speicher wie Amazon S3 zu speichern. Anschließend geben Sie die Objekt-URL oder den ARN für S3 zurück. Der nächste Lambda prüft, ob in der Eingabe eine URL oder ein ARN vorhanden ist, und lädt die Nutzlast aus S3. Wie man sich vorstellen kann, führt dies zu einer Menge Boilerplate-Code zum Speichern und Laden der Nutzlast von und nach Amazon S3, der in jedem Lambda wiederholt werden muss.

Middleware for Step Functions: Automatically Store and Load Payloads from Amazon S3

Dies wird noch umständlicher, wenn Sie nur einen Teil der Nutzlast auf S3 speichern und den Rest unverändert lassen möchten. Wenn Sie beispielsweise mit Schrittfunktionen arbeiten, könnte die Nutzlast Kontrollflussdaten für Zustände wie „Choice“ oder „Map“ enthalten, auf die direkt zugegriffen werden muss. Das bedeutet, dass der erste Lambda einen Teil der Nutzlast in S3 speichert und der nächste Lambda die Teilnutzlast von S3 laden und mit dem Rest der Nutzlast zusammenführen muss. Dazu muss sichergestellt werden, dass die Typen über mehrere Funktionen hinweg konsistent sind, was natürlich sehr fehleranfällig ist.

Wie es funktioniert

middy-store ist eine Middleware für Middy. Es ist an eine Lambda-Funktion angehängt und wird während eines Lambda-Aufrufs zweimal aufgerufen: vor und nach der Ausführung von Lambda handler(). Es empfängt die Eingabe, bevor der Handler ausgeführt wird, und empfängt die Ausgabe vom Handler, nachdem es fertig ist.

Middleware for Step Functions: Automatically Store and Load Payloads from Amazon S3

Beginnen wir am Ende mit der Ausgabe nach einem erfolgreichen Aufruf, um die Verständlichkeit zu erleichtern: middy-store empfängt die Ausgabe (die Nutzlast) von der Funktion handler() und überprüft die Größe. Um die Größe zu berechnen, wird die Nutzlast mit einem String versehen, wenn es sich um ein Objekt handelt, und mit Buffer.byteLength() wird die UTF-8-codierte Stringgröße berechnet. Wenn die Größe einen bestimmten konfigurierbaren Schwellenwert überschreitet, wird die Nutzlast in einem Store wie Amazon S3 gespeichert. Der Verweis auf die gespeicherte Nutzlast (z. B. eine S3-URL oder ein ARN) wird dann als Ausgabe anstelle der ursprünglichen Ausgabe zurückgegeben.

Schauen wir uns nun die nächste Lambda-Funktion (z. B. in einer Zustandsmaschine) an, die diese Ausgabe als Eingabe erhält. Dieses Mal betrachten wir die Eingabe bevor der handler() aufgerufen wird: middy-store empfängt die Eingabe an den Handler und sucht nach einem Verweis auf eine gespeicherte Nutzlast. Wenn eine gefunden wird, wird die Nutzlast aus dem Store geladen und als Eingabe an den Handler zurückgegeben. Der Handler verwendet die Nutzlast, als ob sie direkt an ihn übergeben worden wäre.

Hier ist ein Beispiel, um zu veranschaulichen, wie Middy-Store funktioniert:

/* ./src/functions/handler1.ts */
export const handler1 = middy()
  .use(
    middyStore({
      stores: [new S3Store({ /* S3 options */ })],
    })
  )
  .handler(async (input) => {
    // Return 1MB of random data as a base64 encoded string as output 
    return randomBytes(1024 * 1024).toString('base64');
  });

/* ./src/functions/handler2.ts */
export const handler2 = middy()
  .use(
    middyStore({
      stores: [new S3Store({ /* S3 options */ })],
    })
  )
  .handler(async (input) => {
    // Print the size of the input
    return console.log(`Size: ${Buffer.from(input, "base64").byteLength / 1024 / 1024} MB`);
  });

/* ./src/workflow.ts */
// First Lambda returns a large output
// It automatically uploads the data to S3 
const output1 = await handler1({});

// Output is a reference to the S3 object: { "@middy-store": "s3://bucket/key"}
console.log(output1); 

// Second Lambda receives the output as input
// It automatically downloads the data from S3
const output2 = await handler2(output1);

Was ist ein Geschäft?

Im Allgemeinen ist ein Store jeder Dienst, der es Ihnen ermöglicht, beliebige Nutzlasten zu speichern und zu laden, wie Amazon S3 oder andere persistente Speichersysteme. Datenbanken wie DynamoDB können auch als Store fungieren. Der Store empfängt eine Nutzlast vom Lambda-Handler, serialisiert sie (sofern es sich um ein Objekt handelt) und speichert sie im persistenten Speicher. Wenn der nächste Lambda-Handler die Nutzlast benötigt, lädt der Store die Nutzlast aus dem Speicher, deserialisiert sie und gibt sie zurück.

middy-store interagiert mit einem Store über eine StoreInterface-Schnittstelle, die jeder Store implementieren muss. Die Schnittstelle definiert die Funktionen canStore() und store() zum Speichern von Nutzdaten sowie canLoad() und load() zum Laden von Nutzdaten.

interface StoreInterface<TPayload = unknown, TReference = unknown> {
  name: string;
  canLoad: (args: LoadArgs<unknown>) => boolean;
  load: (args: LoadArgs<TReference | unknown>) => Promise<TPayload>;
  canStore: (args: StoreArgs<TPayload>) => boolean;
  store: (args: StoreArgs<TPayload>) => Promise<TReference>;
}
  • canStore() dient als Wächter, um zu überprüfen, ob der Store eine bestimmte Nutzlast speichern kann. Es empfängt die Nutzlast und ihre Bytegröße und prüft, ob die Nutzlast innerhalb der maximalen Größengrenzen des Stores liegt. Beispielsweise hat ein von DynamoDB unterstützter Store eine maximale Elementgröße von 400 KB, während ein S3-Store praktisch keine Begrenzung der Nutzlastgröße hat, die er speichern kann.

  • store() receives a payload and stores it in its underlying storage system. It returns a reference to the payload, which is a unique identifier to identify the stored payload within the underlying service. For example, the Amazon S3 Store uses an S3 URI in the format s3:/// as a reference, while other Amazon services might use ARNs.

  • canLoad() acts like a filter to check if the Store can load a certain reference. It receives the reference to a stored payload and checks if it's a valid identifier for the underlying storage system. For example, the Amazon S3 Store checks if the reference is a valid S3 URI, while a DynamoDB Store would check if it's a valid ARN.

  • load() receives the reference to a stored payload and loads the payload from storage. Depending on the Store, the payload will be deserialized into its original type according to the metadata that was stored alongside it. For example, a payload of type application/json will get parsed back into a JSON object, while a plain string of type text/plain will remain unaltered.

Single and Multiple Stores

Most of the time, you will only need one Store, like Amazon S3, which can effectively store any payload. However, middy-store lets you work with multiple Stores at the same time. This can be useful if you want to store different types of payloads in different Stores. For example, you might want to store large payloads in S3 and small payloads in DynamoDB.

Middleware for Step Functions: Automatically Store and Load Payloads from Amazon S3

middy-store accepts an Array in the options to provide one or more Stores. When middy-store runs before the handler and finds a reference in the input, it will iterate over the Stores and call canLoad() with the reference for each Store. The first Store that returns true will be used to load the payload with load().

On the other hand, when middy-store runs after the handler and the output is larger than the maximum allowed size, it will iterate over the Stores and call canStore() for each Store. The first Store that returns true will be used to store the payload with store().

Therefore, it is important to note that the order of the Stores in the array is important.

References

When a payload is stored in a Store, middy-store will return a reference to the stored payload. The reference is a unique identifier to find the stored payload in the Store. The value of the identifier depends on the Store and its configuration. For example, the Amazon S3 Store will use an S3 URI by default. However, it can also be configured to return other formats like an ARN arn:aws:s3:::/, an HTTP endpoint https://.s3.us-west-1.amazonaws.com/, or a structured object with the bucket and key.

The output from the handler after middy-store will contain the reference to the stored payload:

/* Output with reference */
{
  "@middy-store": "s3://bucket/key"
}

middy-store embeds the reference from the Store in the output as an object with a key "@middy-store". This allows middy-store to quickly find all references when the next Lambda function is called and load the payloads from the Store before the handler runs. In case you are wondering, middy-store recursively iterates through the input object and searches for the "@middy-store" key. That means the input can contain multiple references, even from different Stores, and middy-store will find and load them.

Selecting a Payload

By default, middy-store will store the entire output of the handler as a payload in the Store. However, you can also select only a part of the output to be stored. This is useful for workflows like AWS Step Functions, where you might need some of the data for control flow, e.g., a Choice state.

middy-store accepts a selector in its storingOptions config. The selector is a string path to the relevant value in the output that should be stored.

Here's an example:

const output = {
  a: {
    b: ['foo', 'bar', 'baz'],
  },
};

export const handler = middy()
  .use(
    middyStore({
      stores: [new S3Store({ /* S3 options */ })],
      storingOptions: {
        selector: '',          /* select the entire output as payload */
        // selector: 'a';      /* selects the payload at the path 'a' */
        // selector: 'a.b';    /* selects the payload at the path 'a.b' */
        // selector: 'a.b[0]'; /* selects the payload at the path 'a.b[0]' */
        // selector: 'a.b[*]'; /* selects the payloads at the paths 'a.b[0]', 'a.b[1]', 'a.b[2]', etc. */
      }
    })
  )
  .handler(async () => output);

await handler({});

The default selector is an empty string (or undefined), which selects the entire output as a payload. In this case, middy-store will return an object with only one property, which is the reference to the stored payload.

/* selector: '' */
{
  "@middy-store": "s3://bucket/key"
}

The selectors a, a.b, or a.b[0] select the value at the path and store only this part in the Store. The reference to the stored payload will be inserted at the path in the output, thereby replacing the original value.

/* selector: 'a' */
{
  a: {
    "@middy-store": "s3://bucket/key"
  }
}
/* selector: 'a.b' */
{
  a: {
    b: {
      "@middy-store": "s3://bucket/key"
    }
  }
}
/* selector: 'a.b[0]' */
{
  a: {
    b: [
      { "@middy-store": "s3://bucket/key" }, 
      'bar', 
      'baz'
    ]
  }
}

A selector ending with [*] like a.b[*] acts like an iterator. It will select the array at a.b and store each element in the array in the Store separately. Each element will be replaced with the reference to the stored payload.

/* selector: 'a.b[*]' */
{
  a: {
    b: [
      { "@middy-store": "s3://bucket/key" }, 
      { "@middy-store": "s3://bucket/key" }, 
      { "@middy-store": "s3://bucket/key" }
    ]
  }
}

Size Limit

middy-store will calculate the size of the entire output returned from the handler. The size is calculated by stringifying the output, if it's not already a string, and calculating the UTF-8 encoded size of the string in bytes. It will then compare this size to the configured minSize in the storingOptions config. If the output size is equal to or greater than the minSize, it will store the output or a part of it in the Store.

export const handler = middy()
  .use(
    middyStore({
      stores: [new S3Store({ /* S3 options */ })],
      storingOptions: {
        minSize: Sizes.STEP_FUNCTIONS,  /* 256KB */
        // minSize: Sizes.LAMBDA_SYNC,  /* 6MB */
        // minSize: Sizes.LAMBDA_ASYNC, /* 256KB */
        // minSize: 1024 * 1024,        /* 1MB */
        // minSize: Sizes.ZERO,         /* 0 */
        // minSize: Sizes.INFINITY,     /* Infinity */
        // minSize: Sizes.kb(512),      /* 512KB */
        // minSize: Sizes.mb(1),        /* 1MB */
      }
    })
  )
  .handler(async () => output);

await handler({});

middy-store provides a Sizes helper with some predefined limits for Lambda and Step Functions. If minSize is not specified, it will use Sizes.STEP_FUNCTIONS with 256KB as the default minimum size. The Sizes.ZERO (equal to the number 0) means that middy-store will always store the payload in a Store, ignoring the actual output size. On the other hand, Sizes.INFINITY (equal to Math.POSITIVE_INFINITY) means that it will never store the payload in a Store.

Stores

Currently, there is only one Store implementation for Amazon S3, but I'm planning to implement a Store backed by DynamoDB and DAX. DynamoDB, with its Time-To-Live (TTL) feature, provides a great option for short-term payloads that only need to exist during the execution of a workflow like Step Functions.

Amazon S3

The middy-store-s3 package provides a store implementation for Amazon S3. It uses the official @aws-sdk/client-s3 package to interact with S3.

import { middyStore } from 'middy-store';
import { S3Store } from 'middy-store-s3';

const handler = middy()
  .use(
    middyStore({
      stores: [
        new S3Store({
          config: { region: "us-east-1" },
          bucket: "bucket",
          key: () => randomUUID(),
          format: "arn",
        }),
      ],
    }),
  )
  .handler(async (input) => {
    return { /* ... */ };
  });

The S3Store only requires a bucket where the payloads are being stored. The key is optional and defaults to randomUUID(). The format configures the style of the reference that is returned after a payload is stored. The supported formats include arn, object, or one of the URL formats from the amazon-s3-url package. It's important to note that S3Store can load any of these formats; the format config only concerns the returned reference. The config is the S3 client configuration and is optional. If not set, the S3 client will resolve the config (credentials, region, etc.) from the environment or file system.

Custom Store

A new Store can be implemented as a class or a plain object, as long as it provides the required functions from the StoreInterface interface.

Here's an example of a Store to store and load payloads as base64 encoded data URLs:

import { StoreInterface, middyStore } from 'middy-store';

const base64Store: StoreInterface<string, string> = {
  name: "base64",
  /* Reference must be a string starting with "data:text/plain;base64," */
  canLoad: ({ reference }) => {
    return (
      typeof reference === "string" &&
      reference.startsWith("data:text/plain;base64,")
    );
  },
  /* Decode base64 string and parse into object */
  load: async ({ reference }) => {
    const base64 = reference.replace("data:text/plain;base64,", "");
    return Buffer.from(base64, "base64").toString();
  },
  /* Payload must be a string or an object */
  canStore: ({ payload }) => {
    return typeof payload === "string" || typeof payload === "object";
  },
  /* Stringify object and encode as base64 string */
  store: async ({ payload }) => {
    const base64 = Buffer.from(JSON.stringify(payload)).toString("base64");
    return `data:text/plain;base64,${base64}`;
  },
};

const handler = middy()
  .use(
    middyStore({
      stores: [base64Store],
      storingOptions: {
        minSize: Sizes.ZERO, /* Always store the data */ 
      }
    }),
  )
  .handler(async (input) => {
    /* Random text with 100 words */ 
    return `Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.`;
  });

const output = await handler(null, context);

/* Prints: { '@middy-store': 'data:text/plain;base64,IkxvcmVtIGlwc3VtIGRvbG9yIHNpdC...' } */
console.log(output);

This example is the perfect way to try middy-store, because it doesn't rely on external resources like an S3 bucket. You will find it in the repository at examples/custom-store and should be able to run it locally.

Contributions and Feedback

I've been tinkering with the API design for a while, and it's definitely not stable yet. I would love to get feedback on the current state as well as suggestions for changes or improvements. If you are eager to contribute to this project, please go ahead and submit feature requests or pull requests.

Middleware for Step Functions: Automatically Store and Load Payloads from Amazon S3 zirkelc / middy-store

Middleware for Step Functions: Automatically Store and Load Payloads

Middleware for Step Functions: Automatically Store and Load Payloads from Amazon S3 Middleware for Step Functions: Automatically Store and Load Payloads from Amazon S3 Middleware for Step Functions: Automatically Store and Load Payloads from Amazon S3

Middleware middy-store

middy-store is a middleware for Lambda that automatically stores and loads payloads from and to a Store like Amazon S3 or potentially other services.

Installation

You will need @middy/core >= v5 to use middy-store Please be aware that the API is not stable yet and might change in the future. To avoid accidental breaking changes, please pin the version of middy-store and its sub-packages in your package.json to an exact version.

npm install --save-exact @middy/core middy-store middy-store-s3 
Enter fullscreen mode Exit fullscreen mode

Motivation

AWS services have certain limits that one must be aware of. For example, AWS Lambda has a payload limit of 6MB for synchronous invocations and 256KB for asynchronous invocations. AWS Step Functions allows for a maximum input or output size of 256KB of data as a UTF-8 encoded string. If you exceed this limit when returning data, you will encounter the infamous States.DataLimitExceeded exception.

Middleware for Step Functions: Automatically Store and Load Payloads from Amazon S3

The usual workaround for this…

View on GitHub

Das obige ist der detaillierte Inhalt vonMiddleware für Schrittfunktionen: Payloads automatisch aus Amazon S3 speichern und laden. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn