### Install AsyncAws SQS Client Source: https://github.com/async-aws/sqs/blob/master/README.md Use Composer to install the SQS client library. ```cli composer require async-aws/sqs ``` -------------------------------- ### startMessageMoveTask Source: https://context7.com/async-aws/sqs/llms.txt Starts an asynchronous task to move messages from a dead-letter queue to a source queue or a custom destination. Only one active task per queue is supported. ```APIDOC ## startMessageMoveTask ### Description Starts an asynchronous task to move messages from a dead-letter queue back to the original source queue or a custom destination. Only one active task per queue at a time is supported. ### Method POST ### Endpoint / ### Parameters #### Query Parameters - **Action** (string) - Required - `StartMessageMoveTask` - **Version** (string) - Required - `2012-11-05` #### Request Body - **SourceArn** (string) - Required - The ARN of the dead-letter queue. - **DestinationArn** (string) - Required - The ARN of the destination queue. - **MaxNumberOfMessagesPerSecond** (integer) - Optional - The maximum number of messages to move per second. Defaults to 1000. ### Request Example ```json { "SourceArn": "arn:aws:sqs:us-east-1:123456789012:my-dead-letter-queue", "DestinationArn": "arn:aws:sqs:us-east-1:123456789012:my-task-queue", "MaxNumberOfMessagesPerSecond": 100 } ``` ### Response #### Success Response (200) - **taskHandle** (string) - An identifier for the message move task. - **approximateNumberOfMessagesMoved** (integer) - The number of messages moved so far. - **approximateNumberOfMessagesToMove** (integer) - The total number of messages to move. - **destinationArn** (string) - The ARN of the destination queue. - **sourceArn** (string) - The ARN of the source queue. - **maxNumberOfMessagesPerSecond** (integer) - The maximum number of messages to move per second. - **createdTimestamp** (integer) - The timestamp when the task was created. - **status** (string) - The status of the task (RUNNING, COMPLETED, FAILED, CANCELLING, CANCELLED). #### Response Example ```json { "taskHandle": "AQEB...(task handle)", "approximateNumberOfMessagesMoved": 0, "approximateNumberOfMessagesToMove": 1000, "destinationArn": "arn:aws:sqs:us-east-1:123456789012:my-task-queue", "sourceArn": "arn:aws:sqs:us-east-1:123456789012:my-dead-letter-queue", "maxNumberOfMessagesPerSecond": 100, "createdTimestamp": 1678886400, "status": "RUNNING" } ``` ``` -------------------------------- ### Start Message Redrive Task from DLQ Source: https://context7.com/async-aws/sqs/llms.txt Initiate an asynchronous task to move messages from a dead-letter queue to a source or destination queue. Only one active task per queue is allowed. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Exception\ResourceNotFoundException; $sqs = new SqsClient(['region' => 'us-east-1']); $dlqArn = 'arn:aws:sqs:us-east-1:123456789012:my-dead-letter-queue'; $destArn = 'arn:aws:sqs:us-east-1:123456789012:my-task-queue'; try { $result = $sqs->startMessageMoveTask([ 'SourceArn' => $dlqArn, 'DestinationArn' => $destArn, 'MaxNumberOfMessagesPerSecond' => 100, ]); $taskHandle = $result->getTaskHandle(); echo "Move task started: {$taskHandle}\n"; } catch (ResourceNotFoundException $e) { echo "Source ARN not found or DLQ not configured."; } ``` -------------------------------- ### Get SQS Queue URL by Name Source: https://context7.com/async-aws/sqs/llms.txt Retrieve the URL of an existing SQS queue by its name. Handles QueueDoesNotExistException if the queue is not found. Can also resolve queues in other AWS accounts. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Exception\QueueDoesNotExistException; $sqs = new SqsClient(['region' => 'us-east-1']); try { $result = $sqs->getQueueUrl(['QueueName' => 'my-task-queue']); $queueUrl = $result->getQueueUrl(); echo $queueUrl; // https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue } catch (QueueDoesNotExistException $e) { echo 'Queue not found.'; } // Resolve a queue in another AWS account $crossAccountResult = $sqs->getQueueUrl([ 'QueueName' => 'shared-queue', 'QueueOwnerAWSAccountId' => '987654321098', ]); ``` -------------------------------- ### SqsClient Instantiation Source: https://context7.com/async-aws/sqs/llms.txt Demonstrates how to instantiate the SqsClient using explicit credentials, environment variables, or a custom endpoint. ```APIDOC ## SqsClient Instantiation The `SqsClient` extends `AbstractApi` from `async-aws/core`. Credentials and region can be provided via constructor options, environment variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`), or instance profile. ```php use AsyncAws\Sqs\SqsClient; // Using explicit credentials $sqs = new SqsClient([ 'region' => 'us-east-1', 'accessKeyId' => 'AKIAIOSFODNN7EXAMPLE', 'accessKeySecret' => 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY', ]); // Using environment variables / instance profile (recommended for production) $sqs = new SqsClient(['region' => 'eu-west-1']); // Target a specific non-standard endpoint (e.g. LocalStack) $sqs = new SqsClient([ 'region' => 'us-east-1', 'endpoint' => 'http://localhost:4566', 'accessKeyId' => 'test', 'accessKeySecret' => 'test', ]); ``` ``` -------------------------------- ### Instantiate SqsClient with Explicit Credentials Source: https://context7.com/async-aws/sqs/llms.txt Instantiate the SqsClient using explicit AWS region, access key ID, and secret access key. ```php use AsyncAws\Sqs\SqsClient; // Using explicit credentials $sqs = new SqsClient([ 'region' => 'us-east-1', 'accessKeyId' => 'AKIAIOSFODNN7EXAMPLE', 'accessKeySecret' => 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY', ]); // Using environment variables / instance profile (recommended for production) $sqs = new SqsClient(['region' => 'eu-west-1']); // Target a specific non-standard endpoint (e.g. LocalStack) $sqs = new SqsClient([ 'region' => 'us-east-1', 'endpoint' => 'http://localhost:4566', 'accessKeyId' => 'test', 'accessKeySecret' => 'test', ]); ``` -------------------------------- ### Create a FIFO SQS Queue Source: https://context7.com/async-aws/sqs/llms.txt Create a FIFO SQS queue. The queue name must end with '.fifo' and can be configured with content-based deduplication. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Enum\QueueAttributeName; $sqs = new SqsClient(['region' => 'us-east-1']); // Create a FIFO queue (name must end in .fifo) $fifoResult = $sqs->createQueue([ 'QueueName' => 'my-ordered-queue.fifo', 'Attributes' => [ QueueAttributeName::FIFO_QUEUE => 'true', QueueAttributeName::CONTENT_BASED_DEDUPLICATION => 'true', ], ]); echo $fifoResult->getQueueUrl(); // https://sqs.us-east-1.amazonaws.com/123456789012/my-ordered-queue.fifo ``` -------------------------------- ### List SQS Queues with Pagination Source: https://context7.com/async-aws/sqs/llms.txt Use `listQueues` to retrieve queue URLs. The result supports automatic iteration over multiple pages. You can also filter by prefix or fetch only the first page. ```php use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient(['region' => 'us-east-1']); // Iterate all queues automatically (fetches next pages as needed) foreach ($sqs->listQueues() as $queueUrl) { echo $queueUrl . "\n"; } // Filter by prefix foreach ($sqs->listQueues(['QueueNamePrefix' => 'production-']) as $queueUrl) { echo $queueUrl . "\n"; } // Single-page fetch only (first page) $result = $sqs->listQueues(['MaxResults' => 100]); foreach ($result->getQueueUrls(currentPageOnly: true) as $url) { echo $url . "\n"; } // Manual pagination while (true) { foreach ($result->getQueueUrls(currentPageOnly: true) as $url) { echo $url . "\n"; } if (null === $result->getNextToken()) break; $result = $sqs->listQueues(['NextToken' => $result->getNextToken()]); } ``` -------------------------------- ### createQueue Source: https://context7.com/async-aws/sqs/llms.txt Creates a new SQS queue, either standard or FIFO, with specified attributes and tags. Returns the queue URL upon successful creation. ```APIDOC ## `createQueue` — Create a Standard or FIFO Queue Creates a new SQS queue and returns its URL. If a queue with identical name and attributes already exists, the existing queue URL is returned. Queue creation requires at least one second before the queue is usable. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Enum\QueueAttributeName; use AsyncAws\Sqs\Exception\QueueNameExistsException; $sqs = new SqsClient(['region' => 'us-east-1']); // Create a standard queue with custom retention and visibility settings try { $result = $sqs->createQueue([ 'QueueName' => 'my-task-queue', 'Attributes' => [ QueueAttributeName::VISIBILITY_TIMEOUT => '60', QueueAttributeName::MESSAGE_RETENTION_PERIOD => '86400', QueueAttributeName::RECEIVE_MESSAGE_WAIT_TIME_SECONDS => '20', ], 'tags' => ['Environment' => 'production', 'Team' => 'backend'], ]); echo $result->getQueueUrl(); // https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue } catch (QueueNameExistsException $e) { echo 'Queue exists with different attributes: ' . $e->getMessage(); } // Create a FIFO queue (name must end in .fifo) $fifoResult = $sqs->createQueue([ 'QueueName' => 'my-ordered-queue.fifo', 'Attributes' => [ QueueAttributeName::FIFO_QUEUE => 'true', QueueAttributeName::CONTENT_BASED_DEDUPLICATION => 'true', ], ]); echo $fifoResult->getQueueUrl(); // https://sqs.us-east-1.amazonaws.com/123456789012/my-ordered-queue.fifo ``` ``` -------------------------------- ### Create a Standard SQS Queue Source: https://context7.com/async-aws/sqs/llms.txt Create a standard SQS queue with custom visibility timeout, message retention period, and receive message wait time. Handles QueueNameExistsException if the queue already exists with different attributes. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Enum\QueueAttributeName; use AsyncAws\Sqs\Exception\QueueNameExistsException; $sqs = new SqsClient(['region' => 'us-east-1']); // Create a standard queue with custom retention and visibility settings try { $result = $sqs->createQueue([ 'QueueName' => 'my-task-queue', 'Attributes' => [ QueueAttributeName::VISIBILITY_TIMEOUT => '60', QueueAttributeName::MESSAGE_RETENTION_PERIOD => '86400', QueueAttributeName::RECEIVE_MESSAGE_WAIT_TIME_SECONDS => '20', ], 'tags' => ['Environment' => 'production', 'Team' => 'backend'], ]); echo $result->getQueueUrl(); // https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue } catch (QueueNameExistsException $e) { echo 'Queue exists with different attributes: ' . $e->getMessage(); } ``` -------------------------------- ### List Queues with Redrive Policy Pointing to a DLQ Source: https://context7.com/async-aws/sqs/llms.txt Retrieve all queues configured with a RedrivePolicy to a specific dead-letter queue. Supports automatic pagination. ```php use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient(['region' => 'us-east-1']); $dlqUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-dead-letter-queue'; // Automatically iterates all pages $result = $sqs->listDeadLetterSourceQueues(['QueueUrl' => $dlqUrl]); foreach ($result as $sourceQueueUrl) { echo "Source queue: {$sourceQueueUrl}\n"; } // Paginated manually $result = $sqs->listDeadLetterSourceQueues([ 'QueueUrl' => $dlqUrl, 'MaxResults' => 50, ]); foreach ($result->getQueueUrls(currentPageOnly: true) as $url) { echo $url . "\n"; } ``` -------------------------------- ### List Recent DLQ Redrive Tasks Source: https://context7.com/async-aws/sqs/llms.txt Retrieve status and progress for up to 10 recent message movement tasks for a given source queue ARN. Includes failure reasons if applicable. ```php use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient(['region' => 'us-east-1']); $dlqArn = 'arn:aws:sqs:us-east-1:123456789012:my-dead-letter-queue'; $result = $sqs->listMessageMoveTasks(['SourceArn' => $dlqArn]); foreach ($result->getResults() as $task) { echo "Task: {$task->getTaskHandle()}\n"; echo "Status: {$task->getStatus()} "; // RUNNING, COMPLETED, CANCELLING, CANCELLED, FAILED echo "Moved: {$task->getApproximateNumberOfMessagesMoved()} "; echo "Remaining: {$task->getApproximateNumberOfMessagesToMove()} "; if ($task->getFailureReason()) { echo "Failure: {$task->getFailureReason()}\n"; } } ``` -------------------------------- ### listQueues Source: https://context7.com/async-aws/sqs/llms.txt Lists queue URLs, supporting transparent pagination for up to 1,000 queues per page. The result can be iterated automatically. ```APIDOC ## listQueues ### Description Returns queue URLs, up to 1,000 per page. The result implements `IteratorAggregate` for automatic multi-page iteration. ### Method POST ### Endpoint / ### Parameters #### Query Parameters - **MaxResults** (integer) - Optional - The maximum number of queues to return. Default is 1000. - **NextToken** (string) - Optional - The token for the next set of results. - **QueueNamePrefix** (string) - Optional - A prefix that filters the list of queues to return. ### Request Example ```php use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient(['region' => 'us-east-1']); // Iterate all queues automatically (fetches next pages as needed) foreach ($sqs->listQueues() as $queueUrl) { echo $queueUrl . "\\n"; } // Filter by prefix foreach ($sqs->listQueues(['QueueNamePrefix' => 'production-']) as $queueUrl) { echo $queueUrl . "\\n"; } // Single-page fetch only (first page) $result = $sqs->listQueues(['MaxResults' => 100]); foreach ($result->getQueueUrls(currentPageOnly: true) as $url) { echo $url . "\\n"; } // Manual pagination while (true) { foreach ($result->getQueueUrls(currentPageOnly: true) as $url) { echo $url . "\\n"; } if (null === $result->getNextToken()) break; $result = $sqs->listQueues(['NextToken' => $result->getNextToken()]); } ``` ### Response #### Success Response (200) - **QueueUrls** (array) - A list of queue URLs. - **NextToken** (string) - The token for the next set of results, if any. ``` -------------------------------- ### Send and Receive Custom Message Attributes with SQS Source: https://context7.com/async-aws/sqs/llms.txt Demonstrates sending messages with custom typed attributes (Number, String.email, Binary) and reading them back. Ensure the `MessageAttributeNames` parameter is set to 'All' or specific attribute names when receiving messages to retrieve custom attributes. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\ValueObject\MessageAttributeValue; $sqs = new SqsClient(['region' => 'us-east-1']); $queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue'; $result = $sqs->sendMessage([ 'QueueUrl' => $queueUrl, 'MessageBody' => 'Process invoice', 'MessageAttributes' => [ 'InvoiceId' => new MessageAttributeValue([ 'DataType' => 'Number', 'StringValue' => '10042', ]), 'CustomerEmail' => new MessageAttributeValue([ 'DataType' => 'String.email', 'StringValue' => 'customer@example.com', ]), 'RawData' => new MessageAttributeValue([ 'DataType' => 'Binary', 'BinaryValue' => random_bytes(16), ]), ], ]); echo $result->getMessageId(); // Reading attributes back from received messages $received = $sqs->receiveMessage([ 'QueueUrl' => $queueUrl, 'MessageAttributeNames' => ['All'], ]); foreach ($received->getMessages() as $msg) { $invoiceId = $msg->getMessageAttributes()['InvoiceId']->getStringValue(); // '10042' $rawData = $msg->getMessageAttributes()['RawData']->getBinaryValue(); // binary string } ``` -------------------------------- ### Wait for Queue to Become Available Source: https://context7.com/async-aws/sqs/llms.txt Polls GetQueueUrl every 5 seconds until the queue exists. Can be used synchronously or with isSuccess(). Throws on timeout or failure. ```php use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient(['region' => 'us-east-1']); // After creating a queue, wait until it's ready $sqs->createQueue(['QueueName' => 'newly-created-queue']); $waiter = $sqs->queueExists(['QueueName' => 'newly-created-queue']); // Block until the queue exists (throws on timeout or failure) $waiter->wait(); echo "Queue is ready.\n"; // Or poll non-blocking if ($waiter->isSuccess()) { echo "Queue already exists.\n"; } else { echo "Queue not yet available.\n"; } ``` -------------------------------- ### getQueueAttributes Source: https://context7.com/async-aws/sqs/llms.txt Retrieves metadata and configuration for a queue, including message counts, ARN, timeout settings, and redrive policies. ```APIDOC ## getQueueAttributes ### Description Fetches one or more queue attributes, including message counts, ARN, timeout settings, and redrive policies. ### Method POST ### Endpoint / ### Parameters #### Query Parameters - **QueueUrl** (string) - Required - The URL of the Amazon SQS queue. - **AttributeNames** (array) - Required - A list of queue attribute names to retrieve. - Possible values: `ApproximateNumberOfMessages`, `ApproximateNumberOfMessagesNotVisible`, `QueueArn`, `VisibilityTimeout`, `RedrivePolicy`, `FifoQueue`, `ContentBasedDeduplication`, `DeduplicationScope`, `FifoThroughputLimit`, `VisibilityTimeout`, `MessageRetentionPeriod`, `Policy`, `ReceiveMessageWaitTimeSeconds`, `VisibilityTimeout`, `RedrivePolicy`, `KmsMasterKeyId`, `KmsDataKeyReusePeriodSeconds`, `Tags`, `QueueArn`, `ApproximateNumberOfMessagesDelayed`, `ApproximateNumberOfMessagesVisible`, `ApproximateNumberOfMessagesNotVisible`, `CreatedTimestamp`, `LastModifiedTimestamp`, `QueueArn`, `VisibilityTimeout`, `MaximumMessageSize`, `MessageVisibilityTimeout`, `RedrivePolicy`, `Arn`, `VisibilityTimeout`, `ApproximateNumberOfMessages`, `ApproximateNumberOfMessagesNotVisible`, `QueueArn`, `VisibilityTimeout`, `RedrivePolicy`. ### Request Example ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Enum\QueueAttributeName; $sqs = new SqsClient(['region' => 'us-east-1']); $queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue'; $result = $sqs->getQueueAttributes([ 'QueueUrl' => $queueUrl, 'AttributeNames' => [ QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES, QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE, QueueAttributeName::QUEUE_ARN, QueueAttributeName::VISIBILITY_TIMEOUT, QueueAttributeName::REDRIVE_POLICY, ], ]); ``` ### Response #### Success Response (200) - **Attributes** (object) - A map of the attributes of the queue. - Keys are attribute names (e.g., `ApproximateNumberOfMessages`, `QueueArn`). - Values are the corresponding attribute values. #### Response Example ```php $attrs = $result->getAttributes(); echo "Visible messages: " . ($attrs[QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES] ?? 0) . "\\n"; echo "In-flight messages: " . ($attrs[QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE] ?? 0) . "\\n"; echo "Queue ARN: " . ($attrs[QueueAttributeName::QUEUE_ARN] ?? '') . "\\n"; echo "Visibility timeout: " . ($attrs[QueueAttributeName::VISIBILITY_TIMEOUT] ?? '') . "s\\n"; if (isset($attrs[QueueAttributeName::REDRIVE_POLICY])) { $policy = json_decode($attrs[QueueAttributeName::REDRIVE_POLICY], true); echo "DLQ ARN: " . $policy['deadLetterTargetArn'] . "\\n"; echo "Max receives: " . $policy['maxReceiveCount'] . "\\n"; } ``` ``` -------------------------------- ### sendMessageBatch Source: https://context7.com/async-aws/sqs/llms.txt Batch-sends up to 10 messages. Each entry requires a unique `Id` within the batch. The result distinguishes successful and failed entries. ```APIDOC ## `sendMessageBatch` — Send up to 10 Messages in One Request Batch-sends up to 10 messages. Each entry requires a unique `Id` within the batch. The result distinguishes successful and failed entries. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Exception\BatchRequestTooLongException; $sqs = new SqsClient(['region' => 'us-east-1']); $queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue'; $result = $sqs->sendMessageBatch([ 'QueueUrl' => $queueUrl, 'Entries' => [ ['Id' => 'msg-1', 'MessageBody' => 'Task A', 'DelaySeconds' => 0], ['Id' => 'msg-2', 'MessageBody' => 'Task B', 'DelaySeconds' => 10], ['Id' => 'msg-3', 'MessageBody' => 'Task C', 'MessageAttributes' => [ 'Source' => ['DataType' => 'String', 'StringValue' => 'batch-job'], ]], ], ]); foreach ($result->getSuccessful() as $entry) { echo "Sent {" . $entry->getId() . "}: MessageId=". $entry->getMessageId() . "\n"; // Sent msg-1: MessageId=abc123... } foreach ($result->getFailed() as $error) { echo "Failed {" . $error->getId() . "}: [" . $error->getCode() . "] " . $error->getMessage() . "\n"; } ``` ``` -------------------------------- ### listMessageMoveTasks Source: https://context7.com/async-aws/sqs/llms.txt Retrieves the most recent message movement tasks (up to 10) for a given source queue ARN, including status and progress. ```APIDOC ## listMessageMoveTasks ### Description Retrieves the most recent message movement tasks (up to 10) for a given source queue ARN, including status, progress counters, and failure reasons. ### Method POST ### Endpoint / ### Parameters #### Query Parameters - **Action** (string) - Required - `ListMessageMoveTasks` - **Version** (string) - Required - `2012-11-05` #### Request Body - **SourceArn** (string) - Required - The ARN of the source queue. - **MaxResults** (integer) - Optional - The maximum number of results to return. Default is 10. - **NextToken** (string) - Optional - The pagination token to retrieve the next page of results. ### Request Example ```json { "SourceArn": "arn:aws:sqs:us-east-1:123456789012:my-dead-letter-queue" } ``` ### Response #### Success Response (200) - **results** (array) - A list of message move tasks. - **taskHandle** (string) - An identifier for the message move task. - **status** (string) - The status of the task (RUNNING, COMPLETED, FAILED, CANCELLING, CANCELLED). - **approximateNumberOfMessagesMoved** (integer) - The number of messages moved so far. - **approximateNumberOfMessagesToMove** (integer) - The total number of messages to move. - **failureReason** (string) - The reason for task failure, if applicable. - **createdTimestamp** (integer) - The timestamp when the task was created. - **lastUpdatedTimestamp** (integer) - The timestamp when the task was last updated. - **sourceArn** (string) - The ARN of the source queue. - **destinationArn** (string) - The ARN of the destination queue. - **nextToken** (string) - A pagination token to retrieve the next page of results. #### Response Example ```json { "results": [ { "taskHandle": "AQEB...(task handle)", "status": "RUNNING", "approximateNumberOfMessagesMoved": 500, "approximateNumberOfMessagesToMove": 1000, "failureReason": null, "createdTimestamp": 1678886400, "lastUpdatedTimestamp": 1678887000, "sourceArn": "arn:aws:sqs:us-east-1:123456789012:my-dead-letter-queue", "destinationArn": "arn:aws:sqs:us-east-1:123456789012:my-task-queue" } ], "nextToken": null } ``` ``` -------------------------------- ### listDeadLetterSourceQueues Source: https://context7.com/async-aws/sqs/llms.txt Lists all queues that have a RedrivePolicy configured to use a specific dead-letter queue. Supports automatic pagination. ```APIDOC ## listDeadLetterSourceQueues ### Description Returns all queues that have a `RedrivePolicy` configured to use a specific dead-letter queue. Supports automatic pagination via `IteratorAggregate`. ### Method POST ### Endpoint / ### Parameters #### Query Parameters - **Action** (string) - Required - `ListDeadLetterSourceQueues` - **Version** (string) - Required - `2012-11-05` #### Request Body - **QueueUrl** (string) - Required - The URL of the dead-letter queue (DLQ). - **MaxResults** (integer) - Optional - The maximum number of results to return. Default is 1000. - **NextToken** (string) - Optional - The pagination token to retrieve the next page of results. ### Request Example ```json { "QueueUrl": "https://sqs.us-east-1.amazonaws.com/123456789012/my-dead-letter-queue" } ``` ### Response #### Success Response (200) - **queueUrls** (array) - A list of queue URLs that are configured as dead-letter queues for the specified DLQ. - **nextToken** (string) - A pagination token to retrieve the next page of results. ``` -------------------------------- ### Retrieve SQS Queue Attributes Source: https://context7.com/async-aws/sqs/llms.txt Use `getQueueAttributes` to fetch queue metadata such as message counts, ARN, visibility timeout, and redrive policies. Ensure the `QueueAttributeName` enum is imported for proper attribute referencing. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Enum\QueueAttributeName; $sqs = new SqsClient(['region' => 'us-east-1']); $queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue'; $result = $sqs->getQueueAttributes([ 'QueueUrl' => $queueUrl, 'AttributeNames' => [ QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES, QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE, QueueAttributeName::QUEUE_ARN, QueueAttributeName::VISIBILITY_TIMEOUT, QueueAttributeName::REDRIVE_POLICY, ], ]); $attrs = $result->getAttributes(); echo "Visible messages: " . ($attrs[QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES] ?? 0) . "\n"; echo "In-flight messages: " . ($attrs[QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE] ?? 0) . "\n"; echo "Queue ARN: " . ($attrs[QueueAttributeName::QUEUE_ARN] ?? '') . "\n"; echo "Visibility timeout: " . ($attrs[QueueAttributeName::VISIBILITY_TIMEOUT] ?? '') . "s\n"; if (isset($attrs[QueueAttributeName::REDRIVE_POLICY])) { $policy = json_decode($attrs[QueueAttributeName::REDRIVE_POLICY], true); echo "DLQ ARN: " . $policy['deadLetterTargetArn'] . "\n"; echo "Max receives: " . $policy['maxReceiveCount'] . "\n"; } ``` -------------------------------- ### queueExists Source: https://context7.com/async-aws/sqs/llms.txt A waiter that polls `GetQueueUrl` every 5 seconds until the queue exists. Returns a `QueueExistsWaiter` that can be used synchronously or with `isSuccess()`. ```APIDOC ## `queueExists` — Wait for Queue to Become Available A waiter that polls `GetQueueUrl` every 5 seconds (up to 200 seconds total) until the queue exists. Returns a `QueueExistsWaiter` that can be used synchronously or with `isSuccess()`. ```php use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient(['region' => 'us-east-1']); // After creating a queue, wait until it's ready $sqs->createQueue(['QueueName' => 'newly-created-queue']); $waiter = $sqs->queueExists(['QueueName' => 'newly-created-queue']); // Block until the queue exists (throws on timeout or failure) $waiter->wait(); echo "Queue is ready."; // Or poll non-blocking if ($waiter->isSuccess()) { echo "Queue already exists."; } else { echo "Queue not yet available."; } ``` ``` -------------------------------- ### sendMessage Source: https://context7.com/async-aws/sqs/llms.txt Delivers a message to a queue. Supports delayed delivery, custom message attributes, FIFO deduplication, and group IDs. ```APIDOC ## `sendMessage` — Send a Single Message Delivers a message to a queue. Supports delayed delivery, custom message attributes, FIFO deduplication, and group IDs. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\ValueObject\MessageAttributeValue; use AsyncAws\Sqs\Exception\InvalidMessageContentsException; $sqs = new SqsClient(['region' => 'us-east-1']); $queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue'; try { $result = $sqs->sendMessage([ 'QueueUrl' => $queueUrl, 'MessageBody' => json_encode(['action' => 'process_order', 'orderId' => 42]), 'DelaySeconds' => 5, 'MessageAttributes' => [ 'ContentType' => [ 'DataType' => 'String', 'StringValue' => 'application/json', ], 'Priority' => [ 'DataType' => 'Number', 'StringValue' => '1', ], ], ]); echo $result->getMessageId(); // e.g. "5fea7756-0ea4-451a-a703-a558b933e274" echo $result->getMd5OfMessageBody(); // MD5 of the body for integrity check } catch (InvalidMessageContentsException $e) { echo 'Message body contains invalid characters: ' . $e->getMessage(); } // FIFO queue — requires MessageGroupId; MessageDeduplicationId if content-based dedup is off $fifoResult = $sqs->sendMessage([ 'QueueUrl' => 'https://sqs.us-east-1.amazonaws.com/123456789012/my-ordered-queue.fifo', 'MessageBody' => 'order-event-payload', 'MessageGroupId' => 'orders-customer-99', 'MessageDeduplicationId' => 'order-42-created', ]); echo $fifoResult->getSequenceNumber(); // e.g. "18849496460467696128" ``` ``` -------------------------------- ### Cancel a Running DLQ Redrive Task Source: https://context7.com/async-aws/sqs/llms.txt Stop a message movement task. Messages already moved are not reverted. Only tasks in RUNNING status can be cancelled. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Exception\ResourceNotFoundException; $sqs = new SqsClient(['region' => 'us-east-1']); $taskHandle = 'AQEB...(task handle from startMessageMoveTask)'; try { $result = $sqs->cancelMessageMoveTask(['TaskHandle' => $taskHandle]); echo "Approximate messages moved before cancel: {$result->getApproximateNumberOfMessagesMoved()} "; } catch (ResourceNotFoundException $e) { echo "Task not found or already completed."; } ``` -------------------------------- ### QueueAttributeName Enum Source: https://context7.com/async-aws/sqs/llms.txt Provides strongly-typed constants for queue attribute names used in `createQueue` and `getQueueAttributes` operations, helping to prevent typos and ensure correct attribute specification. ```APIDOC ## `QueueAttributeName` Enum — Queue Attribute Constants Strongly-typed constants used with `createQueue` and `getQueueAttributes`. Prevents typo-based bugs when specifying attribute names. ```php use AsyncAws\Sqs\Enum\QueueAttributeName; // Available constants: QueueAttributeName::ALL; // 'All' QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES; // visible message count QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED; // delayed message count QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE; // in-flight count QueueAttributeName::DELAY_SECONDS; QueueAttributeName::FIFO_QUEUE; QueueAttributeName::FIFO_THROUGHPUT_LIMIT; QueueAttributeName::CONTENT_BASED_DEDUPLICATION; QueueAttributeName::DEDUPLICATION_SCOPE; QueueAttributeName::KMS_MASTER_KEY_ID; QueueAttributeName::KMS_DATA_KEY_REUSE_PERIOD_SECONDS; QueueAttributeName::MAXIMUM_MESSAGE_SIZE; QueueAttributeName::MESSAGE_RETENTION_PERIOD; QueueAttributeName::POLICY; QueueAttributeName::QUEUE_ARN; QueueAttributeName::RECEIVE_MESSAGE_WAIT_TIME_SECONDS; QueueAttributeName::REDRIVE_ALLOW_POLICY; QueueAttributeName::REDRIVE_POLICY; QueueAttributeName::SQS_MANAGED_SSE_ENABLED; QueueAttributeName::VISIBILITY_TIMEOUT; // Runtime validation $isValid = QueueAttributeName::exists('VisibilityTimeout'); // true $isValid = QueueAttributeName::exists('Nonexistent'); // false ``` ``` -------------------------------- ### purgeQueue Source: https://context7.com/async-aws/sqs/llms.txt Deletes all available and in-flight messages from a queue. The operation can take up to 60 seconds and can only be called once every 60 seconds per queue. ```APIDOC ## purgeQueue ### Description Deletes all available and in-flight messages in a queue. The operation can take up to 60 seconds. Can only be called once every 60 seconds per queue. ### Method POST ### Endpoint / ### Parameters #### Query Parameters - **QueueUrl** (string) - Required - The URL of the Amazon SQS queue. ### Request Example ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Exception\PurgeQueueInProgressException; $sqs = new SqsClient(['region' => 'us-east-1']); $queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue'; try { $sqs->purgeQueue(['QueueUrl' => $queueUrl]); echo "Purge initiated. Wait 60 seconds before sending new messages.\\n"; } catch (PurgeQueueInProgressException $e) { echo "A purge is already in progress for this queue."; } ``` ### Response #### Success Response (200) - **Result** (object) - A generic result indicating the operation was initiated. #### Error Response - **PurgeQueueInProgressException** - Thrown if a purge is already in progress for the queue. ``` -------------------------------- ### Using QueueAttributeName Enum for SQS Queue Configuration Source: https://context7.com/async-aws/sqs/llms.txt Utilize the `QueueAttributeName` enum to prevent typos when specifying queue attributes for operations like `createQueue` and `getQueueAttributes`. The `exists()` method can be used for runtime validation of attribute names. ```php use AsyncAws\Sqs\Enum\QueueAttributeName; // Available constants: QueueAttributeName::ALL; // 'All' QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES; // visible message count QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED; // delayed message count QueueAttributeName::APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE; // in-flight count QueueAttributeName::DELAY_SECONDS; QueueAttributeName::FIFO_QUEUE; QueueAttributeName::FIFO_THROUGHPUT_LIMIT; QueueAttributeName::CONTENT_BASED_DEDUPLICATION; QueueAttributeName::DEDUPLICATION_SCOPE; QueueAttributeName::KMS_MASTER_KEY_ID; QueueAttributeName::KMS_DATA_KEY_REUSE_PERIOD_SECONDS; QueueAttributeName::MAXIMUM_MESSAGE_SIZE; QueueAttributeName::MESSAGE_RETENTION_PERIOD; QueueAttributeName::POLICY; QueueAttributeName::QUEUE_ARN; QueueAttributeName::RECEIVE_MESSAGE_WAIT_TIME_SECONDS; QueueAttributeName::REDRIVE_ALLOW_POLICY; QueueAttributeName::REDRIVE_POLICY; QueueAttributeName::SQS_MANAGED_SSE_ENABLED; QueueAttributeName::VISIBILITY_TIMEOUT; // Runtime validation $isValid = QueueAttributeName::exists('VisibilityTimeout'); // true $isValid = QueueAttributeName::exists('Nonexistent'); // false ``` -------------------------------- ### receiveMessage Source: https://context7.com/async-aws/sqs/llms.txt Polls messages from an SQS queue. Supports long polling, custom visibility timeouts, and selective attribute retrieval. ```APIDOC ## `receiveMessage` — Poll Messages from a Queue Retrieves up to 10 messages. Supports long polling (`WaitTimeSeconds`), custom visibility timeout, and selective system/message attribute retrieval. ### Method POST ### Endpoint / ### Parameters #### Query Parameters - **QueueUrl** (string) - Required - The URL of the Amazon SQS queue to take messages from. - **MaxNumberOfMessages** (integer) - Optional - The maximum number of messages to return. Defaults to 1. - **WaitTimeSeconds** (integer) - Optional - The duration (in seconds) for which the poll call waits for a message to arrive. Defaults to 0. - **VisibilityTimeout** (integer) - Optional - The duration (in seconds) that the received messages are hidden from other consumers. Defaults to 30. - **MessageSystemAttributeNames** (array) - Optional - A list of receive message system attribute names to include in the returned messages. - **MessageAttributeNames** (array) - Optional - A list of all message attribute names to include in the returned messages. ### Request Example ```php $result = $sqs->receiveMessage([ 'QueueUrl' => $queueUrl, 'MaxNumberOfMessages' => 10, 'WaitTimeSeconds' => 20, 'VisibilityTimeout' => 120, 'MessageSystemAttributeNames' => [ MessageSystemAttributeName::APPROXIMATE_RECEIVE_COUNT, MessageSystemAttributeName::SENT_TIMESTAMP, ], 'MessageAttributeNames' => ['All'], ]); ``` ### Response #### Success Response (200) - **Messages** (array) - A list of messages. - **MessageId** (string) - The message's ID. - **ReceiptHandle** (string) - The identifier for the receipt of this message. - **Body** (string) - The body of the message. - **Attributes** (object) - Key-value pairs of message system attributes. - **MessageAttributes** (object) - Key-value pairs of message attributes. ``` -------------------------------- ### Send a Single Message Source: https://context7.com/async-aws/sqs/llms.txt Delivers a message to a queue with support for delayed delivery, custom attributes, FIFO deduplication, and group IDs. Catches InvalidMessageContentsException for invalid message bodies. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\ValueObject\MessageAttributeValue; use AsyncAws\Sqs\Exception\InvalidMessageContentsException; $sqs = new SqsClient(['region' => 'us-east-1']); $queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue'; try { $result = $sqs->sendMessage([ 'QueueUrl' => $queueUrl, 'MessageBody' => json_encode(['action' => 'process_order', 'orderId' => 42]), 'DelaySeconds' => 5, 'MessageAttributes' => [ 'ContentType' => [ 'DataType' => 'String', 'StringValue' => 'application/json', ], 'Priority' => [ 'DataType' => 'Number', 'StringValue' => '1', ], ], ]); echo $result->getMessageId(); // e.g. "5fea7756-0ea4-451a-a703-a558b933e274" echo $result->getMd5OfMessageBody(); // MD5 of the body for integrity check } catch (InvalidMessageContentsException $e) { echo 'Message body contains invalid characters: ' . $e->getMessage(); } // FIFO queue — requires MessageGroupId; MessageDeduplicationId if content-based dedup is off $fifoResult = $sqs->sendMessage([ 'QueueUrl' => 'https://sqs.us-east-1.amazonaws.com/123456789012/my-ordered-queue.fifo', 'MessageBody' => 'order-event-payload', 'MessageGroupId' => 'orders-customer-99', 'MessageDeduplicationId' => 'order-42-created', ]); echo $fifoResult->getSequenceNumber(); // e.g. "18849496460467696128" ``` -------------------------------- ### Receive Messages from SQS Queue Source: https://context7.com/async-aws/sqs/llms.txt Polls messages from an SQS queue with support for long polling, custom visibility timeouts, and selective attribute retrieval. Ensure the SQS client is configured with the correct region. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Enum\MessageSystemAttributeName; $sqs = new SqsClient(['region' => 'us-east-1']); $queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue'; $result = $sqs->receiveMessage([ 'QueueUrl' => $queueUrl, 'MaxNumberOfMessages' => 10, 'WaitTimeSeconds' => 20, // long polling — waits up to 20s for messages 'VisibilityTimeout' => 120, // hide from other consumers for 2 minutes 'MessageSystemAttributeNames' => [ MessageSystemAttributeName::APPROXIMATE_RECEIVE_COUNT, MessageSystemAttributeName::SENT_TIMESTAMP, ], 'MessageAttributeNames' => ['All'], ]); foreach ($result->getMessages() as $message) { $body = $message->getBody(); $receiptHandle = $message->getReceiptHandle(); $receiveCount = $message->getAttributes()[MessageSystemAttributeName::APPROXIMATE_RECEIVE_COUNT] ?? '0'; echo "MessageId: {$message->getMessageId()}\n"; echo "Body: {$body}\n"; echo "Received {$receiveCount} time(s)\n"; // Access custom message attributes foreach ($message->getMessageAttributes() as $name => $attr) { echo "Attribute {$name}: {$attr->getStringValue()}\n"; } // Process the message, then delete it $sqs->deleteMessage([ 'QueueUrl' => $queueUrl, 'ReceiptHandle' => $receiptHandle, ]); } ``` -------------------------------- ### Add IAM Policy to SQS Queue Source: https://context7.com/async-aws/sqs/llms.txt Grant specific AWS account IDs permissions to perform SQS actions on a queue. Limited to account-level principals. ```php use AsyncAws\Sqs\SqsClient; use AsyncAws\Sqs\Exception\OverLimitException; $sqs = new SqsClient(['region' => 'us-east-1']); $queueUrl = 'https://sqs.us-east-1.amazonaws.com/123456789012/my-task-queue'; try { $sqs->addPermission([ 'QueueUrl' => $queueUrl, 'Label' => 'AllowPartnerSendMessage', 'AWSAccountIds' => ['987654321098'], 'Actions' => ['SendMessage', 'GetQueueAttributes'], ]); echo "Permission added.\n"; } catch (OverLimitException $e) { echo "Maximum 7 actions per statement or policy limit reached."; } ```