Publish/Subscribe API for PubNub Rust SDK
The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.
For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.
Publish
The publish_message()
function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publish_key
at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Publish Anytime
It's not required to be subscribed to a channel in order to publish to that channel.
Message Data
The message argument can contain any JSON serializable data, including Objects, Arrays, Integers, and Strings. data
should not contain special classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Don't JSON serialize
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead, just pass the full object as the message payload. PubNub takes care of everything for you.
Message Size
The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.
Message Too Large Error
If the message size exceeds 32KiB, you receive an appropriate error response.
For further details, check the support article.
Message Publish Rate
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably
There are some best practices to ensure messages are delivered when publishing to a channel:
- Publish to any given channel in a serial manner (not concurrently).
- Check that the return code is success (for example,
[1,"Sent","136074940..."]
) - Publish the next message only after receiving a success return code.
- If a failure code is returned (
[0,"blah","<timetoken>"]
), retry the publish. - Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
- Throttle publish bursts in accordance with your app's latency needs, for example, Publish no faster than 5 messages per second to any one channel.
Method(s)
To Publish a message you can use the following method(s) in the Rust SDK:
pubnub
.publish_message(T: Serialize)
.channel(Into<String>)
.store(Option<bool>)
.meta(Option<HashMap<String, String>>)
.replicate(bool)
.ttl(Option<u32>)
.use_post(bool)
.execute()
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
publish_message | T: Serialize | Yes | The message payload. Any type that implements the Serialize trait is allowed. | |
channel | Into<String> | Yes | The channel to send the message to. | |
store | Option<bool> | Optional | Account default | Whether to store the messages in Message Persistence or not. |
meta | Option<HashMap<String, String>> | Optional | A hash map of additional information about the message you can use for Filters. | |
replicate | bool | Optional | Whether to replicate the messages across points of presence or not. Refer to Replicated Transactions for more information. | |
ttl | Option<u32> | Optional | A per message time to live in Message Persistence. 1. If store = true , and ttl = 0 , the message is stored with no expiry time. 2. If store = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours. 3. If store = false , the ttl parameter is ignored. 4. If ttl isn't specified, then expiration of the message defaults back to the expiry value for the key. | |
use_post | bool | Optional | false | Whether to use HTTP POST to publish the message. |
execute | Yes | false | Executes the request based on the provided data. This function returns a Future and you must .await the value. |
Basic Usage
Publish a message to a channel:
Other Examples
Returns
The publish()
operation returns a PublishResult
which contains the timetoken, or a PubNub Error
which contains the error indicator and the description of the error.
// success example
PublishResult { timetoken: "16808621084073203" }
// failure example
Error: PublishError("Status code: 400, body: OtherResponse { status: 400, error: true, service: \"Access Manager\", message: \"Invalid Subscribe Key\" }")
Subscribe
The subscribe function creates an open TCP socket to PubNub and begins listening for messages and events on a specified entity or set of entities. To subscribe successfully, you must configure the appropriate subscribe_key
at initialization.
Entities are first-class citizens that provide access to their encapsulated APIs. You can subscribe using the PubNub client object or directly on a specific entity:
A newly subscribed client receives messages after the subscribe()
call completes. You can configure with_retry_policy()
to automatically attempt to reconnect and retrieve any available messages if a client gets disconnected.
Subscription scope
Subscription objects provide an interface to attach listeners for various real-time update types. Your app receives messages and events via those event listeners. Two types of subscriptions are available:
Subscription
, created from an entity with a scope of only that entity (for example, a particular channel)SubscriptionSet
, created from the PubNub client with a global scope (for example, all subscriptions created on a singlepubnub
object ). A subscription set can have one or more subscriptions.
The event listener is a single point through which your app receives all the messages, signals, and events in the entities you subscribed to. For information on adding event listeners, refer to Event listeners.
Create a subscription
An entity-level Subscription
allows you to receive messages and events for only that entity for which it was created. Using multiple entity-level Subscription
s is useful for handling various message/event types differently in each channel.
// entity-based, local-scoped
let channel = client.channel("channelName");
channel.subscription(options: Option<Vec<SubscriptionOptions>>)
Parameter | Type | Required | Description |
---|---|---|---|
options | Option<Vec<SubscriptionOptions>> | Yes | Subscription behavior configuration. Pass None for no options. |
Create a subscription set
A client-level SubscriptionSet
allows you to receive messages and events for all entities in the set. A single SubscriptionSet
is useful for similarly handling various message/event types in each channel.
// client-based, general-scoped
pubnub.subscription(parameters: (SubscriptionParams {
channels: Option<&[String]>,
channel_groups: Option<&[String]>,
options: Option<Vec<SubscriptionOptions>>
}))
Parameter | Type | Required | Description |
---|---|---|---|
parameters | SubscriptionParams<String> | Yes | Additional Subscription configuration. |
→ channels | Option<&[String]> | Yes | Subscription behavior configuration. Pass None for no options. |
→ channel_groups | Option<&[String]> | Yes | Subscription behavior configuration. Pass None for no options. |
→ options | Option<Vec<SubscriptionOptions>> | Yes | Subscription behavior configuration. Pass None for no options. |
Add/remove sets
You can add and remove subscription sets to create new sets. Refer to the Other examples section for more information.
SubscriptionOptions
SubscriptionOptions
is an enum. Available variants include:
Option | Description |
---|---|
ReceivePresenceEvents | Whether presence updates for userId should be delivered through the listener streams. |
Method(s)
Subscription
and SubscriptionSet
use the same methods to subscribe:
Subscribe
To subscribe, you can use the following method in the Rust SDK:
subscription.subscribe()
Basic usage
Other examples
Create a subscription set from 2 individual subscriptions
// create a subscription from a channel entity
let channel = client.channel("channelName");
let subscription1 = channel.subscription(options: Option<Vec<SubscriptionOptions>>);
// create a subscription from a channel group entity
let channel_group = client.channel_group("channelGroup");
let subscription2 = channel_group.subscription(options: Option<Vec<SubscriptionOptions>>);
// create a subscription set from individual entities
let set = subscription1 + subscription2;
// Add another subscription to the set
set += subscription3
// Or
set.add_subscriptions(subscription3)
show all 20 linesCreate a subscription set from 2 sets
// create a subscription set with multiple channels
let set1 = pubnub.subscription(parameters: (SubscriptionParams {
channels: Some(&["channelName1", "channelName2"]),
channel_groups: None,
options: None
}))
// create a subscription set with multiple channel groups and options
let set2 = pubnub.subscription(parameters: (SubscriptionParams {
channels: None,
channel_groups: Some(&["channelGroup1", "channelGroup2"]),
options: Option<Vec<SubscriptionOptions>>
}))
// create a new subscription set from 2 sets
show all 19 linesReturns
The subscribe()
method doesn't have a return value.
Subscribe with timetoken
To subscribe to real-time updates from a given timetoken, use the following method in the Rust SDK:
subscription.subscribe_with_timetoken(cursor: Into<SubscriptionCursor>)
Parameter | Type | Required | Description |
---|---|---|---|
cursor | Into<SubscriptionCursor> String usize u64 | Yes | Cursor from which to return any available cached messages. Message retrieval with cursor is not guaranteed and should only be considered a best-effort service. A cursor consists of a timetoken and region: SubscriptionCursor{timetoken: String, region: u32} If you pass any primitive type, the SDK converts them into SubscriptionCursor but if their value is not a 17-digit number or a string with numeric characters, the provided value will be ignored. |
Basic usage
let subscription = pubnub.subscription(SubscriptionParams {
channels: Some(&["my_channel", "other_channel"]),
channel_groups: None,
options: Some(vec![SubscriptionOptions::ReceivePresenceEvents]),
});
let cursor = SubscriptionCursor {
timetoken: "100000000000".to_string(),
region: 1,
};
subscription.subscribe_with_timetoken(cursor);
Returns
The subscribe_with_timetoken()
method doesn't have a return value.
Entities
Entities are subscribable objects for which you can receive real-time updates (messages, events, etc).
Create channels
These methods return one or more local Channel
entities.
pubnub.channel(String)
pubnub.channels(&[String])
Parameter | Type | Required | Description |
---|---|---|---|
channel | String | Yes | The name of the channel to create a subscription of. |
channel | &[String] | Yes | The slice with names of the channels to create a subscription of. |
Basic usage
Create channel groups
These methods return one or more local ChannelGroup
entities.
pubnub.channel_group(String)
pubnub.channel_groups(&[String])
Parameter | Type | Required | Description |
---|---|---|---|
channel_group | String | Yes | The name of the channel group to create a subscription of. |
channel_groups | &[String] | Yes | The slice with names of the channel groups to create a subscription of. |
Basic usage
Create channel metadata
These methods return one or more local ChannelMetadata
entities.
pubnub.channel_metadata(String)
pubnub.channels_metadata(&[String])
Parameter | Type | Required | Description |
---|---|---|---|
channel_metadata | String | Yes | The String identifier of the channel metadata object to create a subscription of. |
channels_metadata | &[String] | Yes | The slice with string identifiers of the channel metadata objects to create a subscription of. |