### Complete QStash Message Workflow Example in Rust Source: https://context7.com/drsh4dow/qstash-rs/llms.txt This example illustrates the complete lifecycle of a QStash message using the qstash-rs library. It covers publishing a JSON message with various options, waiting for processing, checking its status, querying events related to the message, and verifying its absence from the dead letter queue. The snippet includes publishing with delay, deduplication, and callback URLs. ```rust use qstash_rs::client::{Client, PublishRequestUrl, PublishOptions}; use std::collections::HashMap; use tokio::time::{sleep, Duration}; #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); // 1. Publish a message with tracking options let options = PublishOptions { headers: None, delay: Some(10), // 10 seconds not_before: None, deduplication_id: Some("workflow-example-001".to_string()), content_based_deduplication: None, retries: Some(3), callback: Some("https://api.example.com/status".to_string()), method: None, }; let payload = HashMap::from([ ("workflow", "order_processing"), ("order_id", "ORD-12345"), ("status", "pending"), ]); println!("Publishing message..."); let responses = client .publish_json( PublishRequestUrl::Url("https://api.example.com/orders".parse().unwrap()), payload, Some(options), ) .await .expect("Failed to publish"); let message_id = responses[0] .message_id .as_ref() .expect("No message ID") .clone(); println!("Published message ID: {}", message_id); // 2. Wait for processing sleep(Duration::from_secs(2)).await; // 3. Check message status let message = client .get_message(&message_id) .await .expect("Failed to retrieve message"); println!("Message URL: {}", message.url); println!("Created at: {}", message.created_at); // 4. Query recent events let events = client .get_events(None) .await .expect("Failed to get events"); let msg_events: Vec<_> = events .events .iter() .filter(|e| e.message_id == message_id) .collect(); println!("Found {} events for message", msg_events.len()); for event in msg_events { println!(" State: {:?}, Time: {}", event.state, event.time); } // 5. Check DLQ for failures let dlq = client .get_dead_letter_queue(None) .await .expect("Failed to get DLQ"); if dlq.messages.iter().any(|m| m.message_id == message_id) { println!("WARNING: Message found in dead letter queue"); } // 6. Cancel message if needed (before delivery) // match client.cancel_message(&message_id).await { // Ok(_) => println!("Message canceled"), // Err(e) => eprintln!("Could not cancel: {}", e), // } } ``` -------------------------------- ### Install qstash-rs SDK with Cargo Source: https://github.com/drsh4dow/qstash-rs/blob/main/README.md This snippet shows how to add the qstash-rs Rust library to your project using the cargo package manager. Ensure you have Rust and Cargo installed. ```bash cargo add qstash-rs ``` -------------------------------- ### Publish JSON Message to QStash Queue in Rust Source: https://github.com/drsh4dow/qstash-rs/blob/main/README.md An example of publishing a JSON message to a specified URL using the qstash-rs client in Rust. It includes error handling and checks the response for any errors. This requires the `tokio` runtime and the `qstash-rs` crate. ```rust use qstash_rs::{Client, PublishRequestUrl}; use std::collections::HashMap; #[tokio::main] async fn main() { let qstash_client = Client::new("", None, None).expect("Could not create client"); match qstash_client .publish_json( PublishRequestUrl::Url("https://google.com".parse().expect("Could not parse URL")), HashMap::from([("test", "test")]), // Example HashMap None, ) .await { Ok(r) => { tracing::info!("Response: {:?}", r); for res in r { if res.error.is_some() { panic!("This should NOT have an error"); } } } Err(e) => { tracing::error!("{}", e.to_string()); panic!("Could not publish"); } }; } ``` -------------------------------- ### Initialize QStash Client in Rust Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Demonstrates how to initialize a QStash client in Rust using the qstash-rs SDK. It shows basic initialization with a token, custom base URL, and specific API version settings. Dependencies include tokio for async execution. ```rust use qstash_rs::client::{Client, Version}; #[tokio::main] async fn main() { // Basic initialization with default settings (V2 API, default base URL) let client = Client::new( "qstash_token_here", None, None ).expect("Failed to create client"); // With custom base URL let client = Client::new( "qstash_token_here", Some("https://custom-qstash.upstash.io"), None ).expect("Failed to create client"); // With specific API version let client = Client::new( "qstash_token_here", None, Some(Version::V2) ).expect("Failed to create client"); } ``` -------------------------------- ### Client Initialization Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Initialize a QStash client with your authentication token and optional configuration for custom base URLs or API versions. ```APIDOC ## Client Initialization ### Description Initialize a QStash client with authentication token and optional configuration. ### Method Initialization (Not an HTTP method, but a library function) ### Endpoint N/A (Client-side SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use qstash_rs::client::{Client, Version}; #[tokio::main] async fn main() { // Basic initialization with default settings (V2 API, default base URL) let client = Client::new( "qstash_token_here", None, None ).expect("Failed to create client"); // With custom base URL let client = Client::new( "qstash_token_here", Some("https://custom-qstash.upstash.io"), None ).expect("Failed to create client"); // With specific API version let client = Client::new( "qstash_token_here", None, Some(Version::V2) ).expect("Failed to create client"); } ``` ### Response #### Success Response (200) N/A (Initialization does not typically return an HTTP response) #### Response Example N/A ``` -------------------------------- ### Initialize QStash Client in Rust Source: https://github.com/drsh4dow/qstash-rs/blob/main/README.md Demonstrates how to create a new instance of the QStash client in Rust using the tokio runtime. It requires a QStash token and optionally allows for configuration of the API URL and version. ```rust use qstash_rs::Client; #[tokio::main] async fn main() { let qstash_client = Client::new("", None, None).expect("Could not create client"); } ``` -------------------------------- ### Publish JSON Messages to Topics in Rust Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Illustrates publishing JSON messages to QStash topics for broadcast distribution using the qstash-rs SDK. This enables a pub/sub pattern where messages are sent to multiple subscribers. It demonstrates handling the responses, which include details for each subscriber. Dependencies include tokio for async operations. ```rust use qstash_rs::client::{Client, PublishRequestUrl}; use std::collections::HashMap; #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); // Publish to a topic (broadcasts to all subscribers) let result = client .publish_json( PublishRequestUrl::Topic("user-events".to_string()), HashMap::from([ ("event_type", "login"), ("user_id", "12345"), ("timestamp", "2025-10-07T12:00:00Z"), ]), // Note: HashMap is used for simplicity. For complex topic messages, a serialized struct is recommended. None, ) .await .expect("Failed to publish to topic"); // Topic responses contain multiple entries (one per subscriber) for response in result { match (response.message_id, response.url) { (Some(id), Some(url)) => { println!("Sent to {} with message ID: {}", url, id); } _ => { if let Some(err) = response.error { eprintln!("Failed to send to subscriber: {}", err); } } } } } ``` -------------------------------- ### Publishing to Topics Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Publish messages to QStash topics, enabling distribution to multiple subscribers using a pub/sub pattern. ```APIDOC ## Publishing to Topics ### Description Publish messages to topics for distribution to multiple subscribers. ### Method POST (Implicitly used by the SDK to interact with QStash API) ### Endpoint `/publish/topic` (Implicitly used by the SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **topic_name** (String) - Required - The name of the topic to publish to. - **payload** (Serialize) - Required - The JSON payload to send. - **options** (PublishOptions) - Optional - Configuration for delivery, retries, callbacks, etc. (Same as for URL publishing). ### Request Example ```rust use qstash_rs::client::{Client, PublishRequestUrl}; use std::collections::HashMap; #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); // Publish to a topic (broadcasts to all subscribers) let result = client .publish_json( PublishRequestUrl::Topic("user-events".to_string()), HashMap::from([ ("event_type", "login"), ("user_id", "12345"), ("timestamp", "2025-10-07T12:00:00Z"), ]), None, ) .await .expect("Failed to publish to topic"); // Topic responses contain multiple entries (one per subscriber) for response in result { match (response.message_id, response.url) { (Some(id), Some(url)) => { println!("Sent to {} with message ID: {}", url, id); } _ => { if let Some(err) = response.error { eprintln!("Failed to send to subscriber: {}", err); } } } } } ``` ### Response #### Success Response (200) - **message_id** (Option) - The ID of the published message for a specific subscriber. - **url** (Option) - The URL of the subscriber the message was sent to. - **error** (Option) - An error message if publishing failed for a specific subscriber. #### Response Example ```json [ { "message_id": "msg_sub1_xyz", "url": "https://subscriber1.example.com/handler" }, { "message_id": "msg_sub2_uvw", "url": "https://subscriber2.example.com/handler" } ] ``` ``` -------------------------------- ### Publish JSON Messages in Rust Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Shows how to publish JSON-serialized messages using the qstash-rs SDK. This includes simple publishing to a URL and publishing with advanced options like delays, retries, and callbacks. It handles both basic payloads and custom structs, with automatic Content-Type handling. Dependencies include serde for serialization and tokio for async operations. ```rust use qstash_rs::client::{Client, PublishRequestUrl, PublishOptions}; use std::collections::HashMap; use serde::Serialize; #[derive(Serialize)] struct Payload { user_id: u64, action: String, } #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); // Simple JSON publish to URL let result = client .publish_json( PublishRequestUrl::Url("https://api.example.com/webhook".parse().unwrap()), HashMap::from([("event", "user_signup"), ("email", "user@example.com")]), // Note: This example uses HashMap directly, which works for simple JSON. For complex structures, a struct like `Payload` is recommended. None, ) .await; match result { Ok(responses) => { for response in responses { if let Some(msg_id) = response.message_id { println!("Message published: {}", msg_id); } if let Some(error) = response.error { eprintln!("Error: {}", error); } } } Err(e) => eprintln!("Publish failed: {}", e), } // Publish with options (delay, retries, callback) let options = PublishOptions { headers: None, delay: Some(300), // 5 minutes delay not_before: None, deduplication_id: Some("unique-id-123".to_string()), content_based_deduplication: None, retries: Some(3), callback: Some("https://api.example.com/callback".to_string()), method: None, }; let payload = Payload { user_id: 42, action: "process_order".to_string(), }; let result = client .publish_json( PublishRequestUrl::Url("https://api.example.com/process".parse().unwrap()), payload, Some(options), ) .await .expect("Failed to publish"); println!("Published {} messages", result.len()); } ``` -------------------------------- ### Publishing JSON Messages Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Publish JSON-serialized messages to a specified URL. Supports automatic Content-Type handling and configurable delivery options. ```APIDOC ## Publishing JSON Messages ### Description Publish JSON-serialized messages with automatic Content-Type handling. ### Method POST (Implicitly used by the SDK to interact with QStash API) ### Endpoint `/publish/url` (Implicitly used by the SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **target_url** (PublishRequestUrl) - Required - The URL to send the message to. - **payload** (Serialize) - Required - The JSON payload to send. - **options** (PublishOptions) - Optional - Configuration for delivery, retries, callbacks, etc. **PublishOptions:** - **headers** (Option>) - Optional - Custom headers. - **delay** (Option) - Optional - Delay in seconds before delivery. - **not_before** (Option) - Optional - Timestamp (in seconds) before which the message should not be delivered. - **deduplication_id** (Option) - Optional - Unique ID for deduplication. - **content_based_deduplication** (Option) - Optional - Enable content-based deduplication. - **retries** (Option) - Optional - Number of retries. - **callback** (Option) - Optional - URL for delivery confirmation callback. - **method** (Option) - Optional - HTTP method for the request (e.g., POST, PUT). ### Request Example ```rust use qstash_rs::client::{Client, PublishRequestUrl, PublishOptions}; use std::collections::HashMap; use serde::Serialize; #[derive(Serialize)] struct Payload { user_id: u64, action: String, } #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); // Simple JSON publish to URL let result = client .publish_json( PublishRequestUrl::Url("https://api.example.com/webhook".parse().unwrap()), HashMap::from([("event", "user_signup"), ("email", "user@example.com")]), None, ) .await; match result { Ok(responses) => { for response in responses { if let Some(msg_id) = response.message_id { println!("Message published: {}", msg_id); } if let Some(error) = response.error { eprintln!("Error: {}", error); } } } Err(e) => eprintln!("Publish failed: {}", e), } // Publish with options (delay, retries, callback) let options = PublishOptions { headers: None, delay: Some(300), // 5 minutes delay not_before: None, deduplication_id: Some("unique-id-123".to_string()), content_based_deduplication: None, retries: Some(3), callback: Some("https://api.example.com/callback".to_string()), method: None, }; let payload = Payload { user_id: 42, action: "process_order".to_string(), }; let result = client .publish_json( PublishRequestUrl::Url("https://api.example.com/process".parse().unwrap()), payload, Some(options), ) .await .expect("Failed to publish"); println!("Published {} messages", result.len()); } ``` ### Response #### Success Response (200) - **message_id** (Option) - The ID of the published message. - **url** (Option) - The URL the message was sent to (relevant for topic publishing). - **error** (Option) - An error message if publishing failed for a specific destination. #### Response Example ```json [ { "message_id": "msg_abc123", "url": "https://api.example.com/webhook" } ] ``` ``` -------------------------------- ### Publish Generic Messages with QStash Rust Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Publish arbitrary message bodies with full control over options like headers, delay, retries, and deduplication. This function is useful for sending data to specified endpoints, supporting plain text or triggering endpoints without a body. ```rust use qstash_rs::client::{Client, PublishRequest, PublishRequestUrl}; use reqwest::{header, Method}; #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); // Publish plain text let mut headers = header::HeaderMap::new(); headers.insert( header::CONTENT_TYPE, header::HeaderValue::from_static("text/plain"), ); let result = client .publish(PublishRequest { url: PublishRequestUrl::Url("https://api.example.com/text".parse().unwrap()), body: Some("Hello, QStash!".to_string()), headers: Some(headers), delay: None, not_before: None, deduplication_id: None, content_based_deduplication: Some(true), retries: Some(5), callback: None, method: Some(Method::PUT), }) .await .expect("Failed to publish"); println!("Response: {:?}", result); // Publish without body (trigger endpoint) let result = client .publish(PublishRequest:: { url: PublishRequestUrl::Url("https://api.example.com/trigger".parse().unwrap()), body: None, headers: None, delay: Some(60), // 1 minute delay not_before: None, deduplication_id: Some("trigger-2025-10-07".to_string()), content_based_deduplication: None, retries: None, callback: None, method: Some(Method::POST), }) .await .expect("Failed to publish trigger"); } ``` -------------------------------- ### Access QStash Dead Letter Queue Messages in Rust Source: https://context7.com/drsh4dow/qstash-rs/llms.txt This snippet shows how to retrieve failed messages from the QStash dead letter queue using the qstash-rs library. It demonstrates fetching all messages and paginating through them. The output includes details like DLQ ID, message ID, URL, method, creation time, and optionally the error body and topic name. ```rust use qstash_rs::client::{Client, dead_letter_queue::DlqRequest}; #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); // Get DLQ messages without pagination let dlq = client .get_dead_letter_queue(None) .await .expect("Failed to get DLQ"); println!("Failed messages in DLQ: {}", dlq.messages.len()); for msg in &dlq.messages { println!("DLQ ID: {}", msg.dlq_id); println!("Message ID: {}", msg.message_id); println!("URL: {}", msg.url); println!("Method: {}", msg.method); println!("Created at: {}", msg.created_at); if let Some(error_body) = &msg.body { println!("Body: {}", error_body); } if let Some(topic) = &msg.topic_name { println!("Topic: {}", topic); } println!("---"); } // Paginate through DLQ let result = client .get_dead_letter_queue(Some(DlqRequest { cursor: Some(1000), })) .await .expect("Failed to get DLQ"); println!("Next page: {} messages", result.messages.len()); } ``` -------------------------------- ### Retrieve Message Details with QStash Rust Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Fetch detailed information about a specific message using its unique message ID. This function returns message details such as URL, method, creation timestamp, topic, body, headers, and retry information. ```rust use qstash_rs::client::Client; #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); let message = client .get_message("msg_abc123xyz") .await .expect("Failed to get message"); println!("Message ID: {}", message.message_id); println!("URL: {}", message.url); println!("Method: {:?}", message.method); println!("Created at: {}", message.created_at); if let Some(topic) = message.topic_name { println!("Topic: {}", topic); } if let Some(body) = message.body { println!("Body: {}", body); } if let Some(headers) = message.header { println!("Headers: {:?}", headers); } if let Some(max_retries) = message.max_retries { println!("Max retries: {}", max_retries); } } ``` -------------------------------- ### Retrieve Events and Logs with QStash Rust Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Query event logs for monitoring message delivery status. This function supports retrieving recent events without pagination or paginating through logs using a cursor. It provides details on message state, time, URL, errors, and next delivery attempts. ```rust use qstash_rs::client::{Client, events::{EventRequest, State}}; #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); // Get recent events without pagination let events = client .get_events(None) .await .expect("Failed to get events"); println!("Retrieved {} events", events.events.len()); for event in &events.events { println!("Message ID: {}", event.message_id); println!("State: {:?}", event.state); println!("Time: {}", event.time); if let Some(url) = &event.url { println!("URL: {}", url); } if let Some(error) = &event.error { eprintln!("Error: {}", error); } if let Some(next_delivery) = event.next_delivery_time { println!("Next delivery: {}", next_delivery); } println!("---"); } // Paginate through events using cursor let mut cursor = events.cursor; while let Some(c) = cursor { let next_events = client .get_events(Some(EventRequest { cursor: Some(c.parse().unwrap()), })) .await .expect("Failed to get events"); println!("Retrieved {} more events", next_events.events.len()); cursor = next_events.cursor; } } ``` -------------------------------- ### Cancel Messages with QStash Rust Source: https://context7.com/drsh4dow/qstash-rs/llms.txt Cancel scheduled or pending messages before they are delivered. This is useful for preventing unintended message processing or correcting errors in message scheduling. It requires the message ID of the message to be canceled. ```rust use qstash_rs::client::Client; #[tokio::main] async fn main() { let client = Client::new("qstash_token", None, None).unwrap(); // Cancel a message by ID match client.cancel_message("msg_abc123xyz").await { Ok(_) => println!("Message canceled successfully"), Err(e) => eprintln!("Failed to cancel message: {}", e), } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.