### Complete AMQP Sender Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-sender.md Demonstrates establishing a TLS connection, creating a sender, sending a message, and handling acknowledgments and errors. Includes connection setup, sender creation with error handling, message sending logic based on credit availability, and proper resource closure. ```typescript import { Connection, Sender, Delivery } from "rhea-promise"; async function main() { const connection = new Connection({ transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password" }); try { await connection.open(); const sender = await connection.createSender({ name: "my-sender", target: { address: "my-queue" }, onError: (context) => { console.error("Sender error:", context.sender?.error); } }); sender.on("accepted", (context) => { console.log("Message accepted:", context.delivery?.id); }); // Check if we can send if (sender.sendable()) { const delivery = sender.send({ body: "Hello World!", message_id: "msg-001", properties: { content_type: "text/plain", subject: "greeting" } }); console.log("Message sent, delivery ID:", delivery.id); } else { console.log("Sender has no credit available"); } await new Promise(resolve => setTimeout(resolve, 1000)); await sender.close(); await connection.close(); } catch (err) { console.error("Error:", err); } } main(); ``` -------------------------------- ### Complete Connection Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md A full example demonstrating how to establish a TLS connection, create a sender, send a message, and close the connection. Includes error handling. ```typescript import { Connection, ConnectionOptions } from "rhea-promise"; async function main() { const connection = new Connection({ transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password", operationTimeoutInSeconds: 60 }); try { await connection.open(); const sender = await connection.createSender({ name: "my-sender", target: { address: "my-queue" } }); const delivery = sender.send({ body: "Hello!" }); console.log("Message sent, delivery ID:", delivery.id); await sender.close(); await connection.close(); } catch (err) { console.error("Error:", err); } } main(); ``` -------------------------------- ### Install rhea-promise Source: https://github.com/amqp/rhea-promise/blob/master/README.md Install the rhea-promise library using npm. Ensure you have Node.js version 20.x or higher. ```bash npm install rhea-promise ``` -------------------------------- ### Basic Send Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/README.md Demonstrates how to establish a connection, create a sender, send a message, and close the connection. ```typescript import { Connection } from "rhea-promise"; async function main() { const connection = new Connection({ transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password" }); await connection.open(); const sender = await connection.createSender({ name: "sender-1", target: { address: "my-queue" } }); const delivery = sender.send({ body: "Hello World!" }); console.log("Message sent, delivery ID:", delivery.id); await sender.close(); await connection.close(); } main().catch(console.error); ``` -------------------------------- ### Rhea-Promise Container Usage Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Demonstrates the basic usage of the rhea-promise Container, including creating an instance, establishing a TLS connection, and handling connection events. Ensure you have the necessary imports and an async context to run this example. ```typescript import { Container } from "rhea-promise"; async function main() { const container = new Container({ id: "my-app-container" }); const connection = await container.connect({ host: "amqp.example.com", port: 5671, transport: "tls", username: "user", password: "pass" }); console.log("Connected with ID:", connection.id); await connection.close(); } main().catch(console.error); ``` -------------------------------- ### Install NPM Dependencies Source: https://github.com/amqp/rhea-promise/blob/master/README.md Install project dependencies using npm ci from the root of the cloned repository. ```bash npm ci ``` -------------------------------- ### Basic Receive Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/README.md Demonstrates how to establish a connection, create a receiver, process incoming messages, and handle errors. ```typescript import { Connection } from "rhea-promise"; async function main() { const connection = new Connection({ transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password" }); await connection.open(); const receiver = await connection.createReceiver({ name: "receiver-1", source: { address: "my-queue" }, onMessage: (context) => { console.log("Received:", context.message?.body); }, onError: (context) => { console.error("Error:", context.receiver?.error); } }); // Keep receiving for 30 seconds await new Promise(resolve => setTimeout(resolve, 30000)); await receiver.close(); await connection.close(); } main().catch(console.error); ``` -------------------------------- ### Complete AMQP Connection and Session Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-session.md Demonstrates establishing a connection, creating a session, setting up a sender and receiver, sending a message, and closing resources. ```typescript import { Connection } from "rhea-promise"; async function main() { const connection = new Connection({ transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password" }); try { await connection.open(); const session = await connection.createSession(); console.log("Session created:", session.id); const sender = await session.createSender({ name: "sender", target: { address: "my-queue" } }); const receiver = await session.createReceiver({ name: "receiver", source: { address: "my-queue" }, onMessage: (context) => { console.log("Message:", context.message?.body); }, onError: (context) => { console.error("Error:", context.receiver?.error); } }); sender.send({ body: "Hello!" }); await new Promise(resolve => setTimeout(resolve, 1000)); await receiver.close(); await sender.close(); await session.close(); await connection.close(); } catch (err) { console.error("Error:", err); } } main(); ``` -------------------------------- ### Awaitable Send Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/README.md Demonstrates sending a message with delivery confirmation using an awaitable sender. ```typescript import { Connection } from "rhea-promise"; async function main() { const connection = new Connection({ transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password" }); await connection.open(); const sender = await connection.createAwaitableSender({ name: "awaitable-sender", target: { address: "my-queue" } }); // Send with delivery confirmation const delivery = await sender.send( { body: "Hello World!" }, { timeoutInSeconds: 10 } ); console.log("Message delivered:", delivery.id); await sender.close(); await connection.close(); } main().catch(console.error); ``` -------------------------------- ### Container.listen Method Source: https://github.com/amqp/rhea-promise/blob/master/review/rhea-promise.api.md Starts a server to listen for incoming AMQP connections. Accepts ListenOptions or TlsOptions with TlsServerConnectionOptions. ```typescript listen(options: ListenOptions | (TlsOptions & TlsServerConnectionOptions)): Server | Server_2; ``` -------------------------------- ### Complete AwaitableSender Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-awaitablesender.md Demonstrates establishing a connection, creating an AwaitableSender, sending multiple messages with error handling for individual sends, and closing the connection. ```typescript import { Connection, AwaitableSender, SendOperationFailedError } from "rhea-promise"; async function main() { const connection = new Connection({ transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password" }); try { await connection.open(); const sender = await connection.createAwaitableSender({ name: "awaitable-sender", target: { address: "my-queue" } }); // Send multiple messages with confirmation for (let i = 0; i < 5; i++) { try { const delivery = await sender.send( { body: `Message ${i}`, message_id: `msg-${i}`, properties: { content_type: "text/plain" } }, { timeoutInSeconds: 10 } ); console.log(`Message ${i} delivered:`, delivery.id); } catch (err) { if (err.name === "SendOperationFailedError") { const failureErr = err as SendOperationFailedError; console.error(`Message ${i} failed with code:`, failureErr.code); } else if (err.name === "InsufficientCreditError") { console.error("No credit, waiting..."); await new Promise(resolve => setTimeout(resolve, 1000)); i--; // Retry this message } else { throw err; } } } await sender.close(); await connection.close(); } catch (err) { console.error("Error:", err); } } main(); ``` -------------------------------- ### Complete Receiver and Connection Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-receiver.md Demonstrates establishing a TLS connection, creating a receiver with automatic credit management, handling messages and errors, and closing the receiver and connection. ```typescript import { Connection, ReceiverEvents } from "rhea-promise"; async function main() { const connection = new Connection({ transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password" }); try { await connection.open(); const receiver = await connection.createReceiver({ name: "my-receiver", source: { address: "my-queue" }, credit_window: 100, // Automatic credit management onMessage: (context) => { const message = context.message; console.log("Received message:", { body: message?.body, id: message?.message_id, contentType: message?.properties?.content_type }); }, onError: (context) => { console.error("Receiver error:", context.receiver?.error); }, onClose: (context) => { console.log("Receiver closed"); } }); console.log("Receiver created:", receiver.name); console.log("Receiver credit:", receiver.credit); // Keep receiving for 30 seconds await new Promise(resolve => setTimeout(resolve, 30000)); // Check receiver status before closing if (receiver.isOpen()) { await receiver.close({ closeSession: true }); } await connection.close(); } catch (err) { console.error("Error:", err); } } main(); ``` -------------------------------- ### Create Container Instance Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Creates a new Container instance with optional configuration. Use this as the starting point for AMQP operations. ```typescript const container = Container.create({ id: "my-container" }); ``` -------------------------------- ### Receive AMQP Message Source: https://github.com/amqp/rhea-promise/blob/master/README.md This snippet demonstrates how to set up a receiver to listen for and process incoming AMQP messages. It includes connection setup, receiver configuration, and event handlers for messages and errors. Ensure environment variables or a .env file are configured for connection details. ```typescript import { Connection, Receiver, EventContext, ConnectionOptions, ReceiverOptions, delay, ReceiverEvents } from "rhea-promise"; import * as dotenv from "dotenv"; // Optional for loading environment configuration from a .env (config) file dotenv.config(); const host = process.env.AMQP_HOST || "host"; const username = process.env.AMQP_USERNAME || "sharedAccessKeyName"; const password = process.env.AMQP_PASSWORD || "sharedAccessKeyValue"; const port = parseInt(process.env.AMQP_PORT || "5671"); const receiverAddress = process.env.RECEIVER_ADDRESS || "address"; async function main(): Promise { const connectionOptions: ConnectionOptions = { transport: "tls", host: host, hostname: host, username: username, password: password, port: port, reconnect: false }; const connection: Connection = new Connection(connectionOptions); const receiverName = "receiver-1"; const receiverOptions: ReceiverOptions = { name: receiverName, source: { address: receiverAddress }, onSessionError: (context: EventContext) => { const sessionError = context.session && context.session.error; if (sessionError) { console.log(">>>>> [%s] An error occurred for session of receiver '%s': %O.", connection.id, receiverName, sessionError); } } }; await connection.open(); const receiver: Receiver = await connection.createReceiver(receiverOptions); receiver.on(ReceiverEvents.message, (context: EventContext) => { console.log("Received message: %O", context.message); }); receiver.on(ReceiverEvents.receiverError, (context: EventContext) => { const receiverError = context.receiver && context.receiver.error; if (receiverError) { console.log(">>>>> [%s] An error occurred for receiver '%s': %O.", connection.id, receiverName, receiverError); } }); // sleeping for 2 mins to let the receiver receive messages and then closing it. await delay(120000); await receiver.close(); await connection.close(); } main().catch((err) => console.log(err)); ``` -------------------------------- ### Open Connection with Timeout using AbortSignal Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/errors.md A practical example of opening a connection with a specified timeout, utilizing AbortController to manage cancellation. ```typescript async function openWithTimeout( connection: Connection, timeoutMs: number = 10000 ): Promise { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeoutMs); try { await connection.open({ abortSignal: controller.signal }); return connection; } finally { clearTimeout(timeoutId); } } ``` -------------------------------- ### Manual Credit Management Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-receiver.md Configure a receiver with `credit_window: 0` to disable automatic credit. Manually grant credit using `addCredit()` to control message flow. ```typescript const receiver = await connection.createReceiver({ name: "manual-receiver", source: { address: "my-queue" }, credit_window: 0, // Disable automatic credit onMessage: (context) => { console.log("Message:", context.message?.body); }, onError: (context) => { console.error("Error:", context.receiver?.error); } }); // Grant credit manually receiver.addCredit(10); ``` -------------------------------- ### Enable AMQP Debug Logs (Excluding Message Transformation) Source: https://github.com/amqp/rhea-promise/blob/master/README.md Set the DEBUG environment variable to 'rhea*,-rhea:raw,-rhea:message,-rhea-promise:eventhandler,-rhea-promise:translate' to get AMQP debug logs while excluding message transformation details. ```bash export DEBUG=rhea*,-rhea:raw,-rhea:message,-rhea-promise:eventhandler,-rhea-promise:translate ``` -------------------------------- ### Simple Delay Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-utilities.md Use the delay function to pause execution for a specified number of milliseconds. ```typescript import { delay } from "rhea-promise"; await delay(1000); // Wait 1 second console.log("1 second passed"); ``` -------------------------------- ### Complete Rhea-Promise Configuration Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/configuration.md This snippet shows how to configure and use rhea-promise for AMQP communication. It includes connection settings, authentication, sender and receiver setup, message sending, and cleanup operations. ```typescript import { Connection, ReceiverEvents } from "rhea-promise"; const connection = new Connection({ // Connection settings transport: "tls", host: "amqp.example.com", port: 5671, hostname: "amqp.example.com", // Authentication username: "user@example.com", password: "password123", sasl_mechanisms: ["PLAIN"], // Protocol tuning idle_time_out: 60000, max_frame_size: 8192, channel_max: 2047, // Reconnection reconnect: true, reconnect_limit: 50, // rhea-promise settings operationTimeoutInSeconds: 60 }); await connection.open(); const sender = await connection.createSender({ name: "sender-1", target: { address: "my-queue", durable: 2 }, onError: (context) => { console.error("Sender error:", context.sender?.error); } }); const receiver = await connection.createReceiver({ name: "receiver-1", source: { address: "my-queue" }, credit_window: 100, onMessage: (context) => { console.log("Message:", context.message?.body); }, onError: (context) => { console.error("Receiver error:", context.receiver?.error); } }); // Send message sender.send({ body: "Hello!" }); // Wait a bit await new Promise(resolve => setTimeout(resolve, 1000)); // Clean up await receiver.close(); await sender.close(); await connection.close(); ``` -------------------------------- ### Automatic Credit Management Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-receiver.md Set `credit_window` to a positive value (e.g., 100) to enable automatic credit management. The library will maintain the specified number of messages in the credit window. ```typescript const receiver = await connection.createReceiver({ name: "auto-receiver", source: { address: "my-queue" }, credit_window: 100, // Automatically maintain 100 messages in window onMessage: (context) => { console.log("Message:", context.message?.body); }, onError: (context) => { console.error("Error:", context.receiver?.error); } }); ``` -------------------------------- ### Session.begin Source: https://github.com/amqp/rhea-promise/blob/master/review/rhea-promise.api.md Initiates a new AMQP session. ```APIDOC ## Session.begin ### Description Initiates a new AMQP session. ### Signature ```typescript begin(): void; ``` ``` -------------------------------- ### Delay with Value Example Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-utilities.md Use the delay function to pause execution and resolve with a specific value. ```typescript const result = await delay(500, "Done!"); console.log(result); // "Done!" ``` -------------------------------- ### begin Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-session.md Initiates the session begin handshake. ```APIDOC ## begin() ### Description Initiates the session begin handshake. ### Method POST ### Endpoint N/A (Method on Session object) ### Returns - **void** ``` -------------------------------- ### Build Rhea-Promise Project Source: https://github.com/amqp/rhea-promise/blob/master/README.md Build the rhea-promise project using the npm run build command. ```bash npm run build ``` -------------------------------- ### Get TLS Socket Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md Retrieves the underlying TLS socket. Use this for advanced socket-level operations if needed. ```typescript getTlsSocket(): Socket | undefined ``` -------------------------------- ### Get Peer Certificate Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md Retrieves the peer's TLS certificate. This is only available if a TLS connection is established. ```typescript getPeerCertificate(): PeerCertificate | undefined ``` -------------------------------- ### Get Connection Error Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md Retrieves the connection error if one has occurred. Returns undefined if the connection is healthy. ```typescript getError(): ConnectionError | undefined ``` -------------------------------- ### Listen for Incoming Connections Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Set up a server listener for incoming AMQP connections on a specified port and host. Handles connection events. ```typescript const server = container.listen({ port: 5671, host: "0.0.0.0" }); server.on("connection", (socket) => { console.log("Incoming connection from", socket.remoteAddress); }); ``` -------------------------------- ### Set and Get Drain Property Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-receiver.md Enable or disable the drain mode on a receiver link, and check its current status. ```typescript receiver.drain = true; // Enable drain const isDraining = receiver.drain; // Check drain status ``` -------------------------------- ### Create Connection Instance Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md Instantiate a new Connection object with specific configuration options. Ensure all required connection parameters like host, port, and credentials are provided. ```typescript import { Connection, ConnectionOptions } from "rhea-promise"; const options: ConnectionOptions = { transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password", operationTimeoutInSeconds: 60 }; const connection = new Connection(options); ``` -------------------------------- ### Connection Constructor Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md Creates a new Connection instance with specified options. The options can configure transport, host, port, credentials, and timeouts. ```APIDOC ## Connection Constructor ### Description Creates a new Connection instance. ### Signature ```typescript constructor(options?: ConnectionOptions | CreatedRheaConnectionOptions) ``` ### Parameters #### Path Parameters - **options** (ConnectionOptions | CreatedRheaConnectionOptions) - Optional - Configuration for the connection including host, credentials, timeouts. Defaults to `{ transport: "tls" }`. ### Request Example ```typescript import { Connection, ConnectionOptions } from "rhea-promise"; const options: ConnectionOptions = { transport: "tls", host: "amqp.example.com", port: 5671, username: "user", password: "password", operationTimeoutInSeconds: 60 }; const connection = new Connection(options); ``` ``` -------------------------------- ### Receiver.drain Source: https://github.com/amqp/rhea-promise/blob/master/review/rhea-promise.api.md Gets or sets the drain mode for the receiver. When drain is true, the receiver will stop accepting new messages once its credit is exhausted. ```APIDOC ## Receiver.drain ### Description Gets or sets the drain mode for the receiver. When drain is true, the receiver will stop accepting new messages once its credit is exhausted. ### Getter ```typescript get drain(): boolean; ``` ### Setter ```typescript set drain(value: boolean); ``` ### Parameters * **value** (boolean) - Set to true to enable drain mode, false to disable. ``` -------------------------------- ### Receiver Event Handling Examples Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-receiver.md Listen for incoming messages, settlement by remote, and receiver errors. Ensure the receiver object is available in the context. ```typescript receiver.on("message", (context) => { console.log("Message received:", context.message?.body); }); receiver.on("settled", (context) => { console.log("Message settled by remote"); }); receiver.on("receiver_error", (context) => { console.error("Receiver error:", context.receiver?.error); }); ``` -------------------------------- ### Container Constructor Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Creates a new Container instance with optional configuration options. ```APIDOC ## Container(options?: ContainerOptions) ### Description Creates a new Container instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | ContainerOptions | No | `{}` | Configuration options for the container, including optional `createdInstance` to wrap an existing rhea container | ### Request Example ```typescript import { Container, ContainerOptions } from "rhea-promise"; const container = new Container({ id: "my-container", autoconnect: false }); ``` ### Response #### Success Response None #### Response Example None ``` -------------------------------- ### Send Message with AbortSignal Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/configuration.md Send a message asynchronously and provide an AbortSignal to cancel the operation. This example demonstrates cancelling the send after 5 seconds. ```typescript const controller = new AbortController(); // Cancel after 5 seconds const timer = setTimeout(() => controller.abort(), 5000); try { const delivery = await sender.send( { body: "Hello!" }, { timeoutInSeconds: 30, abortSignal: controller.signal } ); } catch (err) { if (err.name === "AbortError") { console.log("Send was cancelled"); } } finally { clearTimeout(timer); } ``` -------------------------------- ### Clone Rhea-Promise Repository Source: https://github.com/amqp/rhea-promise/blob/master/README.md Clone the rhea-promise repository from GitHub to your local machine. ```bash git clone https://github.com/amqp/rhea-promise.git ``` -------------------------------- ### Message Filtering on Receiver Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/README.md Configures a receiver to only accept messages that match a specific selector filter. This example filters messages with a 'priority' property equal to 'high'. ```typescript import { filter } from "rhea-promise"; const receiver = await connection.createReceiver({ source: { address: "queue", filter: filter.selector("priority = 'high'") }, onMessage: (context) => { console.log("High priority:", context.message?.body); } }); ``` -------------------------------- ### ConnectionOpenOptions Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/types.md Options for the Connection.open() method, primarily for cancellation. ```APIDOC ## ConnectionOpenOptions ### Description Options for the Connection.open() method, primarily for cancellation. ### Fields - **abortSignal** (AbortSignalLike) - No - Signal to cancel the operation ``` -------------------------------- ### connect Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Creates and opens a connection in a single asynchronous operation. This is a convenient way to establish a connection immediately. ```APIDOC ## async connect(options?: ConnectionOptions): Promise ### Description Creates and opens a connection in a single operation. ### Method Not applicable (method call) ### Endpoint Not applicable (method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | options | ConnectionOptions | No | Options for configuring and opening the connection | ### Request Example ```typescript const connection = await container.connect({ host: "amqp.example.com", port: 5671, transport: "tls", username: "user", password: "password" }); console.log("Connected:", connection.id); ``` ### Response #### Success Response - **Promise** (Promise) - Resolves to an open Connection object #### Response Example None ``` -------------------------------- ### Create Container Instance Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Instantiate a new Container with optional configuration options. Use 'autoconnect: false' to prevent immediate connection attempts. ```typescript import { Container, ContainerOptions } from "rhea-promise"; const container = new Container({ id: "my-container", autoconnect: false }); ``` -------------------------------- ### Override Default Send Timeout Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/configuration.md Override the default send timeout for a specific message send operation. This example sets the timeout to 60 seconds for a single message. ```typescript const delivery = await sender.send( { body: "Hello!" }, { timeoutInSeconds: 60 } // Override default ); ``` -------------------------------- ### Container.connect Method Source: https://github.com/amqp/rhea-promise/blob/master/review/rhea-promise.api.md Establishes a connection to an AMQP broker using provided connection options. Returns a Promise resolving to a Connection object. ```typescript connect(options?: ConnectionOptions): Promise; ``` -------------------------------- ### ContainerOptions Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/types.md Options for creating a Container. It can optionally wrap an existing RheaContainer instance. ```APIDOC ## ContainerOptions ### Description Options for creating a Container. It can optionally wrap an existing RheaContainer instance. ### Fields - **createdInstance** (RheaContainer) - No - An existing rhea Container instance to wrap ``` -------------------------------- ### Set Custom Operation Timeout Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/configuration.md Configure a custom timeout for all asynchronous operations on a connection, such as opening the connection or creating sessions/links. This example sets the timeout to 120 seconds. ```typescript const connection = new Connection({ host: "amqp.example.com", operationTimeoutInSeconds: 120 // 2 minutes }); await connection.open(); // Timeout after 120 seconds ``` -------------------------------- ### listen Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Creates a server listener for incoming AMQP connections. This method is used to accept connections from remote clients. ```APIDOC ## listen(options: ListenOptions | (TlsOptions & TlsServerConnectionOptions)): Server | TlsServer ### Description Creates a server listener for incoming AMQP connections. ### Method Not applicable (method call) ### Endpoint Not applicable (method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | options | ListenOptions \| (TlsOptions & TlsServerConnectionOptions) | Yes | Server configuration including port, host, and optional TLS settings | ### Request Example ```typescript const server = container.listen({ port: 5671, host: "0.0.0.0" }); server.on("connection", (socket) => { console.log("Incoming connection from", socket.remoteAddress); }); ``` ### Response #### Success Response - **Server | TlsServer** (Server | TlsServer) - The underlying Node.js server instance #### Response Example None ``` -------------------------------- ### Create Connection from Connection String Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-utilities.md Parse a connection string and use the configuration to create a new AMQP connection. ```typescript const connStr = process.env.AMQP_CONNECTION || "host=localhost;port=5672;username=guest;password=guest"; const config = parseConnectionString(connStr); const connection = new Connection({ transport: "tls", host: config.host, port: parseInt(config.port || "5671"), username: config.username, password: config.password }); ``` -------------------------------- ### Strongly Typed Connection Configuration using ParsedOutput Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-utilities.md Example of using the ParsedOutput generic type to strongly type the result of parsing a connection string. This provides type safety for connection configurations. ```typescript interface ConnectionConfig { host: string; port: string; username: string; password: string; } const config = parseConnectionString( "host=amqp.example.com;port=5671;username=user;password=pass" ); // config is strongly typed as ConnectionConfig ``` -------------------------------- ### CreateReceiverOptions Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/types.md Options for Connection.createReceiver(). Allows specifying an existing session and an abort signal. ```APIDOC ## CreateReceiverOptions ### Description Options for Connection.createReceiver(). ### Fields #### session (Session) - Optional - Existing session to create receiver on #### abortSignal (AbortSignalLike) - Optional - Signal to cancel the operation #### ... (All ReceiverOptions fields) ``` -------------------------------- ### Handling SendOperationFailedError with a Switch Statement Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/errors.md Provides a detailed approach to handling SendOperationFailedError by inspecting its 'code' property. This example shows specific actions for 'rejected', 'released', 'modified', 'sender_error', and 'session_error' codes. ```typescript try { const delivery = await sender.send(message); } catch (err) { if (err.name === "SendOperationFailedError") { const failErr = err as SendOperationFailedError; switch (failErr.code) { case "rejected": console.error("Message rejected by server:", failErr.message); // Don't retry - message is invalid break; case "released": console.error("Message released by server, retrying..."); // Can retry - message wasn't processed return sendWithRetry(sender, message); case "modified": console.warn("Message was modified:", failErr.message); // Server processed with modifications break; case "sender_error": case "session_error": console.error("Link disconnected, need to reconnect"); // Must reconnect throw new Error("Reconnection required"); } } else { throw err; } } ``` -------------------------------- ### Connect to AMQP Server Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Asynchronously create and open a connection to an AMQP server. This method resolves to an open Connection object. ```typescript const connection = await container.connect({ host: "amqp.example.com", port: 5671, transport: "tls", username: "user", password: "password" }); console.log("Connected:", connection.id); ``` -------------------------------- ### ConnectionOptions Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/types.md Options for creating a Connection. This includes standard connection options along with WebSocket configuration and operation timeouts. ```APIDOC ## ConnectionOptions ### Description Options for creating a Connection. This includes standard connection options along with WebSocket configuration and operation timeouts. ### Fields - **operationTimeoutInSeconds** (number) - No - Timeout for async operations (open, close, create) (Default: 60) - **webSocketOptions** (object) - No - WebSocket configuration including constructor, URL, and protocol - **webSocketOptions.webSocket** (any) - Conditional - WebSocket constructor (required if using WebSocket) - **webSocketOptions.url** (string) - Conditional - WebSocket URL (required if using WebSocket) - **webSocketOptions.protocol** (string[]) - Conditional - WebSocket subprotocol list - **webSocketOptions.options** (any) - No - Additional options for WebSocket connect ``` -------------------------------- ### createSender Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md Creates a new AMQP sender link. Creates a new session if not provided in options. Resolves to an open Sender. Throws OperationTimeoutError, AmqpError, or AbortError. ```APIDOC ## createSender(options?: CreateSenderOptions): Promise ### Description Creates a new AMQP sender link. Creates a new session if not provided in options. ### Method `createSender` ### Parameters #### Path Parameters - **options** (CreateSenderOptions) - Optional - Sender options including target address, session (optional), and abortSignal ### Response #### Success Response - **Promise** - Resolves to an open Sender ### Throws - `OperationTimeoutError` if timeout occurs - `AmqpError` on failure - `AbortError` if `abortSignal` is aborted ### Request Example ```typescript const sender = await connection.createSender({ name: "sender-1", target: { address: "queue-name" } }); const delivery = sender.send({ body: "Hello World!" }); ``` ``` -------------------------------- ### Container.create Method Source: https://github.com/amqp/rhea-promise/blob/master/review/rhea-promise.api.md Creates a new Container instance. Accepts optional ContainerOptionsBase. ```typescript static create(options?: ContainerOptionsBase): Container; ``` -------------------------------- ### createSession Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md Creates a new AMQP session. Resolves to a new open Session. Throws OperationTimeoutError, AmqpError, or AbortError. ```APIDOC ## createSession(options?: SessionCreateOptions): Promise ### Description Creates a new AMQP session. ### Method `createSession` ### Parameters #### Path Parameters - **options** (SessionCreateOptions) - Optional - Options including optional `abortSignal` ### Response #### Success Response - **Promise** - Resolves to a new open Session ### Throws - `OperationTimeoutError` if timeout occurs - `AmqpError` on session creation failure - `AbortError` if `abortSignal` is aborted ### Request Example ```typescript const session = await connection.createSession(); console.log("Session created:", session.id); ``` ``` -------------------------------- ### Connection.open Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md Opens the AMQP connection asynchronously. It resolves with the Connection instance upon successful opening or rejects on failure. ```APIDOC ## Connection.open ### Description Opens the AMQP connection. ### Method `async open(options?: ConnectionOpenOptions): Promise` ### Parameters #### Path Parameters - **options** (ConnectionOpenOptions) - Optional - Options including optional `abortSignal` to cancel the operation. ### Returns `Promise` - Resolves to this Connection instance when open ### Throws - `Error` or `AmqpError` on connection failure - `AbortError` if `abortSignal` is aborted ### Request Example ```typescript const connection = new Connection({ host: "amqp.example.com", port: 5671, transport: "tls", username: "user", password: "password" }); try { await connection.open(); console.log("Connection opened:", connection.id); } catch (err) { console.error("Failed to open connection:", err); } ``` ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/README.md Environment variables to control the verbosity of logging output for the rhea-promise library and related AMQP components. ```bash export DEBUG=rhea-promise* # rhea-promise logs only export DEBUG=rhea* # All AMQP logs export DEBUG=rhea*,-rhea:raw # Exclude verbose categories ``` -------------------------------- ### Connection.open Method Source: https://github.com/amqp/rhea-promise/blob/master/review/rhea-promise.api.md Opens the AMQP connection asynchronously. Accepts optional ConnectionOpenOptions. ```typescript open(options?: ConnectionOpenOptions): Promise; ``` -------------------------------- ### Enable rhea-promise Debug Logs Source: https://github.com/amqp/rhea-promise/blob/master/README.md Set the DEBUG environment variable to 'rhea-promise*' to enable debug logs specifically for this library. ```bash export DEBUG=rhea-promise* ``` -------------------------------- ### Importing Utility Functions Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-utilities.md Import necessary utility functions and types from the rhea-promise library. ```typescript import { delay, parseConnectionString, isAmqpError, AmqpResponseStatusCode, messageProperties, messageHeader, ParsedOutput, Func, AbortSignalLike } from "rhea-promise"; ``` -------------------------------- ### Using Standard AbortController for Connection Cancellation Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-utilities.md Demonstrates how to use a standard AbortController to cancel a connection attempt. The connection open operation is cancelled after a 5-second timeout. ```typescript import { Connection } from "rhea-promise"; const controller = new AbortController(); // Start connection const openPromise = connection.open({ abortSignal: controller.signal }); // Cancel after 5 seconds const timeoutId = setTimeout(() => controller.abort(), 5000); try { await openPromise; clearTimeout(timeoutId); } catch (err) { if (err.name === "AbortError") { console.log("Connection open was cancelled"); } } ``` -------------------------------- ### Import Connection Class Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-connection.md Import the Connection class from the rhea-promise library. This is typically the first step before using any connection-related functionality. ```typescript import { Connection } from "rhea-promise"; ``` -------------------------------- ### Create Basic Sender Link Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/configuration.md This snippet demonstrates the minimal configuration required to create a sender link. It specifies the sender's name and the target queue address. ```typescript const sender = await connection.createSender({ name: "my-sender", target: { address: "my-queue" } }); ``` -------------------------------- ### Parse Connection String - Standard Format Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-utilities.md Parse a standard AMQP connection string into configuration options. ```typescript import { parseConnectionString } from "rhea-promise"; const connStr = "host=amqp.example.com;port=5671;username=user;password=pass"; const config = parseConnectionString(connStr); console.log(config.host); // "amqp.example.com" console.log(config.port); // "5671" console.log(config.username); // "user" ``` -------------------------------- ### CreatedRheaConnectionOptions Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/types.md Options for wrapping an existing rhea Connection. Requires the rhea connection and the rhea-promise Container instance. ```APIDOC ## CreatedRheaConnectionOptions ### Description Options for wrapping an existing rhea Connection. Requires the rhea connection and the rhea-promise Container instance. ### Fields - **operationTimeoutInSeconds** (number) - No - Timeout for async operations - **rheaConnection** (RheaConnection) - Yes - The underlying rhea connection object - **container** (Container) - Yes - The rhea-promise Container instance ``` -------------------------------- ### Create WebSocket Connection Implementation Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Creates a WebSocket connection implementation using a provided WebSocket library. This is useful for establishing AMQP over WebSocket connections. ```typescript import WebSocket from "ws"; const wsImpl = container.websocketConnect(WebSocket); ``` -------------------------------- ### Handling AbortError in Connection Open Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/errors.md Demonstrates how to catch and identify an AbortError when opening a connection with an abort signal. ```typescript const controller = new AbortController(); const connectionPromise = connection.open({ abortSignal: controller.signal }); // Abort after 5 seconds setTimeout(() => controller.abort(), 5000); try { await connectionPromise; } catch (err) { if (err.name === "AbortError") { console.log("Connection open was cancelled"); } } ``` -------------------------------- ### Container Source: https://github.com/amqp/rhea-promise/blob/master/review/rhea-promise.api.md Manages AMQP connections and provides factory methods for creating them. It also handles global settings and utilities. ```APIDOC ## Container ### Description Manages AMQP connections and provides factory methods for creating them. It also handles global settings and utilities. ### Methods - `static copyFromContainerInstance(instance: Container_2): Container`: Creates a new Container instance by copying from an existing one. - `static create(options?: ContainerOptionsBase): Container`: Creates a new Container instance. - `connect(options?: ConnectionOptions): Promise`: Connects to an AMQP service and returns a Promise that resolves with a Connection object. - `createConnection(options?: ConnectionOptions): Connection`: Creates a Connection object without immediately connecting. - `generateUUid(): string`: Generates a universally unique identifier. - `listen(options: ListenOptions | (TlsOptions & TlsServerConnectionOptions)): Server | Server_2`: Starts listening for incoming AMQP connections. - `stringToUuid(uuidString: string): Buffer`: Converts a UUID string to a Buffer. - `uuidToString(buffer: Buffer): string`: Converts a Buffer to a UUID string. - `websocketAccept(socket: Socket, options: ConnectionOptions_2): void`: Accepts an incoming WebSocket connection. - `websocketConnect(impl: any): any`: Establishes a WebSocket connection. ### Properties - `filter`: The filter used by the container. - `id`: The unique identifier of the container. - `message`: Utilities for working with AMQP messages. - `options`: The options used to configure the container. - `sasl`: The SASL negotiation handler. - `saslServerMechanisms`: The available SASL server mechanisms. - `types`: Utilities for AMQP types. ``` -------------------------------- ### Container API Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/README.md Methods for managing AMQP connections and servers. ```APIDOC ## Container API ### `createConnection()` Creates a new AMQP connection object. ### `connect()` Creates and opens a new AMQP connection. ### `listen()` Starts a server to accept incoming AMQP connections. ``` -------------------------------- ### Enable All AMQP Debug Logs Source: https://github.com/amqp/rhea-promise/blob/master/README.md Set the DEBUG environment variable to 'rhea*' to enable debug logs for both rhea-promise and the underlying rhea library. ```bash export DEBUG=rhea* ``` -------------------------------- ### Create Connection Object Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Create a Connection object without initiating an immediate connection. Configure connection details like host, port, transport, and credentials. ```typescript const connection = container.createConnection({ host: "amqp.example.com", port: 5671, transport: "tls", username: "user", password: "password" }); ``` -------------------------------- ### Container.create Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Static factory method to create a Container instance. Allows for the creation of a new Container with optional configuration. ```APIDOC ## Container.create ### Description Static factory method to create a Container instance. ### Signature ```typescript static create(options?: ContainerOptionsBase): Container ``` ### Parameters #### Path Parameters - **options** (ContainerOptionsBase) - Optional - Container configuration options ### Returns `Container` - New Container instance ### Example ```typescript const container = Container.create({ id: "my-container" }); ``` ``` -------------------------------- ### Connection Options Interface Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/README.md Defines the configuration options for establishing a connection. Includes transport protocol, host, port, credentials, and timeout settings. ```typescript interface ConnectionOptions { transport?: "tcp" | "tls"; // Default: "tls" host?: string; // Default: "localhost" port?: number; // Default: 5671 (tls) / 5672 (tcp) username?: string; password?: string; operationTimeoutInSeconds?: number; // Default: 60 webSocketOptions?: { webSocket: any; url: string; protocol: string[]; }; } ``` -------------------------------- ### ConnectionOptions Type Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/types.md Options for creating a Connection. Includes standard options, operation timeouts, and WebSocket configuration. ```typescript type ConnectionOptions = RheaConnectionOptions & { operationTimeoutInSeconds?: number; webSocketOptions?: { webSocket: any; url: string; protocol: string[]; options?: any; }; } ``` -------------------------------- ### ReceiverOptions Source: https://github.com/amqp/rhea-promise/blob/master/review/rhea-promise.api.md Options for configuring an AMQP receiver. ```APIDOC ## ReceiverOptions ### Description Options for configuring an AMQP receiver. ### Interface Definition ```typescript export interface ReceiverOptions extends ReceiverOptions_2 { onClose?: OnAmqpEvent; onError?: OnAmqpEvent; onMessage?: OnAmqpEvent; onSessionClose?: OnAmqpEvent; onSessionError?: OnAmqpEvent; onSettled?: OnAmqpEvent; } ``` ### Properties * **onClose** (OnAmqpEvent) - Callback for when the receiver is closed. * **onError** (OnAmqpEvent) - Callback for when an error occurs on the receiver. * **onMessage** (OnAmqpEvent) - Callback for when a message is received. * **onSessionClose** (OnAmqpEvent) - Callback for when the associated session is closed. * **onSessionError** (OnAmqpEvent) - Callback for when an error occurs on the associated session. * **onSettled** (OnAmqpEvent) - Callback for when a message settlement is acknowledged. ``` -------------------------------- ### Import Session Class Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-session.md Import the Session class from the rhea-promise library. This is the first step to using session functionalities. ```typescript import { Session } from "rhea-promise"; ``` -------------------------------- ### createConnection Source: https://github.com/amqp/rhea-promise/blob/master/_autodocs/api-reference-container.md Creates a new Connection object without immediately connecting. Use this to configure a connection before establishing it. ```APIDOC ## createConnection(options?: ConnectionOptions): Connection ### Description Creates a new Connection object without immediately connecting. ### Method Not applicable (method call) ### Endpoint Not applicable (method call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | options | ConnectionOptions | No | Options for configuring the connection (host, port, credentials, etc.) | ### Request Example ```typescript const connection = container.createConnection({ host: "amqp.example.com", port: 5671, transport: "tls", username: "user", password: "password" }); ``` ### Response #### Success Response - **Connection** (Connection) - A new Connection instance #### Response Example None ```