Salesforce Developer Apis Streaming

salesforce-developer-apis

https://trailhead.salesforce.com/force_com_dev_intermediate/api_basics/api_basics_streaming
https://developer.salesforce.com/docs/atlas.en-us.204.0.api.meta/object_ref/pushtopic.htm
https://developer.salesforce.com/docs/atlas.en-us.202.0.api_streaming.meta/api_streaming/resources_push.htm
https://developer.salesforce.com/docs/atlas.en-us.204.0.api_streaming.meta/api_streaming/code_sample_generic_vfp_intro.htm
https://developer.salesforce.com/docs/atlas.en-us.204.0.api_streaming.meta/api_streaming/BayeauxProtocolAndCometD.htm
https://github.com/developerforce/SalesforceDurableStreamingDemo
https://github.com/developerforce/StreamingReplayClientExtensions

// Salesforce - Developer - Streaming API:

Use Streaming API to receive notifications for changes to data that match a 
SOQL query that you define.  Streaming API is useful when you want notifications 
to be pushed from the server to the client. Consider Streaming API for 
applications that poll frequently. Applications that have constant polling 
against the Salesforce infrastructure consume unnecessary API call and 
processing time. Streaming API reduces the number of requests that return no 
data, and is also ideal for applications that require general notification of 
data changes.  Streaming API enables you to reduce the number of API calls and 
improve performance.

Streaming API is a specialized API for setting up notifications that trigger 
when changes are made to your data. It uses a publish-subscribe, or pub/sub, 
model in which users can subscribe to channels that broadcast certain types of 
data changes.  The pub/sub model reduces the number of API requests by 
eliminating the need for polling. Streaming API is great for writing apps that 
would otherwise need to frequently poll for changes.

Streaming API lets you push a stream of notifications from Salesforce to client 
apps based on criteria that you define.

Streaming API is your radar. It lets you define events and push notifications 
to your client app when the events occur. You don’t have to keep an active 
lookout for data changes—you don’t have to constantly poll Salesforce and make 
unnecessary API requests.

Using Triggers and callout might be one way to implement the streaming API.

Tracking data changes in Salesforce is especially useful when you have business 
data stored in a system external to Salesforce. You can use Streaming API to 
keep your external source in sync with your Salesforce data. Also, Streaming 
API lets you process business logic in an external system in response to data 
changes in Salesforce. For example, you can use Streaming API to notify a 
fulfillment center whenever an opportunity is updated.

In addition to data changes, you can use Streaming API to broadcast 
notifications for events defined outside of Salesforce. For example, you can 
make your app display a message whenever a system maintenance window is about 
to start or when a new offer is available to your users. This functionality is 
called generic streaming.

Streaming API uses the Bayeux protocol and the CometD messaging library.

// PushTopics:

We interface with Streaming API through PushTopics. A PushTopic is an sObject 
that contains the criteria of events you want to listen to, such as data changes 
for a particular object. You define the criteria as a SOQL query in the 
PushTopic and specify the record operations to notify on (create, update, 
delete, and undelete). In addition to event criteria, a PushTopic represents 
the channel that client apps subscribe to.

PushTopic queries support all custom objects. PushTopic queries support the 
following standard objects:

1. Account
2. Campaign
3. Case
4. Contact
5. Lead
6. Opportunity
7. Task

The following standard objects are supported in PushTopic queries through a 
pilot program:

1. ContractLineItem
2. Entitlement
3. LiveChatTranscript
4. Quote
5. QuoteLineItem
6. ServiceContract

A PushTopic enables you to define the object, fields, and criteria you’re 
interested in receiving event notifications for. The following example shows a 
PushTopic defined and inserted in Apex. After this PushTopic is created, you can 
subscribe to this PushTopic channel to track changes on accounts whose billing 
city is San Francisco. This PushTopic specifies that the Id, Name, Phone fields 
are returned in each event notification. By default, notifications are sent for 
create, update, delete, and undelete operations that match the query’s criteria.

PushTopic pushTopic = new PushTopic();
pushTopic.Name = 'AccountUpdates';
pushTopic.Query = 'SELECT Id, Name, Phone FROM Account WHERE BillingCity=\'San Francisco\'';
pushTopic.ApiVersion = 37.0;
insert pushTopic;

At the minimum, define the PushTopic name, query, and API version. You can use 
default values for the remaining properties. By default, the fields in the 
SELECT statement field list and WHERE clause are the ones that trigger 
notifications. Notifications are sent only for the records that match the 
criteria in the WHERE clause. To change which fields trigger notifications, 
set pushTopic.NotifyForFields to one of these values.

1. All: Notifications are generated for all record field changes, provided the 
   evaluated records match the criteria specified in the WHERE clause.

2. Referenced (default): Changes to fields referenced in the SELECT and WHERE 
   clauses are evaluated. Notifications are generated for the evaluated records 
   only if they match the criteria specified in the WHERE clause.

3. Select: Changes to fields referenced in the SELECT clause are evaluated. 
   Notifications are generated for the evaluated records only if they match the 
   criteria specified in the WHERE clause.

4. Changes to fields referenced in the WHERE clause are evaluated. Notifications 
   are generated for the evaluated records only if they match the criteria 
   specified in the WHERE clause.

To set notification preferences explicitly, set the following properties to 
either true or false. By default, all values are set to true.

pushTopic.NotifyForOperationCreate = true;
pushTopic.NotifyForOperationUpdate = true;
pushTopic.NotifyForOperationUndelete = true;
pushTopic.NotifyForOperationDelete = true;

If you create an account, an event notification is generated. The notification 
is in JSON and contains the fields that we specified in the PushTopic query: 
Id, Name, and Phone. The event notification looks similar to the following.

{
  "clientId": "lxdl9o32njygi1gj47kgfaga4k", 
  "data": {
    "event": {
      "createdDate": "2016-09-16T19:45:27.454Z", 
      "replayId": 1, 
      "type": "created"
    }, 
    "sobject": {
      "Phone": "(415) 555-1212", 
      "Id": "001D000000KneakIAB", 
      "Name": "Blackbeard"
    }
  }, 
  "channel": "/topic/AccountUpdates"
}

The notification message includes the channel for the PushTopic, whose name 
format is /topic/PushTopicName. When you create a PushTopic, the channel is 
created automatically.

PushTopic queries are regular SOQL queries, so if you’re familiar with SOQL, 
you don’t need to learn a new format. If you’re not familiar, don’t worry. 
We cover the basic query format here. In short, the query contains a 
SELECT statement with an optional WHERE clause, as follows:

SELECT <comma-separated list of fields> 
FROM <Salesforce object> 
WHERE <filter criteria>

To ensure that notifications are sent in a timely manner, the following 
requirements apply to PushTopic queries:

1. The SELECT statement’s field list must include Id.
2. Only one object per query is allowed.
3. The object must be valid for the specified API version.

Certain queries aren’t supported, such as aggregate queries or semi-joins.

// Retrieve Past Notifications Using Durable Streaming:

So far, you’ve learned about PushTopics and event notifications for Salesforce 
record changes. What happens if a Salesforce record is created or updated before 
a client subscribes to the PushTopic? Before API version 37.0, the client misses 
the corresponding notification. As of API version 37.0, Salesforce stores events 
that match PushTopic queries, even if no one is subscribed to the PushTopic. 
The events are stored for 24 hours, and you can retrieve them at any time during 
that window.

Starting with API version 37.0, each event notification contains a field called 
replayId. Similar to replaying a video, Streaming API replays the event 
notifications that were sent by using the replayId field. The value of the 
replayId field is a number that identifies the event in the stream. The replay 
ID is unique for the org and channel. When you replay an event, you’re 
retrieving a stored event from a location in the stored stream. You can either 
retrieve a stream of events starting after the event specified by a replay ID, 
or you can retrieve all stored events. Here’s a summary of the replay options 
we can specify when subscribing to a channel.

1. replayId: Subscriber receives notifications for events that occur after the 
   event specified by the replay ID value.

2. -1: Subscriber receives notifications for all new events that occur after 
   subscription.

3. -2: Subscriber receives notifications for all new events that occur after 
   subscription and previous events that fall within the 24-hour retention 
   window.

To learn how to subscribe to events and use replay options, check out the 
Durable Streaming Walkthrough in the Streaming API Developer Guide. The sample 
for the walkthrough is a Visualforce page and a JavaScript CometD extension, the 
Streaming API Developer Guide has a sample app, including a walkthrough with 
detailed instructions. Or you can access the sample code directly in GitHub. 
Check out the Durable Streaming Walkthrough and Salesforce Durable Streaming 
Demo project in the Resources section.

Streaming API supports sending notifications with a generic payload that aren’t 
tied to Salesforce data changes.  You can use generic streaming for any 
situation where you want to send custom notifications, such as:

1. Broadcasting messages to specific teams or to your entire organization
2. Sending notifications for events that are external to Salesforce

To use generic streaming, you need:

1. A streaming channel that defines the channel
2. One or more clients subscribed to the channel
3. The Streaming Channel Push resource to monitor and invoke events on the 
   channel

You can create a streaming channel for generic streaming either through the 
Streaming Channels app in the user interface, or through the API. A streaming 
channel is represented by the StreamingChannel sObject, so you can create it 
through Apex, REST API, or SOAP API. The format of the channel name for generic 
streaming is /u/ChannelName. For example, this Apex snippet creates a channel 
named Broadcast.

StreamingChannel ch = new StreamingChannel();
ch.Name = '/u/Broadcast';
insert ch;

Alternatively, you can opt to have Salesforce create the streaming channel 
dynamically for you if it doesn’t exist. To enable dynamic streaming channels 
in your org, from Setup, enter User Interface in the Quick Find box, then 
select User Interface. On the User Interface page, select the Enable Dynamic 
Streaming Channel Creation option.

You can subscribe to the channel by using a CometD client. (The Resources 
section links to a sample walkthrough in the Streaming API Developer Guide.)

To generate events, make a POST request to the following REST resource. Replace 
XX.0 with the API version and Streaming Channel ID with the ID of your channel.

To obtain your channel ID, run a SOQL query on StreamingChannel, such as: 

SELECT Id, Name FROM StreamingChannel

Instead of broadcasting to all subscribers, specify a list of subscribed users 
to send notifications to by using the optional userIds field. Also, you can use 
the GET method of the Streaming Channel Push REST API resource to get a list of 
active subscribers to the channel.

The event notification that the subscribed client receives looks similar to the 
following:

{
  "clientId": "1p145y6g3x3nmnlodd7v9nhi4k", 
  "data": {
    "payload": "Broadcast message to all subscribers", 
    "event": {
      "createdDate": "2016-09-16T20:43:39.392Z", 
      "replayId": 1
    }
  }, 
  "channel": "/u/Broadcast"
}

Notice that this event notification contains the replayId field. As with 
PushTopic streaming, generic event notifications are also stored for 24 hours 
and can be retrieved using the replayId value starting in API version 37.0.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License