### Create and Get Stream Information Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstreamcontext.md Examples of creating a new stream with configuration and retrieving its information. Note that stream creation is typically done via extension methods. ```swift // Create a stream (use extension methods) let stream = try await js.createStream(config: streamConfig) // Get stream info let streamInfo = try await stream.info() ``` -------------------------------- ### Complete JetStream Swift Example Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-stream.md A comprehensive example showing how to connect to NATS, interact with JetStream streams, retrieve messages, and manage consumers. ```swift import Nats import JetStream // Connect and get stream let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() try await nats.connect() let js = JetStreamContext(client: nats) let stream = try await js.getStream(name: "orders") // Get stream info let info = try await stream.info() print("Stream '\(info.config.name)' has \(info.state.messages) messages") // Retrieve a message if let msg = try await stream.getMessage(firstForSubject: "order.created") { let order = String(data: msg.message.payload ?? Data(), encoding: .utf8) ?? "" print("Order: \(order)") } // Create a consumer var consumerConfig = ConsumerConfig() consumerConfig.filterSubject = "order.*" let consumer = try await stream.createConsumer(config: consumerConfig) // List all consumers let consumers = try await stream.listConsumers() print("Stream has \(consumers.count) consumers") try await nats.close() ``` -------------------------------- ### Install NATS Server Source: https://github.com/nats-io/nats.swift/blob/main/CLAUDE.md Installs the nats-server binary, which is required for running integration tests. ```bash curl --fail https://binaries.nats.dev/nats-io/nats-server/v2@latest | PREFIX='/usr/local/bin' sh ``` -------------------------------- ### NatsSubscription Immediate Unsubscribe Example Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natssubscription.md Demonstrates how to create a subscription and immediately unsubscribe from it. ```swift let sub = try await nats.subscribe(subject: "events.>") // Option 1: Unsubscribe immediately try await sub.unsubscribe() ``` -------------------------------- ### Create and Get Consumer Information Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstreamcontext.md Examples of creating a consumer on a stream and retrieving its information. ```swift // Create consumer on stream let consumer = try await stream.createConsumer(config: consumerConfig) // Get consumer info let consumerInfo = try await consumer.info() ``` -------------------------------- ### List Streams Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstreamcontext.md Example of how to list all available streams within JetStream. ```swift // List streams let streams = try await js.listStreams() ``` -------------------------------- ### NATS Client Event Handling Examples Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclient.md Examples demonstrating how to register handlers for connected, disconnected, and error events using the NATS Swift client. ```swift nats.on(.connected) { print("Connected to NATS") } nats.on(.disconnected) { print("Disconnected from NATS") } nats.on(.error) { print("NATS error: \(event.error ?? "")") } ``` -------------------------------- ### NATS Swift Client Quick Start Source: https://github.com/nats-io/nats.swift/blob/main/README.md This snippet demonstrates the basic workflow of connecting, subscribing, publishing, and receiving messages with the NATS Swift client. ```swift import Nats // create the client let nats = NatsClientOptions().url(URL(string: "nats://localhost:4222")!).build() // connect to the server try await nats.connect() // subscribe to a subject let subscription = try await nats.subscribe(subject: "events.>") // publish a message try await nats.publish("my event".data(using: .utf8)!, subject: "events.example") // receive published messages for await msg in subscriptions { print( "Received: \(String(data:msg.payload!, encoding: .utf8)!)") } ``` -------------------------------- ### Complete NATS Client Example in Swift Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclient.md Demonstrates connecting to a NATS server, publishing a message, subscribing to a subject, receiving messages, and closing the connection. Ensure the NATS server is running and accessible. ```swift import Nats let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .usernameAndPassword("admin", "password") .pingInterval(30) .reconnectWait(2) .build() nats.on(.connected) { event in print("Connected to NATS") } try await nats.connect() // Publish a message let data = "Hello NATS".data(using: .utf8)! try await nats.publish(data, subject: "greeting") // Subscribe and receive messages let sub = try await nats.subscribe(subject: "greeting") for try await msg in sub { print("Received: \(String(data: msg.payload ?? Data(), encoding: .utf8) ?? "")") } try await nats.close() ``` -------------------------------- ### Complete JetStream Example in Swift Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstreamcontext.md Demonstrates connecting to NATS, creating a JetStream context, publishing a message, and waiting for acknowledgment. Includes error handling for timeouts. ```swift import Nats import JetStream // Connect to NATS let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() try await nats.connect() // Create JetStream context let js = JetStreamContext(client: nats, timeout: 10.0) // Publish a message do { let ackFuture = try await js.publish( "events.order.created", message: "Order #12345 created".data(using: .utf8)! ) // Wait for acknowledgment let ack = try await ackFuture.wait() print("Message published with sequence: \(ack.sequence)") } catch JetStreamError.RequestError.timeout { print("Acknowledgment timed out") } // Close connection try await nats.close() ``` -------------------------------- ### Initialize Empty NatsHeaderMap Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Create an empty NatsHeaderMap to start collecting headers. ```swift var headers = NatsHeaderMap() ``` -------------------------------- ### Adding Authentication Headers Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md This example shows how to include authentication credentials, such as Authorization tokens or API keys, in NATS message headers. ```swift var headers = NatsHeaderMap() headers.insert(try! NatsHeaderName("Authorization"), NatsHeaderValue("Bearer token123")) headers.insert(try! NatsHeaderName("X-API-Key"), NatsHeaderValue("api-key-xyz")) try await nats.publish(payload, subject: "secure.operation", headers: headers) ``` -------------------------------- ### Consume Messages Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstreamcontext.md Example demonstrating how to consume messages from a stream using a consumer. Iterates through received messages. ```swift // Consume messages let messages = try await consumer.consume() for try await msg in messages { print("Got message: \(msg)") } ``` -------------------------------- ### NATS Event Listener Removal Example Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclient.md Example showing how to register a listener and then remove it using the returned listener ID. ```swift let listenerId = nats.on(.connected) { print("Connected") } nats.off(listenerId) ``` -------------------------------- ### NatsSubscription Auto-Unsubscribe Example Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natssubscription.md Demonstrates how to set up a subscription to automatically unsubscribe after receiving a specific number of messages. ```swift let sub = try await nats.subscribe(subject: "user.updates") // Will receive exactly 5 messages then auto-unsubscribe try await sub.unsubscribe(after: 5) var count = 0 for try await msg in sub { count += 1 print("Message \(count): \(msg.subject)") // Loop exits after 5 messages } ``` -------------------------------- ### NATS Header Format Example Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Illustrates the structure of NATS headers, including the protocol line, status/description, header pairs, and the end-of-headers marker. ```text NATS/1.0 Header-Name: value Another-Header: another value ``` -------------------------------- ### NatsMessage Usage Example Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/types.md Demonstrates how to subscribe to a subject and process incoming NATS messages, accessing their properties like subject, length, and payload. ```swift let subscription = try await nats.subscribe(subject: "events.>") for try await msg in subscription { print("Subject: \(msg.subject)") print("Length: \(msg.length)") if let payload = msg.payload { let text = String(data: payload, encoding: .utf8) print("Content: \(text ?? "")") } } ``` -------------------------------- ### Handle Connection Loss During Subscription in Swift Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natssubscription.md Provides an example of how to gracefully handle `NatsError.ClientError.connectionClosed` exceptions that may occur while processing messages from a subscription. Ensure your application logic can reconnect or recover. ```swift let sub = try await nats.subscribe(subject: "events.>") do { for try await msg in sub { // Process message } } catch NatsError.ClientError.connectionClosed { print("Connection lost during subscription") } ``` -------------------------------- ### build() Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Constructs and returns a configured `NatsClient` instance, ready to establish a connection. ```APIDOC ## build() ### Description Constructs the configured `NatsClient` instance. ### Method `build() -> NatsClient` ### Returns A configured `NatsClient` ready to connect ### Request Example ```swift let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .usernameAndPassword("user", "pass") .pingInterval(30) .build() try await nats.connect() ``` ``` -------------------------------- ### Configure Username and Password Authentication Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Set up authentication using a username and password. Provide both strings to the method. ```swift NatsClientOptions() .usernameAndPassword("admin", "secretpassword") ``` -------------------------------- ### Configure Authentication with Credentials File Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Specify the path to a credentials file containing JWT and NKey for authentication. ```swift NatsClientOptions() .credentialsFile(URL(fileURLWithPath: "/etc/nats/user.creds")) ``` -------------------------------- ### NatsHeaderMap Methods Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Provides methods to insert, append, get, and retrieve header values from a NatsHeaderMap. ```APIDOC ### Methods #### insert(_:_:) Sets a header value, replacing any existing value. ```swift public mutating func insert(_ name: NatsHeaderName, _ value: NatsHeaderValue) ``` **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `name` | `NatsHeaderName` | Yes | Header name | | `value` | `NatsHeaderValue` | Yes | Header value | **Example:** ```swift var headers = NatsHeaderMap() headers.insert(try! NatsHeaderName("X-Request-ID"), NatsHeaderValue("abc123")) ``` #### append(_:_:) Appends a header value. If the header already exists, adds another value (headers can have multiple values). ```swift public mutating func append(_ name: NatsHeaderName, _ value: NatsHeaderValue) ``` **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `name` | `NatsHeaderName` | Yes | Header name | | `value` | `NatsHeaderValue` | Yes | Header value to append | **Example:** ```swift var headers = NatsHeaderMap() headers.append(try! NatsHeaderName("X-Tag"), NatsHeaderValue("important")) headers.append(try! NatsHeaderName("X-Tag"), NatsHeaderValue("urgent")) // Header now has two values ``` #### get(_:) Retrieves the first value for a header name. ```swift public func get(_ name: NatsHeaderName) -> NatsHeaderValue? ``` **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `name` | `NatsHeaderName` | Yes | Header name to retrieve | **Returns:** First header value, or nil if not found **Example:** ```swift if let userID = headers.get(try! NatsHeaderName("X-User-ID")) { print("User: \(userID)") } ``` #### getAll(_:) Retrieves all values for a header name. ```swift public func getAll(_ name: NatsHeaderName) -> [NatsHeaderValue] ``` **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `name` | `NatsHeaderName` | Yes | Header name to retrieve | **Returns:** Array of all values (empty if header not found) **Example:** ```swift let tags = headers.getAll(try! NatsHeaderName("X-Tag")) for tag in tags { print("Tag: \(tag)") } ``` ``` -------------------------------- ### StatusCode Initialization and Usage Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/types.md Shows how to create StatusCode instances from UInt16 or String values, and how to compare them with predefined constants. ```swift // Create from UInt16 if let status = StatusCode(503) { print("No responders: \(status.value)") } // Create from string if let status = StatusCode("200") { print("OK") } // Use predefined if status == StatusCode.timeout { print("Request timed out") } ``` -------------------------------- ### Auth Static Constructors Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/types.md Convenience methods for creating `Auth` configurations. Use these to easily set up authentication using different methods like username/password, tokens, or files. ```swift // Username/password Auth(user: "username", password: "password") ``` ```swift // Token Auth(token: "token_string") ``` ```swift // Credentials file Auth.fromCredentials(URL(fileURLWithPath: "/path/to/creds")) ``` ```swift // NKey from file Auth.fromNkey(URL(fileURLWithPath: "/path/to/key")) ``` ```swift // NKey inline Auth.fromNkey("SUAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") ``` -------------------------------- ### Build and Test NATS.swift Project Source: https://github.com/nats-io/nats.swift/blob/main/CLAUDE.md Commands for building, testing, and cleaning the NATS.swift project. Ensure nats-server is on your PATH for integration tests. ```bash swift build ``` ```bash swift test ``` ```bash swift test --filter / ``` ```bash # Example: swift test --filter NatsTests.CoreNatsTests/testConnect ``` ```bash swift test --filter NatsTests ``` ```bash swift test --filter JetStreamTests ``` ```bash swift build -c release ``` ```bash swift package clean ``` -------------------------------- ### Consumer Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/API-INDEX.md Represents a JetStream consumer. Used to get consumer information, consume messages, and fetch messages. ```APIDOC ## Consumer ### Description Represents a JetStream consumer. Used to get consumer information, consume messages, and fetch messages. ### Creation Via `Stream.createConsumer()` or `.getConsumer()` ### Methods - `info()` → `ConsumerInfo` — Get consumer info - `consume()` → `AsyncSequence` — Consume messages (push) - `pull(batch:timeout:)` → `AsyncSequence` — Pull messages - `fetch(batch:timeout:)` → `AsyncSequence` — Fetch messages ### Properties - `info: ConsumerInfo` — Consumer info (may be stale) ``` -------------------------------- ### Import Test Utilities Module Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/README.md Import the NatsServer test utilities for testing purposes. ```swift // Test utilities import NatsServer ``` -------------------------------- ### Stream Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/API-INDEX.md Represents a JetStream stream. Used to get stream information, manage messages, and create/manage consumers. ```APIDOC ## Stream ### Description Represents a JetStream stream. Used to get stream information, manage messages, and create/manage consumers. ### Creation Via `JetStreamContext.createStream()` or `.getStream()` ### Methods - `info()` → `StreamInfo` — Get stream info - `getMessage(sequence:subject:)` → `StreamMessage?` — Get message by sequence - `getMessage(firstForSubject:)` → `StreamMessage?` — Get first message on subject - `getMessage(lastForSubject:)` → `StreamMessage?` — Get last message on subject - `getMessageDirect(sequence:subject:)` → `StreamMessage?` — Direct get (replica) - `getMessageDirect(firstForSubject:)` → `StreamMessage?` — Direct get first - `getMessageDirect(lastForSubject:)` → `StreamMessage?` — Direct get last - `deleteMessage(sequence:)` — Delete message - `purge()` — Purge all messages - `purge(subject:)` — Purge subject messages - `createConsumer(config:)` → `Consumer` — Create consumer - `getConsumer(name:)` → `Consumer?` — Get consumer - `listConsumers()` → `[Consumer]` — List consumers ### Properties - `info: StreamInfo` — Stream info (may be stale) ``` -------------------------------- ### Connect, Publish, and Receive with Async/Await Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/README.md Demonstrates basic NATS operations using Swift's async/await syntax. Ensure the client is connected before publishing or receiving messages. ```swift try await nats.connect() try await nats.publish(data, subject: "test") let msg = try await subscription.makeAsyncIterator().next() ``` -------------------------------- ### Get Last Message for Subject Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-stream.md Retrieves the most recent message published to a specific subject within the stream. ```swift if let msg = try await stream.getMessage(lastForSubject: "status.updates") { print("Last status: \(String(data: msg.message.payload ?? Data(), encoding: .utf8) ?? "") } ``` -------------------------------- ### Get First Message for Subject Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-stream.md Retrieves the earliest message published to a specific subject within the stream. ```swift if let msg = try await stream.getMessage(firstForSubject: "orders.123") { print("First message on orders.123") } ``` -------------------------------- ### JetStream Server Error Codes Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-errors.md Examples of common JetStream server error codes for streams, consumers, and resource limits. ```swift // Stream errors ErrorCode.streamNotFound // 10059 ErrorCode.streamNameExist // 10058 ErrorCode.maximumStreamsLimit // 10027 // Consumer errors ErrorCode.consumerNotFound // 10014 ErrorCode.maximumConsumersLimit // 10026 // Resource errors ErrorCode.accountResourcesExceeded // 10002 ErrorCode.storageResourcesExceeded // 10047 ErrorCode.memoryResourcesExceeded // 10028 ``` -------------------------------- ### Publish a Basic Message Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/MANIFEST.txt Sends a simple message to a NATS subject. No special setup is required beyond establishing a connection. ```swift try await nats.publish("updates", data: "Hello NATS!".data(using: .utf8)!) ``` -------------------------------- ### Build NatsClient Instance Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Constructs and returns a fully configured `NatsClient` instance based on the applied options, ready to establish a connection. ```swift let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .usernameAndPassword("user", "pass") .pingInterval(30) .build() try await nats.connect() ``` -------------------------------- ### Implement Request/Reply Pattern Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natssubscription.md Demonstrates the request/reply pattern by publishing a message with a reply subject and subscribing to that subject to receive the response. This is useful for synchronous communication where a response is expected. ```swift let replySubject = nats.newInbox() let replySub = try await nats.subscribe(subject: replySubject) // Send request with reply subject try await nats.publish( "get_config".data(using: .utf8)!, subject: "config.request", reply: replySubject ) // Wait for response if let response = try await replySub.makeAsyncIterator().next() { if let payload = response.payload { print("Config: \(String(data: payload, encoding: .utf8) ?? "")") } } ``` -------------------------------- ### NatsClient Initialization Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclient.md Configure and build a NatsClient instance using NatsClientOptions. This allows setting connection URLs and other options before establishing a connection. ```APIDOC ## NatsClient Initialization Use `NatsClientOptions` to configure and build a client: ```swift let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() ``` ``` -------------------------------- ### Handle DirectGetError.invalidResponse Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-errors.md Catch and handle `invalidResponse` errors when the direct get response is malformed. This can occur due to protocol errors or data corruption. ```swift do { let msg = try await stream.getMessageDirect(sequence: 100) } catch JetStreamError.DirectGetError.invalidResponse(let reason) { print("Invalid response: \(reason)") } ``` -------------------------------- ### Get All Header Values from NatsHeaderMap Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Retrieve all values associated with a given header name as an array. Returns an empty array if the header is not found. ```swift let tags = headers.getAll(try! NatsHeaderName("X-Tag")) for tag in tags { print("Tag: \(tag)") } ``` -------------------------------- ### Publishing Messages with Headers Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Create a NatsClient, establish a connection, construct a NatsHeaderMap with key-value pairs, and publish a message with the specified headers. ```swift import Nats let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() try await nats.connect() // Create headers var headers = NatsHeaderMap() headers.insert(try! NatsHeaderName("X-User-ID"), NatsHeaderValue("user123")) headers.append(try! NatsHeaderName("X-Priority"), NatsHeaderValue("high")) headers.append(try! NatsHeaderName("X-Trace-ID"), NatsHeaderValue("trace-abc-123")) // Publish with headers let payload = "Important message".data(using: .utf8)! try await nats.publish(payload, subject: "events.important", headers: headers) ``` -------------------------------- ### Get Single Header Value from NatsHeaderMap Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Retrieve the first value associated with a given header name. Returns nil if the header is not found. ```swift if let userID = headers.get(try! NatsHeaderName("X-User-ID")) { print("User: \(userID)") } ``` -------------------------------- ### Production NATS Client Configuration with Clustering Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/configuration.md Set up a connection to a clustered NATS environment with multiple server URLs and authentication. Use secure passwords for production. ```swift let nats = NatsClientOptions() .urls([ URL(string: "nats://nats1.prod:4222")!, URL(string: "nats://nats2.prod:4222")!, URL(string: "nats://nats3.prod:4222")! ]) .usernameAndPassword("prod_user", "secure_password") .pingInterval(30) .reconnectWait(0.5) .maxReconnects(100) .build() ``` -------------------------------- ### Configure Multiple Server URLs for Failover Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Provide an array of server URLs for failover or clustering. The client will attempt to connect to these servers in the order provided. ```swift NatsClientOptions() .urls([ URL(string: "nats://nats1.example.com:4222")!, URL(string: "nats://nats2.example.com:4222")!, URL(string: "nats://nats3.example.com:4222")! ]) ``` -------------------------------- ### Get Stream Information Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-stream.md Retrieves the current state of the stream, including configuration and message counts. This also updates the local `info` property. ```swift let streamInfo = try await stream.info() print("Stream: \(streamInfo.config.name)") print("Messages: \(streamInfo.state.messages)") print("Bytes: \(streamInfo.state.bytes)") ``` -------------------------------- ### credentialsFile(_:) Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Sets the path to a credentials file containing JWT and NKey for authentication. ```APIDOC ## credentialsFile(_:) ### Description Sets path to a credentials file containing JWT and NKey. ### Method N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift NatsClientOptions() .credentialsFile(URL(fileURLWithPath: "/etc/nats/user.creds")) ``` ### Response N/A (SDK Method) ERROR HANDLING: N/A ``` -------------------------------- ### Adding and Retrieving Multi-Value Headers Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Demonstrates how to append multiple values for the same header key (e.g., X-Tag) and how to retrieve all associated values later. ```swift var headers = NatsHeaderMap() // Add multiple tags headers.append(try! NatsHeaderName("X-Tag"), NatsHeaderValue("production")) headers.append(try! NatsHeaderName("X-Tag"), NatsHeaderValue("high-priority")) headers.append(try! NatsHeaderName("X-Tag"), NatsHeaderValue("alert-enabled")) // Later, retrieve all tags let tags = headers.getAll(try! NatsHeaderName("X-Tag")) print("All tags: \(tags.count)") // Output: All tags: 3 ``` -------------------------------- ### Configure TLS/mTLS Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/MANIFEST.txt Sets up secure TLS or mTLS connections using provided certificates and keys. Requires careful configuration of paths and passwords. ```swift let options = NatsClientOptions.builder() .withServers([URL(string: "tls://localhost:4443")!]) .withTlsConfiguration({ var config = TLSConfiguration.makeClientConfiguration() // Load certificates and keys here return config }()) .build() let nats = try NatsClient(options: options) nats.connect() ``` -------------------------------- ### Add NATS Dependency to Package.swift Source: https://github.com/nats-io/nats.swift/blob/main/README.md Include the NATS Swift client as a dependency in your project's Package.swift file. This example shows how to add it for Swift 5.7. ```swift // swift-tools-version:5.7 import PackageDescription let package = Package( name: "YourApp", products: [ .executable(name: "YourApp", targets: ["YourApp"]), ], dependencies: [ .package(name: "Nats", url: "https://github.com/nats-io/nats.swift.git", from: "0.1") ], targets: [ .target(name: "YourApp", dependencies: ["Nats"]), ] ) ``` -------------------------------- ### connect() Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclient.md Establishes a connection to a NATS server. This method can be configured to retry on failure or to throw immediately if the connection cannot be established. ```APIDOC ## connect() Establishes a connection to a NATS server using configuration from `NatsClientOptions`. ```swift public func connect() async throws ``` **Behavior:** - If `retryOnfailedConnect()` was set in options, returns immediately and handles reconnection in background - Otherwise, waits for connection to be established before returning - Throws immediately if connection is already established or in invalid state **Throws:** - `NatsError.ConnectError.invalidConfig(_:)` — Configuration is invalid - `NatsError.ConnectError.tlsFailure(_:)` — TLS handshake failed - `NatsError.ConnectError.timeout` — TCP connection timeout - `NatsError.ConnectError.dns(_:)` — DNS lookup failed - `NatsError.ConnectError.io(_:)` — Other I/O errors - `NatsError.ServerError.authorizationViolation` — Authentication/authorization failed - `NatsError.ServerError.other(_:)` — Server rejected connection **Example:** ```swift let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() do { try await nats.connect() print("Connected to NATS") } catch { print("Connection failed: \(error)") } ``` ``` -------------------------------- ### Handle DirectGetError.errorResponse Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-errors.md Catch and handle `errorResponse` errors when the direct get returns an error status. This includes cases like message not found or bad requests. ```swift do { let msg = try await stream.getMessageDirect(sequence: 999) } catch JetStreamError.DirectGetError.errorResponse(let code, let desc) { print("Error: \(code.value) - \(desc ?? "unknown")") } ``` -------------------------------- ### Implement Subscription Iterator Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/types.md Provides an asynchronous iterator for NATS subscriptions, enabling the use of `for try await` loops. This class is automatically created when you start iterating over a subscription. ```swift public final class SubscriptionIterator: AsyncIteratorProtocol, Sendable { public func next() async throws -> NatsMessage? } ``` -------------------------------- ### Get Message Directly by Sequence Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-stream.md Retrieves a message directly from any available replica, bypassing the leader. This requires the stream to be configured with `allowDirect: true` and offers read-after-write consistency. ```swift if let msg = try await stream.getMessageDirect(sequence: 50) { print("Got message directly") } ``` -------------------------------- ### Minimal NATS Client Configuration Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/configuration.md Use this for a basic connection to a single NATS server. Ensure the URL is correct. ```swift let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() ``` -------------------------------- ### Get First Message Directly for Subject Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-stream.md Retrieves the first message for a given subject directly from any replica, ensuring read-after-write consistency. Requires the stream to have direct access enabled. ```swift if let msg = try await stream.getMessageDirect(firstForSubject: "data.sync") { print("Got latest message") } ``` -------------------------------- ### nkeyFile(_:) Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Sets the path to an NKey seed file for authentication. This is mutually exclusive with nkey(). ```APIDOC ## nkeyFile(_:) ### Description Sets path to an NKey seed file. ### Method N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift NatsClientOptions() .nkeyFile(URL(fileURLWithPath: "/home/user/.nkeys/seed")) ``` ### Response N/A (SDK Method) ERROR HANDLING: N/A ``` -------------------------------- ### Publishing with Headers Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Demonstrates how to create and attach NATS headers to a published message. ```APIDOC ## Publishing with Headers ### Description This section shows how to create a `NatsHeaderMap` and populate it with key-value pairs before publishing a message. ### Method `nats.publish(payload:subject:headers:)` ### Parameters - `payload` (Data): The message payload. - `subject` (String): The subject to publish the message to. - `headers` (NatsHeaderMap): A map containing the headers to be sent with the message. ### Request Example ```swift import Nats let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() try await nats.connect() // Create headers var headers = NatsHeaderMap() headers.insert(try! NatsHeaderName("X-User-ID"), NatsHeaderValue("user123")) headers.append(try! NatsHeaderName("X-Priority"), NatsHeaderValue("high")) headers.append(try! NatsHeaderName("X-Trace-ID"), NatsHeaderValue("trace-abc-123")) // Publish with headers let payload = "Important message".data(using: .utf8)! try await nats.publish(payload, subject: "events.important", headers: headers) ``` ``` -------------------------------- ### Get Message by Sequence Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstream-stream.md Retrieves a specific message from the stream using its sequence number. An optional subject can be provided to filter messages with a sequence greater than or equal to the specified number. ```swift // Get message at sequence 42 if let msg = try await stream.getMessage(sequence: 42) { print("Sequence: \(msg.metadata.sequence)") print("Payload: \(String(data: msg.message.payload ?? Data(), encoding: .utf8) ?? "") } // Get first message with sequence >= 100 on subject "orders" if let msg = try await stream.getMessage(sequence: 100, subject: "orders") { print("Got message: \(msg.metadata.sequence)") } ``` -------------------------------- ### NatsClientOptions Builder Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/MANIFEST.txt Documentation for configuring NatsClient instances using the NatsClientOptions builder. ```APIDOC ## NatsClientOptions ### Description NatsClientOptions provides a fluent API for configuring various aspects of a NATS client connection, including authentication, reconnection behavior, and TLS settings. ### Builder Methods - **url(_:)** Sets the NATS server URL. - **reconnect(_:)** Enables or disables automatic reconnection. - **maxReconnects(_:)** Sets the maximum number of reconnection attempts. - **pingInterval(_:)** Configures the interval for sending PING frames. - **tlsConfig(_:)** Configures TLS/mTLS settings for the connection. ### Examples ```swift let options = NatsClientOptions() .url("nats://secure.example.com:4443") .reconnect(true) .maxReconnects(5) .tlsConfig(TLSConfiguration.client(serverName: "secure.example.com")) NatsClient.connect(options: options) .then { client in // Use the connected client } .catch { error in print("Failed to connect with options: \(error)") } ``` ``` -------------------------------- ### Configure Client Certificate and Key for mTLS Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Sets the client certificate and private key files for mutual TLS (mTLS) authentication. Both paths must point to PEM-encoded files. ```swift NatsClientOptions() .clientCertificate( URL(fileURLWithPath: "/path/to/client.crt"), URL(fileURLWithPath: "/path/to/client.key") ) ``` -------------------------------- ### Accessing Message Headers in Swift Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natssubscription.md Demonstrates how to retrieve header values from received NATS messages using the `headers` property and `get`/`getAll` methods. Ensure NATS headers are properly formatted. ```swift let subscription = try await nats.subscribe(subject: "api.requests") for try await message in subscription { if let headers = message.headers { // Get single header value if let userID = headers.get(try! NatsHeaderName("X-User-ID")) { print("User ID: \(userID)") } // Get all values for a header (supports multiple values) let values = headers.getAll(try! NatsHeaderName("X-Tag")) for value in values { print("Tag: \(value)") } } } ``` -------------------------------- ### Configure NKey Authentication with Seed File Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Set the path to an NKey seed file for NKey-based authentication. This option is mutually exclusive with `nkey()`. ```swift NatsClientOptions() .nkeyFile(URL(fileURLWithPath: "/home/user/.nkeys/seed")) ``` -------------------------------- ### Basic Connection and Publish Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/README.md Connect to a NATS server, publish a message, and close the connection. Ensure a NATS server is running at the specified URL. ```swift import Nats let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() try await nats.connect() try await nats.publish("Hello NATS".data(using: .utf8)!, subject: "greeting") try await nats.close() ``` -------------------------------- ### Create Queue Group Workers Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natssubscription.md Starts multiple worker tasks that subscribe to a subject using a queue group. This ensures that messages are distributed among workers, with only one worker processing each message. Requires a running NATS server. ```swift func startWorker(id: Int) { Task { let sub = try await nats.subscribe( subject: "tasks.process", queue: "workers" ) for try await task in sub { print("Worker \(id) processing: \(task.subject)") // Process the task } } } // Start 5 workers for i in 1...5 { startWorker(id: i) } // Publish tasks for i in 1...100 { try await nats.publish( "Task \(i)".data(using: .utf8)!, subject: "tasks.process" ) } ``` -------------------------------- ### JetStreamContext Entry Point Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/MANIFEST.txt Information on accessing JetStream functionality through the JetStreamContext. ```APIDOC ## JetStreamContext ### Description The JetStreamContext provides the entry point for interacting with NATS JetStream, enabling stream and consumer management, as well as message publishing and consumption within a JetStream environment. ### Methods - **publish(subject: String, payload: Data, stream: String? = nil, expectedLastSequence: UInt64? = nil) -> Promise** Publishes a message to a JetStream stream. - **streamNamed(_ name: String) -> Stream** Retrieves a reference to a specific stream by name. - **consumer(stream: String, consumer: String) -> Consumer** Retrieves a reference to a specific consumer. ### Examples ```swift let js = try await client.jetStreamContext() js.publish(subject: "orders", payload: "New order data".data(using: .utf8)!, stream: "order-stream") .then { ack in print("Message published to stream: \(ack.stream)") } .catch { error in print("Failed to publish to JetStream: \(error)") } ``` ``` -------------------------------- ### JetStreamContext Initialization with Default Settings Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstreamcontext.md Initializes a JetStreamContext using a provided NatsClient with default API prefix and timeout values. ```APIDOC ## init(client:) ### Description Creates a JetStreamContext with default settings. ### Parameters - **client** (`NatsClient`) - Required - Connected NATS client ### Default API Prefix `$JS.API` ### Default Timeout 5 seconds ### Example ```swift let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() try await nats.connect() let js = JetStreamContext(client: nats) ``` ``` -------------------------------- ### Using Standard Headers Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Demonstrates how to retrieve values for standard NATS headers from a received message's headers object using predefined header name constants. ```swift // Use standard JetStream headers if let stream = headers.get(.natsStream) { print("Stream: \(stream)") } if let seq = headers.get(.natsSequence) { print("Sequence: \(seq)") } ``` -------------------------------- ### Configuration Methods Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/API-INDEX.md Methods for configuring NATS client options, including server URLs, authentication, and connection settings. ```APIDOC ## Configuration ### `url(_:)` **Purpose:** Set a single server URL for the NATS client. ### `urls(_:)` **Purpose:** Set multiple server URLs for the NATS client. ### `usernameAndPassword(_:_:)` **Purpose:** Configure basic authentication with username and password. ### `token(_:)` **Purpose:** Configure authentication using a bearer token. ### `credentialsFile(_:)` **Purpose:** Configure authentication using a NATS credentials file. ### `nkey(_:)` **Purpose:** Configure NKEY authentication using a public NKEY. ### `nkeyFile(_:)` **Purpose:** Configure NKEY authentication using a NKEY file. ### `requireTls()` **Purpose:** Require TLS for the connection. ### `withTlsFirst()` **Purpose:** Initiate the connection with TLS. ### `rootCertificates(_:)` **Purpose:** Provide custom root certificates for TLS verification. ### `clientCertificate(_:_:)` **Purpose:** Configure client certificate authentication for TLS. ### `pingInterval(_:)` **Purpose:** Set the interval for sending PING frames to keep the connection alive. ### `reconnectWait(_:)` **Purpose:** Set the wait time between reconnect attempts. ### `maxReconnects(_:)` **Purpose:** Set the maximum number of reconnect attempts. ### `inboxPrefix(_:)` **Purpose:** Set a custom prefix for generated inbox subjects. ### `retainServersOrder()` **Purpose:** Retain the order of servers as provided in the configuration. ### `retryOnfailedConnect()` **Purpose:** Enable background retries on failed connection attempts. ### `setTimeout(_:)` **Purpose:** Set the timeout for JetStream requests. ``` -------------------------------- ### url(_:) Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Sets a single server URL to connect to. Supports nats://, tls://, ws://, or wss:// schemes with default port assignments. ```APIDOC ## url(_:) ### Description Sets a single server URL to connect to. ### Method N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) ``` ### Response N/A (SDK Method) ERROR HANDLING: N/A ``` -------------------------------- ### Configure NATS Client Options Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/MANIFEST.txt Builds a configuration object for the NatsClient. Supports various options like URLs, credentials, and TLS settings. ```swift let options = NatsClientOptions.builder() .withServers([URL(string: "nats://localhost:4222")!]) .withUsername("user") .withPassword("password") .build() let nats = try NatsClient(options: options) nats.connect() ``` -------------------------------- ### Configure TLS for NATS Client Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclient.md Set up TLS for secure connections, including specifying root certificates and client certificates with their private keys. ```swift let nats = NatsClientOptions() .url(URL(string: "tls://localhost:4222")!) .requireTls() .rootCertificates(URL(fileURLWithPath: "/path/to/ca.pem")!) .clientCertificate( URL(fileURLWithPath: "/path/to/client.pem"), URL(fileURLWithPath: "/path/to/key.pem") ) .build() ``` -------------------------------- ### Initialize JetStreamContext with Default Settings Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstreamcontext.md Creates a JetStreamContext using a connected NatsClient with default API prefix and timeout. Ensure the NatsClient is connected before initializing. ```swift let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .build() try await nats.connect() let js = JetStreamContext(client: nats) ``` -------------------------------- ### nkey(_:) Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Sets an inline NKey string for authentication. This option is mutually exclusive with `nkeyFile()`. ```APIDOC ## nkey(_:) ### Description Sets an inline NKey string. ### Method `nkey(_ nkey: String) -> NatsClientOptions` ### Parameters #### Path Parameters - **nkey** (String) - Required - NKey seed string ### Mutually Exclusive Cannot be used with `nkeyFile()` ### Request Example ```swift NatsClientOptions() .nkey("SUAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX") ``` ``` -------------------------------- ### JetStream Prefix Configuration in Swift Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/jetstreamcontext.md Shows how to configure the API prefix for JetStream requests, including using the default, a custom prefix, or a custom domain. ```swift // Default: $JS.API let js1 = JetStreamContext(client: nats) // Custom prefix let js2 = JetStreamContext(client: nats, prefix: "$JS.CUSTOM.API") // Custom domain let js3 = JetStreamContext(client: nats, domain: "us-west") // Results in: $JS.us-west.API ``` -------------------------------- ### Publish with Headers Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/README.md Publish a message with custom headers. Requires importing Nats and establishing a connection. ```swift var headers = NatsHeaderMap() headers.insert(try! NatsHeaderName("X-User-ID"), NatsHeaderValue("user123")) try await nats.publish(data, subject: "events", headers: headers) ``` -------------------------------- ### Request/Reply with Headers Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsheaders.md Shows how to send a request with headers and access headers in the response. ```APIDOC ## Request/Reply with Headers ### Description This section demonstrates sending a request message with custom headers and processing the headers of the reply message. ### Method `nats.request(payload:subject:headers:timeout:)` ### Parameters - `payload` (Data): The request payload. - `subject` (String): The subject to send the request to. - `headers` (NatsHeaderMap): A map containing the headers for the request. - `timeout` (Double): The timeout in seconds for the request. ### Request Example ```swift // Send request with headers var requestHeaders = NatsHeaderMap() requestHeaders.insert(try! NatsHeaderName("X-Request-ID"), NatsHeaderValue("req123")) requestHeaders.insert(try! NatsHeaderName("X-Timeout"), NatsHeaderValue("5000")) let payload = "get /users".data(using: .utf8)! let response = try await nats.request( payload, subject: "api.request", headers: requestHeaders, timeout: 5.0 ) // Check response headers if let responseHeaders = response.headers { if let status = responseHeaders.get(try! NatsHeaderName("X-Response-Status")) { print("Response status: \(status)") } } ``` ``` -------------------------------- ### Connect to NATS Server Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/MANIFEST.txt Establishes a connection to a NATS server. Ensure the server is running before attempting to connect. ```swift let nats = NatsClient() nats.connect() // ... nats.disconnect() ``` -------------------------------- ### Local Development NATS Client Configuration Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/configuration.md Configure for local development with specific ping intervals, reconnection wait times, and maximum reconnect attempts. ```swift let nats = NatsClientOptions() .url(URL(string: "nats://localhost:4222")!) .pingInterval(30) .reconnectWait(1) .maxReconnects(10) .build() ``` -------------------------------- ### Configure NATS Client Username and Password Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/configuration.md Set up basic username and password authentication for the NATS client. This method is mutually exclusive with other authentication types. ```swift NatsClientOptions() .usernameAndPassword("admin", "secretpassword") ``` ```swift NatsClientOptions() .usernameAndPassword("user@example.com", "p@ssw0rd") ``` -------------------------------- ### urls(_:) Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/natsclientoptions.md Sets a list of server URLs for failover/clustering. ```APIDOC ## urls(_:) ### Description Sets a list of server URLs for failover/clustering. ### Method N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift NatsClientOptions() .urls([ URL(string: "nats://nats1.example.com:4222")!, URL(string: "nats://nats2.example.com:4222")!, URL(string: "nats://nats3.example.com:4222")! ]) ``` ### Response N/A (SDK Method) ERROR HANDLING: N/A ``` -------------------------------- ### Enable Retry on Failed Connection Source: https://github.com/nats-io/nats.swift/blob/main/_autodocs/configuration.md Configure the client to attempt background reconnection if the initial connection fails. The `connect()` call will return immediately. ```swift NatsClientOptions() .retryOnfailedConnect() .build() // Returns immediately, reconnects in background try await nats.connect() ```