diff --git a/s3-multipart-getpart-sqs-lambda/typescript/cdk/.gitignore b/s3-multipart-getpart-sqs-lambda/typescript/cdk/.gitignore new file mode 100644 index 000000000..81344fc85 --- /dev/null +++ b/s3-multipart-getpart-sqs-lambda/typescript/cdk/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +cdk.out/ +build/ +cdk.context.json +package-lock.json diff --git a/s3-multipart-getpart-sqs-lambda/typescript/cdk/README.md b/s3-multipart-getpart-sqs-lambda/typescript/cdk/README.md new file mode 100644 index 000000000..d73768dd6 --- /dev/null +++ b/s3-multipart-getpart-sqs-lambda/typescript/cdk/README.md @@ -0,0 +1,133 @@ +# Process Amazon S3 multipart upload parts while the upload is in progress with Amazon SQS and AWS Lambda + +This pattern sends the Amazon S3 `s3:MultipartUpload:PartUploaded` event for each uploaded part to an Amazon SQS queue. An AWS Lambda function reads that part with the Amazon S3 GetPart API before the upload completes, hashes it, and records it in an Amazon DynamoDB part ledger, which is marked COMPLETE or ABORTED when the upload ends. + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/s3-multipart-getpart-sqs-lambda-typescript-cdk + +Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. No resource in the stack has an hourly or provisioned charge: you pay for Amazon S3 requests and storage (each part read is a GET request), Amazon SQS requests, Lambda invocations and DynamoDB on-demand writes. + +## Requirements + +* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured +* [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) installed +* [Node.js](https://nodejs.org/en/download/) installed (the AWS CDK app and the function are written in TypeScript) +* [AWS CDK v2](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html), with your account and Region bootstrapped (`npx cdk bootstrap`). The commands below use `npx cdk`, which runs the CDK CLI version this project installs, so no global install is needed. The function is bundled with esbuild from the project's dev dependencies, so Docker is not needed. + +## Supported Regions + +The [announcement](https://aws.amazon.com/about-aws/whats-new/2026/11/amazon-s3-supports-reading-parts-multipart-uploads/) lists all AWS Regions, but when this pattern was written (November 30, 2026) both `PartUploaded` events and GetPart on an in-progress upload were seen working only in us-east-1. In ap-south-1 GetPart worked but no `PartUploaded` events arrived. GetPart returned `405 MethodNotAllowed` in us-east-2, us-west-2, eu-central-1, eu-west-1 and ap-southeast-1, and in us-west-2 the bucket accepted the notification configuration but delivered no `PartUploaded` events. Deploy in us-east-1. In another Region, depending on the Region, part events either do not arrive, so no parts are recorded, or GetPart fails with `MethodNotAllowed` and the message goes to the dead-letter queue after five tries. + +## How it works + +1. A client starts a multipart upload and uploads parts. Amazon S3 sends one `s3:MultipartUpload:PartUploaded` event per uploaded part to the queue, with the upload ID, part number, part size and part ETag in a `multipartUploadEventData` block. It also sends `s3:ObjectCreated:CompleteMultipartUpload` and `s3:MultipartUpload:Aborted`, which carry the upload ID too. +2. The Lambda function reads the queue in batches of 10. For each part event it calls GetPart with the upload ID and part number and streams the part through a SHA-256 hash (parts can be up to 5 GiB, so they are not buffered). When the client sent a SHA-256 checksum, the function compares its hash with the SHA-256 checksum that GetPart returns. +3. The function creates an `UPLOAD` item with status `IN_PROGRESS` if there is none, then writes one item per part to the ledger (`pk` = upload ID, `sk` = `PART#00001`) with the hash, the checksum result and the upload status that GetPart reported (`IN_PROGRESS` or `COMPLETED`). +4. The completion and abort events set the `UPLOAD` item to `COMPLETE` (with the object size and ETag) or `ABORTED`. + +Amazon S3 delivers event notifications at least once and not in order, so the ledger is written with conditions: + +* A part number can be uploaded again while the upload is in progress, and GetPart returns the newest copy. When the event ETag differs from the GetPart ETag, the event describes replaced bytes: the function logs `superseded` and writes nothing. +* A part item is written only when it is new, or when the event is a newer upload of that part (different ETag, later `eventTime`). A repeated or older event is logged as `duplicate`. +* The completion event can arrive before the last part event. GetPart still works after completion, so the late part is recorded with `uploadStatusAtRead` `COMPLETED`, and a `COMPLETE` or `ABORTED` upload item is never moved back. +* `NoSuchUpload` (for example, an aborted upload) and `NoSuchPart` cannot succeed on a retry, so those records are skipped. Any other error returns the message as a batch item failure: Amazon SQS retries only that message and moves it to the dead-letter queue after five receives. + +## Important Notes + +* The queue sits between Amazon S3 and Lambda to absorb bursts of parallel part uploads, to batch them, to retry one failed part without the rest of the batch, and to keep failed parts in the dead-letter queue. +* GetPart works only for uploads started after November 29, 2026, 00:00 UTC, in general purpose buckets, without SSE-C and not through S3 Access Points. It does not work for uploads completed with non-consecutive part numbers, or for completed objects in S3 Glacier Flexible Retrieval, S3 Glacier Deep Archive or S3 Intelligent-Tiering. See the [GetPart API reference](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPart.html). +* Reading a part in progress needs `s3:GetIncompleteUpload` in addition to `s3:GetObject`. The function role has both, on this bucket's objects only. +* Parts written with UploadPartCopy send `s3:MultipartUpload:PartCopied`, which this stack does not subscribe to, so copied parts are not in the ledger. +* The Lambda runtime includes a fixed version of the AWS SDK for JavaScript that may not have GetPart yet, so the function bundles `@aws-sdk/client-s3` from `package.json`. aws-cdk-lib has no `s3.EventType` value for the part events yet, so the stack casts the documented event names. +* The function reads the records of a batch one after another, so its 2 minute timeout must cover a whole batch of up to 10 parts, not one part. A timeout returns every message of the batch to the queue, including parts already recorded, and after five timeouts all of them move to the dead-letter queue. For large parts, lower `batchSize`, or raise the timeout and the queue visibility timeout together. +* The bucket aborts incomplete uploads after one day, because their parts are billed until then. Besides the part reader, the stack has two CDK helper functions: one configures the bucket notifications and one empties the bucket on `cdk destroy`. + +## Deployment Instructions + +1. Clone the repository: + ```bash + git clone https://github.com/aws-samples/serverless-patterns + cd serverless-patterns/s3-multipart-getpart-sqs-lambda/typescript/cdk + ``` +2. Install the dependencies: + ```bash + npm install + ``` +3. Deploy the stack in us-east-1 (see Supported Regions; run `npx cdk bootstrap` first if the account and Region are not bootstrapped): + ```bash + export AWS_REGION=us-east-1 + npx cdk deploy + ``` + The outputs are `BucketName`, `TableName`, `DeadLetterQueueUrl` and `PartReaderLogGroupName`. + +## Testing + +1. Set the Region and read the stack outputs (run this again in a new terminal): + ```bash + export AWS_REGION=us-east-1 + out() { aws cloudformation describe-stacks --stack-name S3MultipartGetpartSqsLambdaStack --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue" --output text; } + BUCKET=$(out BucketName); TABLE=$(out TableName); DLQ=$(out DeadLetterQueueUrl); LOG_GROUP=$(out PartReaderLogGroupName) + ``` +2. Start an upload and upload two 5 MiB parts with SHA-256 checksums. Do not complete it yet. Run steps 2 to 6 in the same terminal, because they reuse `KEY`, `UPLOAD_ID` and `UPLOAD_ID2`: + ```bash + head -c 5242880 /dev/urandom > /tmp/part1.bin; head -c 5242880 /dev/urandom > /tmp/part2.bin + KEY="uploads/sample-$(date +%s).bin" + UPLOAD_ID=$(aws s3api create-multipart-upload --bucket "$BUCKET" --key "$KEY" --checksum-algorithm SHA256 --query UploadId --output text) + for n in 1 2; do aws s3api upload-part --bucket "$BUCKET" --key "$KEY" --upload-id "$UPLOAD_ID" --part-number $n --body /tmp/part$n.bin --checksum-algorithm SHA256 --query ETag --output text; done + ``` +3. Wait about 10 seconds and read the ledger while the upload is still in progress, check that the object does not exist yet, then hash the files on your machine (on Linux, `sha256sum` prints the same): + ```bash + sleep 10 + aws dynamodb query --table-name "$TABLE" --key-condition-expression "pk = :u" --expression-attribute-values "{\":u\":{\"S\":\"$UPLOAD_ID\"}}" --query "Items[].[sk.S, uploadStatusAtRead.S, checksumMatch.BOOL, sha256Hex.S, status.S]" --output text + aws s3api head-object --bucket "$BUCKET" --key "$KEY" + shasum -a 256 /tmp/part1.bin /tmp/part2.bin + ``` + Expected: `PART#00001` and `PART#00002` with `IN_PROGRESS` and `True`, and a `sha256Hex` equal to the local hash of each file, plus an `UPLOAD` row with status `IN_PROGRESS`. `head-object` fails with `An error occurred (404) when calling the HeadObject operation: Not Found`, because the object exists only after the upload completes. +4. Complete the upload, wait about 10 seconds and read the upload item: + ```bash + aws s3api list-parts --bucket "$BUCKET" --key "$KEY" --upload-id "$UPLOAD_ID" --query "{Parts: Parts[].{PartNumber: PartNumber, ETag: ETag, ChecksumSHA256: ChecksumSHA256}}" --output json > /tmp/parts.json + aws s3api complete-multipart-upload --bucket "$BUCKET" --key "$KEY" --upload-id "$UPLOAD_ID" --multipart-upload file:///tmp/parts.json + sleep 10 + aws dynamodb get-item --table-name "$TABLE" --key "{\"pk\":{\"S\":\"$UPLOAD_ID\"},\"sk\":{\"S\":\"UPLOAD\"}}" --query "Item.[status.S, objectSize.N]" --output text + ``` + Expected: `COMPLETE` and `10485760`. +5. In a second upload, upload part 1 twice with different bytes, wait about 10 seconds, then read the ledger and the log: + ```bash + head -c 5242880 /dev/urandom > /tmp/part1b.bin + UPLOAD_ID2=$(aws s3api create-multipart-upload --bucket "$BUCKET" --key uploads/reupload.bin --query UploadId --output text) + for f in part1 part1b; do aws s3api upload-part --bucket "$BUCKET" --key uploads/reupload.bin --upload-id "$UPLOAD_ID2" --part-number 1 --body /tmp/$f.bin --query ETag --output text; done + sleep 10 + aws dynamodb query --table-name "$TABLE" --key-condition-expression "pk = :u" --expression-attribute-values "{\":u\":{\"S\":\"$UPLOAD_ID2\"}}" --query "Items[].[sk.S, partETag.S, status.S]" --output text + aws logs filter-log-events --log-group-name "$LOG_GROUP" --filter-pattern '"superseded"' --query "events[].message" --output text + ``` + Expected: `PART#00001` holds the second ETag that `upload-part` printed (without the quotes). The log shows `superseded` for the first event when it was processed after the second upload; if it was processed before, the item was written and then replaced, and the log shows nothing. On a second run the log also shows lines from earlier runs. +6. Abort the second upload, wait about 10 seconds, and check the upload item and the dead-letter queue: + ```bash + aws s3api abort-multipart-upload --bucket "$BUCKET" --key uploads/reupload.bin --upload-id "$UPLOAD_ID2" + sleep 10 + aws dynamodb get-item --table-name "$TABLE" --key "{\"pk\":{\"S\":\"$UPLOAD_ID2\"},\"sk\":{\"S\":\"UPLOAD\"}}" --query "Item.status.S" --output text + aws sqs get-queue-attributes --queue-url "$DLQ" --attribute-names ApproximateNumberOfMessages --query Attributes.ApproximateNumberOfMessages --output text + ``` + Expected: `ABORTED` and `0`. + +## Cleanup + +1. If you are in a new terminal, run Testing step 1 first so that `BUCKET` is set. +2. Abort every upload that is still open. The command prints nothing when there is none: + ```bash + aws s3api list-multipart-uploads --bucket "$BUCKET" --query "Uploads[].[Key, UploadId]" --output text | while IFS=$'\t' read -r key id; do if [ -n "$id" ]; then aws s3api abort-multipart-upload --bucket "$BUCKET" --key "$key" --upload-id "$id" < /dev/null && echo "aborted $key"; fi; done + ``` +3. Delete the stack and remove the test files. `cdk destroy` deletes the bucket with its objects and the ledger table, so the data cannot be recovered: + ```bash + npx cdk destroy + rm -f /tmp/part1.bin /tmp/part2.bin /tmp/part1b.bin /tmp/parts.json + ``` +4. The two CDK helper functions write to log groups that the stack does not manage. List them, check that each name belongs to this stack, and delete each one with `aws logs delete-log-group --log-group-name `: + ```bash + aws logs describe-log-groups --log-group-name-prefix /aws/lambda/S3MultipartGetpart --query "logGroups[].logGroupName" --output text + ``` + +---- +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/s3-multipart-getpart-sqs-lambda/typescript/cdk/bin/app.ts b/s3-multipart-getpart-sqs-lambda/typescript/cdk/bin/app.ts new file mode 100644 index 000000000..744a1a4b7 --- /dev/null +++ b/s3-multipart-getpart-sqs-lambda/typescript/cdk/bin/app.ts @@ -0,0 +1,8 @@ +#!/usr/bin/env node +import * as cdk from 'aws-cdk-lib'; +import { S3MultipartGetpartSqsLambdaStack } from '../lib/s3-multipart-getpart-sqs-lambda-stack'; + +const app = new cdk.App(); +new S3MultipartGetpartSqsLambdaStack(app, 'S3MultipartGetpartSqsLambdaStack', { + env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION }, +}); diff --git a/s3-multipart-getpart-sqs-lambda/typescript/cdk/cdk.json b/s3-multipart-getpart-sqs-lambda/typescript/cdk/cdk.json new file mode 100644 index 000000000..a6700a2ff --- /dev/null +++ b/s3-multipart-getpart-sqs-lambda/typescript/cdk/cdk.json @@ -0,0 +1,3 @@ +{ + "app": "npx ts-node --prefer-ts-exts bin/app.ts" +} diff --git a/s3-multipart-getpart-sqs-lambda/typescript/cdk/example-pattern.json b/s3-multipart-getpart-sqs-lambda/typescript/cdk/example-pattern.json new file mode 100644 index 000000000..165d3f9c9 --- /dev/null +++ b/s3-multipart-getpart-sqs-lambda/typescript/cdk/example-pattern.json @@ -0,0 +1,65 @@ +{ + "title": "Amazon S3 multipart upload parts to Amazon SQS and AWS Lambda with GetPart", + "description": "Amazon S3 sends each PartUploaded event to Amazon SQS. AWS Lambda reads the part with GetPart before the upload completes and records it in Amazon DynamoDB.", + "language": "TypeScript", + "level": "300", + "framework": "AWS CDK", + "introBox": { + "headline": "How it works", + "text": [ + "A client uploads the parts of an Amazon S3 multipart upload. Amazon S3 sends an s3:MultipartUpload:PartUploaded event for each part, plus the completion and abort events, to an Amazon SQS queue with a dead-letter queue.", + "An AWS Lambda function reads the queue in batches, reads each part with the Amazon S3 GetPart API while the upload is still in progress, and streams it through a SHA-256 hash, which it compares with the SHA-256 checksum that Amazon S3 returns when the client sent one.", + "The function keeps a part ledger in Amazon DynamoDB. Conditional writes make it safe for duplicate, out-of-order and superseded part events, and the completion or abort event closes the upload item.", + "This pattern deploys one AWS Lambda function for the parts and two AWS CDK helper functions for the bucket notifications and for emptying the bucket on delete." + ] + }, + "gitHub": { + "template": { + "templateFile": "lib/s3-multipart-getpart-sqs-lambda-stack.ts" + } + }, + "resources": { + "bullets": [ + { + "text": "Amazon S3 GetPart API reference", + "link": "https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPart.html" + }, + { + "text": "Amazon S3 event notification types and destinations", + "link": "https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-how-to-event-types-and-destinations.html" + }, + { + "text": "Using AWS Lambda with Amazon SQS", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html" + } + ] + }, + "deploy": { + "text": [ + "npm install", + "npx cdk bootstrap (once per account and Region)", + "export AWS_REGION=us-east-1 (see Supported Regions in the README)", + "npx cdk deploy" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Abort any open multipart upload first, as described in the Cleanup section of the README.", + "npx cdk destroy", + "Then delete the two CDK helper log groups, as described in the README." + ] + }, + "authors": [ + { + "name": "Nithin Chandran R", + "image": "https://github.com/NithinChandranR-AWS.png", + "bio": "Technical Account Manager at AWS", + "linkedin": "nithin-chandran-r" + } + ] +} diff --git a/s3-multipart-getpart-sqs-lambda/typescript/cdk/lambda/part-reader.ts b/s3-multipart-getpart-sqs-lambda/typescript/cdk/lambda/part-reader.ts new file mode 100644 index 000000000..3b18eb515 --- /dev/null +++ b/s3-multipart-getpart-sqs-lambda/typescript/cdk/lambda/part-reader.ts @@ -0,0 +1,160 @@ +import { createHash } from 'node:crypto'; +import type { Readable } from 'node:stream'; +import { GetPartCommand, NoSuchPart, NoSuchUpload, S3Client } from '@aws-sdk/client-s3'; +import { + AttributeValue, ConditionalCheckFailedException, DynamoDBClient, PutItemCommand, UpdateItemCommand, +} from '@aws-sdk/client-dynamodb'; +import type { SQSBatchResponse, SQSEvent } from 'aws-lambda'; + +const TABLE_NAME = process.env.TABLE_NAME; +if (!TABLE_NAME) throw new Error('TABLE_NAME is not set'); + +const requestHandler = { connectionTimeout: 5_000, requestTimeout: 30_000 }; +const s3 = new S3Client({ maxAttempts: 3, requestHandler }); +const ddb = new DynamoDBClient({ maxAttempts: 3, requestHandler }); + +// The fields this function reads. multipartUploadEventData is a sibling of s3 in the record, not part of s3.object. +interface S3Record { + eventName: string; + eventTime: string; + s3: { bucket: { name: string }; object: { key: string; size?: number; eTag?: string } }; + multipartUploadEventData?: { uploadId: string; partNumber?: number; partSize?: number; partETag?: string }; +} + +const S = (value: string): AttributeValue => ({ S: value }); +const N = (value: number): AttributeValue => ({ N: String(value) }); +const log = (message: string, fields: object) => console.info(JSON.stringify({ message, ...fields })); + +export const handler = async (event: SQSEvent): Promise => { + const batchItemFailures: SQSBatchResponse['batchItemFailures'] = []; + for (const message of event.Records) { + try { + // The s3:TestEvent message that Amazon S3 sends when the notification is configured has no Records. + const records: S3Record[] = JSON.parse(message.body).Records ?? []; + for (const record of records) await processRecord(record); + } catch (err) { + console.error(JSON.stringify({ message: 'failed', messageId: message.messageId, error: String(err) })); + // Only this message is retried; after five receives SQS moves it to the dead-letter queue. + batchItemFailures.push({ itemIdentifier: message.messageId }); + } + } + return { batchItemFailures }; +}; + +async function processRecord(record: S3Record): Promise { + const upload = record.multipartUploadEventData; + if (!upload?.uploadId) return; + // Object keys in event notifications are URL-encoded. + const key = decodeURIComponent(record.s3.object.key.replace(/\+/g, ' ')); + if (record.eventName === 'MultipartUpload:PartUploaded') { + await recordPart(record, upload.uploadId, key); + } else if (record.eventName === 'ObjectCreated:CompleteMultipartUpload') { + await closeUpload(record, upload.uploadId, key, 'COMPLETE'); + } else if (record.eventName === 'MultipartUpload:Aborted') { + await closeUpload(record, upload.uploadId, key, 'ABORTED'); + } +} + +async function recordPart(record: S3Record, uploadId: string, key: string): Promise { + const partNumber = record.multipartUploadEventData?.partNumber ?? 0; + const partETag = record.multipartUploadEventData?.partETag ?? ''; + let part; + try { + part = await s3.send(new GetPartCommand({ + Bucket: record.s3.bucket.name, Key: key, UploadId: uploadId, PartNumber: partNumber, ChecksumMode: 'ENABLED', + })); + } catch (err) { + // The upload was aborted or the part does not exist: a retry cannot succeed, so the record is not retried. + if (err instanceof NoSuchUpload || err instanceof NoSuchPart) { + log('skipped', { reason: err.name, uploadId, partNumber }); + return; + } + throw err; + } + const body = part.Body as Readable; + // A part number can be uploaded again while the upload is in progress. GetPart returns the latest copy, so an + // event whose ETag differs describes bytes that no longer exist (the GetPart ETag is quoted, the event ETag is not). + if (part.ETag?.replace(/"/g, '') !== partETag) { + body.destroy(); + log('superseded', { uploadId, partNumber, eventETag: partETag, currentETag: part.ETag }); + return; + } + // Stream the part through the hash: a part can be up to 5 GiB, so it is never buffered in memory. + const hash = createHash('sha256'); + for await (const chunk of body) hash.update(chunk); + const digest = hash.digest(); + + const item: Record = { + pk: S(uploadId), + sk: S(`PART#${String(partNumber).padStart(5, '0')}`), + objectKey: S(key), + partNumber: N(partNumber), + partSize: N(part.ContentLength ?? 0), + partETag: S(partETag), + sha256Hex: S(digest.toString('hex')), + uploadStatusAtRead: S(part.MultipartUploadStatus ?? 'UNKNOWN'), + eventTime: S(record.eventTime), + processedAt: S(new Date().toISOString()), + }; + // Present only when the client sent a SHA-256 checksum with UploadPart. + if (part.ChecksumSHA256) { + item.s3ChecksumSHA256 = S(part.ChecksumSHA256); + item.checksumMatch = { BOOL: part.ChecksumSHA256 === digest.toString('base64') }; + } + // Creates the upload item on the first part; a COMPLETE or ABORTED status is never moved back. It runs before the + // part write and is safe to repeat, so a message retried after a partial failure still leaves the upload item. + await ddb.send(new UpdateItemCommand({ + TableName: TABLE_NAME, + Key: { pk: S(uploadId), sk: S('UPLOAD') }, + UpdateExpression: 'SET objectKey = :key, #status = if_not_exists(#status, :inProgress)', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { ':key': S(key), ':inProgress': S('IN_PROGRESS') }, + })); + try { + // Events are delivered at least once and in any order. Write when the part is new, or when this event is a + // newer upload of the same part number; a repeated or older event changes nothing. + await ddb.send(new PutItemCommand({ + TableName: TABLE_NAME, + Item: item, + ConditionExpression: 'attribute_not_exists(pk) OR (partETag <> :etag AND eventTime < :eventTime)', + ExpressionAttributeValues: { ':etag': S(partETag), ':eventTime': S(record.eventTime) }, + })); + } catch (err) { + if (err instanceof ConditionalCheckFailedException) { + log('duplicate', { uploadId, partNumber, partETag }); + return; + } + throw err; + } + log('recorded', { uploadId, partNumber, partETag, uploadStatusAtRead: part.MultipartUploadStatus }); +} + +async function closeUpload(record: S3Record, uploadId: string, key: string, status: 'COMPLETE' | 'ABORTED'): Promise { + const values: Record = { + ':status': S(status), ':key': S(key), ':closedAt': S(record.eventTime), ':inProgress': S('IN_PROGRESS'), + }; + let update = 'SET #status = :status, objectKey = :key, closedAt = :closedAt'; + if (status === 'COMPLETE') { + update += ', objectSize = :size, objectETag = :objectETag'; + values[':size'] = N(record.s3.object.size ?? 0); + values[':objectETag'] = S(record.s3.object.eTag ?? ''); + } + try { + await ddb.send(new UpdateItemCommand({ + TableName: TABLE_NAME, + Key: { pk: S(uploadId), sk: S('UPLOAD') }, + UpdateExpression: update, + // The completion event can arrive before the last part event, so the upload item may not exist yet. + ConditionExpression: 'attribute_not_exists(#status) OR #status = :inProgress', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: values, + })); + } catch (err) { + if (err instanceof ConditionalCheckFailedException) { + log('duplicate', { uploadId, status }); + return; + } + throw err; + } + log('closed', { uploadId, status }); +} diff --git a/s3-multipart-getpart-sqs-lambda/typescript/cdk/lib/s3-multipart-getpart-sqs-lambda-stack.ts b/s3-multipart-getpart-sqs-lambda/typescript/cdk/lib/s3-multipart-getpart-sqs-lambda-stack.ts new file mode 100644 index 000000000..a41ab3b0f --- /dev/null +++ b/s3-multipart-getpart-sqs-lambda/typescript/cdk/lib/s3-multipart-getpart-sqs-lambda-stack.ts @@ -0,0 +1,107 @@ +import * as path from 'path'; +import * as cdk from 'aws-cdk-lib'; +import { Construct } from 'constructs'; +import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; +import * as iam from 'aws-cdk-lib/aws-iam'; +import * as lambda from 'aws-cdk-lib/aws-lambda'; +import * as eventsources from 'aws-cdk-lib/aws-lambda-event-sources'; +import * as nodejs from 'aws-cdk-lib/aws-lambda-nodejs'; +import * as logs from 'aws-cdk-lib/aws-logs'; +import * as s3 from 'aws-cdk-lib/aws-s3'; +import * as s3n from 'aws-cdk-lib/aws-s3-notifications'; +import * as sqs from 'aws-cdk-lib/aws-sqs'; + +// aws-cdk-lib has no s3.EventType members for the multipart part events yet, so the documented event names are cast. +// Remove the cast once s3.EventType lists them. Event names: Amazon S3 User Guide, "Event notification types and destinations". +const PART_UPLOADED = 's3:MultipartUpload:PartUploaded' as s3.EventType; +const UPLOAD_ABORTED = 's3:MultipartUpload:Aborted' as s3.EventType; + +export class S3MultipartGetpartSqsLambdaStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + // Private bucket for the uploads. Incomplete multipart uploads keep billing for their parts, so the lifecycle + // rule aborts any upload that is still open after one day. + const bucket = new s3.Bucket(this, 'UploadBucket', { + blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, + encryption: s3.BucketEncryption.S3_MANAGED, + enforceSSL: true, + lifecycleRules: [{ abortIncompleteMultipartUploadAfter: cdk.Duration.days(1) }], + removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true, + }); + + // The queue buffers bursts of parallel part uploads, lets Lambda read them in batches and keeps a part whose + // processing keeps failing in a dead-letter queue instead of dropping it. + const deadLetterQueue = new sqs.Queue(this, 'PartEventsDlq', { + encryption: sqs.QueueEncryption.SQS_MANAGED, + enforceSSL: true, + retentionPeriod: cdk.Duration.days(14), + }); + const queue = new sqs.Queue(this, 'PartEventsQueue', { + encryption: sqs.QueueEncryption.SQS_MANAGED, + enforceSSL: true, + // Lambda recommends at least six times the function timeout for an SQS event source. + visibilityTimeout: cdk.Duration.minutes(12), + deadLetterQueue: { queue: deadLetterQueue, maxReceiveCount: 5 }, + }); + + // SqsDestination adds a queue policy statement for the Amazon S3 service principal, limited to this bucket. + const destination = new s3n.SqsDestination(queue); + bucket.addEventNotification(PART_UPLOADED, destination); + bucket.addEventNotification(UPLOAD_ABORTED, destination); + bucket.addEventNotification(s3.EventType.OBJECT_CREATED_COMPLETE_MULTIPART_UPLOAD, destination); + + // Part ledger: pk = uploadId, sk = "PART#00001" for each part and "UPLOAD" for the upload itself. + const table = new dynamodb.Table(this, 'PartLedger', { + partitionKey: { name: 'pk', type: dynamodb.AttributeType.STRING }, + sortKey: { name: 'sk', type: dynamodb.AttributeType.STRING }, + billingMode: dynamodb.BillingMode.PAY_PER_REQUEST, + removalPolicy: cdk.RemovalPolicy.DESTROY, + }); + + const logGroup = new logs.LogGroup(this, 'PartReaderLogGroup', { + retention: logs.RetentionDays.TWO_WEEKS, + removalPolicy: cdk.RemovalPolicy.DESTROY, + }); + + const partReader = new nodejs.NodejsFunction(this, 'PartReader', { + entry: path.join(__dirname, '..', 'lambda', 'part-reader.ts'), + handler: 'handler', + runtime: lambda.Runtime.NODEJS_24_X, + memorySize: 512, + // The records of a batch are read and hashed one after another, so this covers a whole batch (batchSize x the + // read time of the largest part). A timeout returns every message of the batch, so for large parts lower + // batchSize, or raise this and the queue visibility timeout together. + timeout: cdk.Duration.minutes(2), + logGroup, + loggingFormat: lambda.LoggingFormat.JSON, + environment: { TABLE_NAME: table.tableName }, + bundling: { + // The Lambda runtime has a fixed AWS SDK version that may not have GetPart yet, so bundle the SDK clients + // from package.json instead of leaving @aws-sdk/* to the runtime. + externalModules: [], + }, + }); + + partReader.addEventSource(new eventsources.SqsEventSource(queue, { + batchSize: 10, + reportBatchItemFailures: true, + })); + + // GetPart needs s3:GetObject, plus s3:GetIncompleteUpload while the upload is in progress (GetPart API reference). + partReader.addToRolePolicy(new iam.PolicyStatement({ + actions: ['s3:GetObject', 's3:GetIncompleteUpload'], + resources: [bucket.arnForObjects('*')], + })); + partReader.addToRolePolicy(new iam.PolicyStatement({ + actions: ['dynamodb:PutItem', 'dynamodb:UpdateItem'], + resources: [table.tableArn], + })); + + new cdk.CfnOutput(this, 'BucketName', { value: bucket.bucketName }); + new cdk.CfnOutput(this, 'TableName', { value: table.tableName }); + new cdk.CfnOutput(this, 'DeadLetterQueueUrl', { value: deadLetterQueue.queueUrl }); + new cdk.CfnOutput(this, 'PartReaderLogGroupName', { value: logGroup.logGroupName }); + } +} diff --git a/s3-multipart-getpart-sqs-lambda/typescript/cdk/package.json b/s3-multipart-getpart-sqs-lambda/typescript/cdk/package.json new file mode 100644 index 000000000..4aaf22663 --- /dev/null +++ b/s3-multipart-getpart-sqs-lambda/typescript/cdk/package.json @@ -0,0 +1,23 @@ +{ + "name": "s3-multipart-getpart-sqs-lambda-cdk", + "version": "1.0.0", + "private": true, + "scripts": { + "build": "tsc --noEmit", + "synth": "cdk synth" + }, + "dependencies": { + "@aws-sdk/client-dynamodb": "^3.1180.0", + "@aws-sdk/client-s3": "^3.1180.0", + "aws-cdk-lib": "^2.278.0", + "constructs": "^10.8.1" + }, + "devDependencies": { + "@types/aws-lambda": "^8.10.164", + "@types/node": "^24.0.0", + "aws-cdk": "^2.1149.0", + "esbuild": "^0.28.2", + "ts-node": "^10.9.2", + "typescript": "~5.9.3" + } +} diff --git a/s3-multipart-getpart-sqs-lambda/typescript/cdk/tsconfig.json b/s3-multipart-getpart-sqs-lambda/typescript/cdk/tsconfig.json new file mode 100644 index 000000000..3ef8e8c44 --- /dev/null +++ b/s3-multipart-getpart-sqs-lambda/typescript/cdk/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "commonjs", + "lib": ["es2022"], + "strict": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "skipLibCheck": true, + "noEmit": true, + "types": ["node", "aws-lambda"] + }, + "include": ["bin/**/*.ts", "lib/**/*.ts", "lambda/**/*.ts"], + "exclude": ["node_modules", "cdk.out"] +}