Latest Version: 1.1.0
This library lets your agent code connect to Google’s Cloud Pub/Sub service. It makes use of the Google Cloud Pub/Sub REST API.
You can view the library’s source code on GitHub. Click here to see information on other versions of this library.
To include this library in your project, add
#require "GooglePubSub.agent.lib.nut:1.1.0"
at the top of your agent code.
Google Cloud Pub/Sub is a publish/subscribe service — a messaging service where the senders of messages are decoupled from the receivers of those messages. There are five main entities used by the Pub/Sub service:
Communication between publishers and subscribers can be one-to-many, many-to-one or many-to-many.
Before working with Google Cloud Pub/Sub Service you need to:
A Google Cloud Project is the component of the Google Cloud Platform which allows users to create, configure and use all Cloud Platform resources and services, including Pub/Sub. All Pub/Sub topics and subscriptions are owned by a specific project; the library’s classes needs to instanced for each project you work with.
You can view example that will show you how to create and configure a Google Cloud Project here. For more information, please see Google Cloud Project resource description and Creating and Managing Projects.
The library API is described in detail below.
The library consists of five independent classes. You can instantiate and use any of these classes in your agent code as required by your application. They are:
To instantiate any of these classes you need to have:
The library requires an external provider of access tokens to gain access to Google Cloud services. The provider must contain an acquireAccessToken() method that takes one required parameter: a handler that is called when an access token is acquired or an error occurs. The handler itself has two required parameters: token, a string representation of the access token, and error, a string with error details (or null
if no error occurred). You can either write the provider code yourself or use an external library such as Electric Imp’s OAuth2 library, which contains the required acquireAccessToken() method.
For information about Google Cloud Pub/Sub service authentication, please see this page.
// GooglePubSub library
#require "GooglePubSub.agent.lib.nut:1.1.0"
// OAuth 2.0 library
#require "OAuth2.agent.lib.nut:2.0.0"
// Substitute with real values
const GOOGLE_ISS = "...";
const GOOGLE_SECRET_KEY = "...";
const TOPIC_NAME = "<your_topic_name>";
const PROJECT_ID = "<your_google_cloud_project_id>";
// configuration for OAuth2
local config = { "iss" : GOOGLE_ISS,
"jwtSignKey" : GOOGLE_SECRET_KEY,
"scope" : "https://www.googleapis.com/auth/pubsub" };
// Obtain the Access Tokens Provider
local oAuthTokenProvider = OAuth2.JWTProfile.Client(OAuth2.DeviceFlow.GOOGLE, config);
// Instantiation of topics and publisher components
topics <- GooglePubSub.Topics(PROJECT_ID, oAuthTokenProvider);
publisher <- GooglePubSub.Publisher(PROJECT_ID, oAuthTokenProvider, TOPIC_NAME);
All requests that are made to the Google Cloud Pub/Sub service occur asynchronously. Every method that sends a request has an optional parameter which takes a callback function that will be called when the operation is completed, successfully or not. The callbacks’ parameters are listed in the corresponding method documentation, but every callback has at least one parameter, error. If error is null
, the operation has been executed successfully. Otherwise, error is an instance of the GooglePubSub.Error class and contains the details of the error, accessed through the following properties:
The error type will be one of the following:
PUB_SUB_ERROR.LIBRARY_ERROR — This is reported if the library has been wrongly initialized or invalid arguments are passed into a method. Usually it indicates an issue during an application development which should be fixed during debugging and therefore should not occur after the application has been deployed. Includes the GooglePubSub.Error.details property.
PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED — This is reported if the HTTP request to Google Cloud Pub/Sub service fails. This error may occur during the normal execution of an application. The application logic should process this error. Includes the GooglePubSub.Error.details, GooglePubSub.Error.httpStatus and GooglePubSub.Error.httpResponse properties.
PUB_SUB_ERROR.PUB_SUB_UNEXPECTED_RESPONSE — This indicates an unexpected behavior by the Google Cloud Pub/Sub service, such as a response which does not correspond to the Google Cloud Pub/Sub REST API specification. Includes the GooglePubSub.Error.details and GooglePubSub.Error.httpResponse fields.
GooglePubSub.Message is an auxiliary class that represents a Google Cloud Pub/Sub message, which is a combination of data (of any type) and attributes (a table) that moves through the service. Both data and attributes are optional.
GooglePubSub.Message instances are retrieved using the GooglePubSub.PullSubscriber and/or GooglePubSub.PushSubscriber classes.
GooglePubSub.Message instances may be sent to the Pub/Sub service using the GooglePubSub.Publisher class.
local gMsg = GooglePubSub.Message("Test message", { "attr1" : "value1", "attr2" : "value2" });
A topic is a named entity that represents a message channel. Each message is sent to the Google Cloud Pub/Sub service via a specified topic. Each topic name must be unique to its project.
The GooglePubSub.Topics class can be used to the check the existence of a topic within a project; create and delete topics from the project; and obtain a list of a project’s topics.
The GooglePubSub.Topics class is not intended to send messages — use the GooglePubSub.Publisher class.
const TOPIC_NAME = "<my_topic_name>";
topics <- GooglePubSub.Topics(PROJECT_ID, oAuthTokenProvider);
// Create topic if it doesn't exist
topics.obtain(TOPIC_NAME, { "autoCreate" : true }, function(error) {
if (error) {
server.error(error.details);
} else {
// The topic exists or has been created.
// You can now publish or receive messages
}
});
// Remove topic
topics.remove(TOPIC_NAME, function(error) {
if (error) {
server.error(error.details);
} else {
// The topic was removed successfully
}
});
// Get the list of all topics
topics.list({ "paginate" : false }, function(error, topicNames, nextOptions) {
if (error) {
server.error(error.details);
} else {
// 'topicNames' contains names of all the topics registered to the project
foreach (topic in topicNames) {
// Process topics individually
}
}
});
// Callback for paginated list of topics
function topicsListCallback(error, topicNames, nextOptions) {
if (error) {
server.error(error.details);
} else {
// 'topicNames' contains limited number of topic names
foreach (topic in topicNames) {
// Process topics individually
}
}
if (nextOptions) {
// More topics exist, so continue listing
topics.list(nextOptions, topicsListCallback);
}
}
// Retrieve a paginated list of topics
topics.list({ "paginate" : true, "pageSize" : 5 }, topicsListCallback);
The GooglePubSub.Publisher class allows the agent to publish messages to a specific topic. One instance of this class publishes messages to one of a project’s topics. Both the project and topic are specified in the class constructor.
The class provides only one method, GooglePubSub.Publisher.publish(), which accepts the following data as a message:
const TOPIC_NAME = "<my_topic_name>";
publisher <- GooglePubSub.Publisher(PROJECT_ID, oAuthTokenProvider, TOPIC_NAME);
// Publish a simple message
publisher.publish("Hello!", function(error, messageIds) {
if (!error) {
// Message published successfully
}
});
// Publish an array of compound messages
publisher.publish(
[ { "temperature" : 36.6, "humidity" : 80 },
{ "temperature" : 37.2, "humidity" : 75 } ],
function(error, messageIds) {
if (!error) {
// Message published successfully
}
});
// Publish a message with attributes using GooglePubSub.Message class
publisher.publish(
GooglePubSub.Message("Test message", { "attr1" : "value1", "attr2" : "value2" }),
function(error, messageIds) {
if (!error) {
// Message published successfully
}
});
A subscription is a named entity that represents an interest in receiving messages on a particular topic. Messages are received from a specified Google Cloud Pub/Sub subscription. Subscription names must be unique within the project.
There are two types of subscription:
The class allows your to manage both pull and push subscriptions. It is possible to change a push subscription to a pull one, or vice versa, using the GooglePubSub.Subscriptions.modifyPushConfig() method.
One instance of GooglePubSub.Subscriptions is sufficient to manage all of the subscriptions belonging to the project specified in the class constructor. It can be used to check the existence of a subscription; to create, configure and delete the project’s subscriptions; and to obtain a list of the subscriptions registered to the project or related to a topic.
A subscription configuration is encapsulated in an instance of the GooglePubSub.SubscriptionConfig class. Additional configuration parameters for a push subscription are encapsulated in an instance of GooglePubSub.PushConfig which has a pushEndpoint property: the URL of the endpoint that messages should be pushed to.
The GooglePubSub.Subscriptions class allows to the agent to manage Pub/Sub subscriptions but is not intended to receive messages. To receive messages, the library provides two other components:
const TOPIC_NAME = "<my_topic_name>";
const SUBSCR_NAME = "<my_pull_subscription_name>";
const SUBSCR_NAME_2 = "<my_other_pull_subscription_name>";
const PUSH_SUBSCR_NAME = "<my_push_subscription_name>";
subscrs <- GooglePubSub.Subscriptions(PROJECT_ID, oAuthTokenProvider);
// Check if the subscription exists
subscrs.obtain(SUBSCR_NAME, null, function(error, subscrConfig) {
if (error) {
if (error.type == PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED && error.httpStatus == 404) {
// The subscription doesn't exist
} else {
// A different error occurs
server.error(error.details);
}
} else {
// The subscription exists
}
});
// Get or create a pull subscription
subscrs.obtain(
SUBSCR_NAME_2,
{ "autoCreate" : true, "subscrConfig" : GooglePubSub.SubscriptionConfig(TOPIC_NAME) },
function(error, subscrConfig) {
if (error) {
server.error(error.details);
} else {
// The subscription is obtained
}
});
// Get or create a push subscription based on the agent URL
subscrs.obtain(
PUSH_SUBSCR_NAME,
{
"autoCreate" : true,
"subscrConfig" : GooglePubSub.SubscriptionConfig(
TOPIC_NAME,
10, // ackDeadlineSeconds
GooglePubSub.PushConfig(subscrs.getImpAgentEndpoint()))
},
function(error, subscrConfig) {
if (error) {
server.error(error.details);
} else {
// The subscription is obtained
}
});
// Remove a subscription
subscrs.remove(SUBSCR_NAME_2, function(error) {
if (error) {
server.error(error.details);
} else {
// the subscription removed successfully
}
});
// Get a list of subscriptions related to the topic
subscrs.list({ "topicName" : TOPIC_NAME }, function(error, subscrNames, nextOptions) {
if (error) {
server.error(error.details);
} else {
// 'subscrNames' contains names of all subscriptions related to the topic
foreach (subscr in subscrNames) {
// Process subscriptions individually
}
}
});
The GooglePubSub.PullSubscriber class allows your code to receive messages from a pull subscription and to acknowledge their receipt. One instance of this class receives messages from one of the project’s pull subscription. Both project and subscription are specified in the class constructor.
The received messages are provided as instances of the GooglePubSub.Message class.
The GooglePubSub.PullSubscriber class provides three types of pull operation:
One-shot — A basic pull operation. Call the GooglePubSub.PullSubscriber.pull() method. This checks for new messages and triggers the callback immediately, with or without the messages. It might be used in a universal or in any custom use case, or when other pull operations are not convenient.
Periodic — Call the GooglePubSub.PullSubscriber.periodicPull() method. This periodically checks for new messages and triggers the callback if new messages are available. It might be used when an application does not need to deal with new messages as quickly as possible. If the required period is small, consider using a pending pull (see below).
Pending (waiting) — Call the GooglePubSub.PullSubscriber.pendingPull() method. This waits for new messages and triggers the callback when new messages appear. Optionally, it may automatically recall the same pending pull operation after the callback is executed. This operation might be used in a case when an application needs to deal with new messages as quickly as possible.
Only one pull operation per subscription can be active at a time. An attempt to call a new pull operation while another one is active will fail with a PUB_SUB_ERROR.LIBRARY_ERROR error.
Periodic and pending pull operations may be cancelled by calling the method GooglePubSub.PullSubscriber.stopPull().
Every pull method has an optional parameter to specify the maximum number of messages returned in the callback. Note that the Google Cloud Pub/Sub service may return fewer messages than the specified maximum number even if there are more messages currently available in the subscription.
There are two ways to acknowledge the receipt of a message:
true
, the received messages are automatically acknowledged by the library. This is the recommended setting.const SUBSCR_NAME = "<my_pull_subscription_name>";
pullSubscriber <- GooglePubSub.PullSubscriber(PROJECT_ID, oAuthTokenProvider, SUBSCR_NAME);
// One-shot pulling
pullSubscriber.pull({ "autoAck" : true }, function(error, messages) {
if (!error && messages.len() > 0) {
foreach (msg in messages) {
// Process messages individually
server.log(format("Message received: %s: %s", msg.publishTime, msg.data));
}
}
});
// Periodic pulling with manual acknowledge
pullSubscriber.periodicPull(5.0, null, function(error, messages) {
if (!error) {
pullSubscriber.ack(messages, function(error) {
if (!error) {
// Messages acknowledged successfully
}
});
}
});
// Pending pulling
pullSubscriber.pendingPull({ "repeat" : true, "autoAck" : true }, function(error, messages) {
// The callback is executed every time new messages arrive
if (!error) {
foreach (msg in messages) {
// Process messages individually
}
}
});
The GooglePubSub.PushSubscriber class lets the agent receive messages from a push subscription configured with a push endpoint based on the URL of the agent where the library is running. One instance of this class receives messages from one push subscription. Both the subscription and the project it belongs to, are specified in the class constructor.
The class provides only one method: GooglePubSub.PushSubscriber.setMessagesHandler(). This checks if the specified subscription is configured with an appropriate endpoint URL and sets the specified handler function to be executed every time new messages are received.
The received messages are provided as instances of the GooglePubSub.Message class and are automatically acknowledged by the library.
const PUSH_SUBSCR_NAME = "<my_push_subscription_name>";
pushSubscriber <- GooglePubSub.PushSubscriber(PROJECT_ID, oAuthTokenProvider, PUSH_SUBSCR_NAME);
function messageHandler(error, messages) {
// The handler is executed when incoming messages are received
if (!error) {
foreach (msg in messages) {
// Process messages individually
server.log(format("Message received: %s: %s", msg.publishTime, msg.data));
}
}
}
pushSubscriber.setMessagesHandler(messageHandler, function(error) {
if (!error) {
// Push messages handler set successfully
} else if (error.type == PUB_SUB_ERROR.LIBRARY_ERROR) {
// PushSubscriber cannot be used for the specified subscription
// (e.g. the subscription's push endpoint does not match the agent URL)
}
});
Google’s Identity and Access Management (IAM) functionality allows your code to manage access control by defining who (members) has what access (role) for which resource. For example:
For a detailed description of IAM and its features, please see the Google Cloud Identity and Access Management Overview.
GooglePubSub.IAM is the class that provides IAM functionality for individual Google Cloud Pub/Sub resources (topics and subscriptions). This class should not be instantiated by a user directly; instead the GooglePubSub.Topics.iam() and GooglePubSub.Subscriptions.iam() methods are used to get the instances and to execute IAM methods for topics and subscriptions, respectively.
One instance of GooglePubSub.IAM class is sufficient to manage access to either all the topics or all the subscriptions belonging to one project.
IAM policy representation is encapsulated in instances of the GooglePubSub.IAM.Policy class.
const TOPIC_NAME = "<my_topic_name>";
topics <- GooglePubSub.Topics(PROJECT_ID, oAuthTokenProvider);
// Get the access control policy for the topic
topics.iam().getPolicy(TOPIC_NAME, function(error, policy) {
if (error) {
server.error(error.details);
} else {
// The policy was obtained successfully
foreach (binding in policy.bindings) {
// Process policy bindings
server.log(format("Binding %s : %s", binding.role,
binding.members.reduce(function(prev, curr) { return (prev + ", " + curr); })));
}
}
});
const SUBSCR_NAME = "<my_subscription_name>";
subscrs <- GooglePubSub.Subscriptions(PROJECT_ID, oAuthTokenProvider);
local testedPermissions = ["pubsub.subscriptions.get", "pubsub.subscriptions.delete"];
// Test subscription permissions
subscrs.iam().testPermissions(
SUBSCR_NAME,
testedPermissions,
function(error, returnedPermissions) {
if (!error) {
// 'returnedPermissions' contains the subset of 'testedPermissions' that allowed for the subscription
}
});
This method enables (value = true
) or disables (value = false
) the library debug output (including error logging). It is disabled by default and returns nothing.
Represents an error returned by the library and has the following public properties:
null
if type is PUB_SUB_ERROR.LIBRARY_ERRORnull
if type is PUB_SUB_ERROR.LIBRARY_ERROR.Represents a Google Pub/Sub Message: a combination of data of any type and optional attributes that a publisher sends to a topic. It has the following public properties:
"2014-10-02T15:01:23.045123456Z"
.Creates a message that can be published. The message must contain either a non-empty data field, or at least one attribute. Otherwise GooglePubSub.Publisher.publish() method will fail with PUB_SUB_ERROR.LIBRARY_ERROR error.
Parameter | Data Type | Required? | Description |
---|---|---|---|
data | Any | Optional | The message data |
attributes | Table of key-value strings | Optional | The message attributes |
Helps your code manage topics.
Parameter | Data Type | Required? | Description |
---|---|---|---|
projectId | String | Yes | The ID of a Google Cloud Project |
oAuthTokenProvider | Object | Yes | The provider of access tokens suitable for Google Pub/Sub service requests authentication. See here for more information |
Checks if the specified topic exists. If the topic does not exist and the autoCreate option is true
, the topic is created.
If the topic does not exist and the autoCreate option is false
, the method fails with a PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error (with httpStatus 404).
Parameter | Data Type | Required? | Description |
---|---|---|---|
topicName | String | Yes | The name of the topic |
options | Table of key-value strings | Optional | The valid keys (options) are: autoCreate — A boolean indicating whether the topic should be created if it does not exist. Default: false |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has a single parameter, error, which will be null
on success, or an instance of GooglePubSub.Error.
Deletes the specified topic, if it exists. If it doesn’t, the operation fails with a PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error (with httpStatus 404).
Existing subscriptions related to the deleted topic are not destroyed.
After the topic is deleted, a new topic may be created with the same name; this will be an entirely new topic with none of the old configuration or subscriptions.
Parameter | Data Type | Required? | Description |
---|---|---|---|
topicName | String | Yes | The unique name of the topic |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has a single parameter, error, which will be null
on success, or an instance of GooglePubSub.Error.
Get a list of the names of all topics registered to the project.
Parameter | Data Type | Required? | Description |
---|---|---|---|
options | Table of key-value strings | Optional | The valid keys (options) are: paginate — a boolean indicating whether the operation returns a limited number of topics (up to pageSize) and a new pageToken which allows to obtain the next page of data, or the entire list of topics ( false ). Default: false .pageSize — An integer specifying the maximum number of topics to return. If paginate is false , this option is ignored. Default: 20.pageToken — A string containing the page token returned by the previous paginated list() call; indicates that the library should return the next page of data. If paginate is false , this option is ignored. If paginate is true and pageToken is not specified, the library starts listing from the beginning |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
topicNames | Array of strings | The names of the topics |
nextOptions | Table of key-value strings | An options table that can be directly used as an argument for a subsequent paginated list() call; it contains pageToken returned by the currently executed list() call. nextOptions is null if no more results are available, the paginate option was false or the operation fails |
Returns an instance of the GooglePubSub.IAM class that can be used to execute Identity and Access Management methods for topics.
Allows your code to publish messages to a specific topic.
Parameter | Data Type | Required? | Description |
---|---|---|---|
projectId | String | Yes | The project’s ID |
oAuthTokenProvider | Object | Yes | The provider of access tokens suitable for Google Pub/Sub service requests authentication. See [here]( |
| topicName | String | Yes | The name of the topic to publish message to |
Publishes the provided message, or array of messages, to the topic.
Parameter | Data Type | Required? | Description |
---|---|---|---|
message | Various | Yes | The message(s) to be published. It can be: • Any type — Raw data value • Array of any type — An array of raw data values • GooglePubSub.Message instance • Array of GooglePubSub.Message instances |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
messageIds | Array of strings | Google Pub/Sub service IDs of each published message, in the same order as the messages in the request. IDs are guaranteed to be unique within the topic |
Represents a Google Pub/Sub subscription’s configuration and has the following public properties:
null
for pull subscriptions.Creates a subscription configuration that can be used to crete a new subscription.
Parameter | Data Type | Required? | Description |
---|---|---|---|
topicName | String | Yes | The name of the topic from which this subscription receives messages |
ackDeadlineSeconds | Integer | Optional | The maximum time (in seconds) after receiving a message when the message must be acknowledged before it is redelivered by the Pub/Sub service. Default: 10 seconds |
pushConfig | GooglePubSub.PushConfig | Optional | Additional configuration for push subscription. Default: null (ie. pull subscription) |
Represents the additional configuration details required by a push subscription. It has the following public properties:
null
.Parameter | Data Type | Required? | Description |
---|---|---|---|
pushEndpoint | String | Yes | The push endpoint URL |
attributes | Table of key-value strings | Optional | Push endpoint attributes |
Allows your code to manage subscriptions.
Parameter | Data Type | Required? | Description |
---|---|---|---|
projectId | String | Yes | The project’s ID |
oAuthTokenProvider | Object | Yes | The provider of access tokens suitable for Google Pub/Sub service requests authentication. See here for more information |
Obtains the specified subscription. If a subscription with the specified name exists, the method retrieves its configuration. If a subscription with the specified name doesn’t exist, and the autoCreate option is true
, the subscription is created. In this case, the subscrConfig option must be specified. If the subscription does not exist and autoCreate is false
, the method fails with a PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error (with httpStatus 404).
Parameter | Data Type | Required? | Description |
---|---|---|---|
subscriptionName | String | Yes | The unique name of the subscription |
options | Table of key-value strings | Optional | The valid keys (options) are: autoCreate — a boolean indicating whether the subscription should be created if it does not exist. Default: false subscrConfig — a GooglePubSub.SubscriptionConfig instance holding configuration of the subscription to be created. If autoCreate is true , subscrConfig must be specified. Otherwise, subscrConfig is ignored |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
subscrConfig | GooglePubSub.SubscriptionConfig | The configuration of the obtained subscription |
This method may be used to change a push subscription to a pull one or vice versa, or to change the push endpoint URL and other attributes of a push subscription. To modify a push subscription to a pull one, pass null
or an empty table as the value of the pushConfig parameter.
Parameter | Data Type | Required? | Description |
---|---|---|---|
subscriptionName | String | Yes | The unique name of the subscription |
pushConfig | GooglePubSub.PushConfig | Yes | A new push configuration for future deliveries. null or an empty table indicates that the Pub/Sub service should stop pushing messages from the given subscription and allow messages to be pulled and acknowledged |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has a single parameter, error, which will be null
on success, or an instance of GooglePubSub.Error.
Deletes the specified subscription, if it exists. Otherwise it fails with a PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error (with httpStatus 404).
All messages retained in the subscription are immediately dropped and cannot be delivered by any means.
After the subscription is deleted, a new one may be created with the same name. The new subscription has no association with the old one or its topic unless the same topic is specified for the new subscription.
Parameter | Data Type | Required? | Description |
---|---|---|---|
subscriptionName | String | Yes | The unique name of the subscription |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has a single parameter, error, which will be null
on success, or an instance of GooglePubSub.Error.
Gets a list of the names of all subscriptions registered to the project or related to the specified topic.
Parameter | Data Type | Required? | Description |
---|---|---|---|
options | Table of key-value strings | Optional | The valid keys (options) are: topicName — A string with name of the topic to list subscriptions from. If not specified, the method lists all subscriptions registered to the project. paginate — a boolean indicating whether the operation returns a limited number of topics (up to pageSize) and a new pageToken which allows to obtain the next page of data, or the entire list of topics ( false ). Default: false .pageSize — An integer specifying the maximum number of topics to return. If paginate is false , this option is ignored. Default: 20.pageToken — A string containing the page token returned by the previous paginated list() call; indicates that the library should return the next page of data. If paginate is false , this option is ignored. If paginate is true and pageToken is not specified, the library starts listing from the beginning |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
subscrNames | Array of strings | The names of the subscriptions |
nextOptions | Table of key-value strings | An options table that can be directly used as an argument for subsequent paginated list() call; it contains the pageToken returned by the currently executed list() call. nextOptions is null if no more results are available, paginate was false , or the operation failed |
Returns an instance of the GooglePubSub.IAM class that can be used to execute Identity and Access Management methods for subscriptions.
Composes and returns an endpoint URL based on the URL of the agent where the library is running. The resulting URL can be used to create a push subscription and receive messages from this subscription using the GooglePubSub.PushSubscriber class.
Parameter | Data Type | Required? | Description |
---|---|---|---|
relativePath | String | Optional | The relative path which to be added to the agent URL |
secretToken | String | Optional | A secret token specified by a user. It can be used to verify that the messages pushed to the push endpoint are originated from the Google Cloud Pub/Sub service. More information here |
Allows messages to be received from a pull subscription and then acknowledged.
Parameter | Data Type | Required? | Description |
---|---|---|---|
projectId | String | Yes | The project’s ID |
oAuthTokenProvider | Object | Yes | The provider of access tokens suitable for Google Pub/Sub service requests authentication. See here for more information |
subscriptionName | String | Yes | The unique name of the subscription |
Provides one-shot pulling. Checks for new messages and calls any callback immediately, with or without the messages. The new messages (if any) are returned in the callback (up to maxMessages in number). The messages are automatically acknowledged if the autoAck option is true
.
Only one pull operation can be active at a time. An attempt to call a new pull operation while another one is active fails with a PUB_SUB_ERROR.LIBRARY_ERROR error.
Parameter | Data Type | Required? | Description |
---|---|---|---|
options | Table of key-value strings | Optional | The valid keys (options) are: autoAck — A boolean indicating whether messages should be automatically acknowledged once it's pulled. Default: false maxMessages — An integer specifying the maximum number of messages to be returned. The Google Pub/Sub service may return fewer than the number specified even if there are more messages available. Default: 20 |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
messages | Array of GooglePubSub.Message instances | The messages returned |
Provides periodic pulling. It periodically checks for new messages and calls any callback if new messages are available at the time of the check. The new messages are returned in the callback (up to maxMessages in number). The messages are automatically acknowledged if the autoAck option is true
.
Only one pull operation can be active at a time. An attempt to call a new pull operation while another one is active fails with a PUB_SUB_ERROR.LIBRARY_ERROR error.
Parameter | Data Type | Required? | Description |
---|---|---|---|
period | Float | Yes | The period of checks, in seconds. Must be positive. The specified period should not be too small, otherwise a number of HTTP requests per second will exceed Electric Imp’s maximum rate limit and further requests will fail with a PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error. More information about HTTP request rate-limiting can be found here |
options | Table of key-value strings | Optional | The valid keys (options) are: autoAck — A boolean indicating whether messages should be automatically acknowledged once it's pulled. Default: false maxMessages — An integer specifying the maximum number of messages to be returned. The Google Pub/Sub service may return fewer than the number specified even if there are more messages available. Default: 20 |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
messages | Array of GooglePubSub.Message instances | The messages returned |
Provides pending (waiting) pulling. It waits for new messages and calls any callback when new messages appear. The new messages are returned in the callback (up to maxMessages in number). The messages are automatically acknowledged if the autoAck option is true
.
Only one pull operation can be active at a time. An attempt to call a new pull operation while another one is active fails with a PUB_SUB_ERROR.LIBRARY_ERROR error.
Parameter | Data Type | Required? | Description |
---|---|---|---|
options | Table of key-value strings | Optional | The valid keys (options) are: repeat — A boolean: if true , pendingPull() is automatically called with the same parameters after the callback is executed. Default: false autoAck — A boolean indicating whether messages should be automatically acknowledged once it's pulled. Default: false maxMessages — An integer specifying the maximum number of messages to be returned. The Google Pub/Sub service may return fewer than the number specified even if there are more messages available. Default: 20 |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
messages | Array of GooglePubSub.Message instances | The messages returned |
Stops periodic or pending pull operation if it was started by periodicPull() or pendingPull(). It does nothing if no periodic or pending pull operation is currently active.
Acknowledges that the message or messages have been received. Acknowledging a message whose acknowledgement deadline has expired may succeed, but such a message may be redelivered by the Google Pub/Sub service later. Acknowledging a message more than once will not result in an error.
Parameter | Data Type | Required? | Description |
---|---|---|---|
message | Various types | Yes | The message(s) to be acknowledged. It can be: • String — The acknowledgment ID of the received message • Array of strings — An array of the acknowledgment IDs • GooglePubSub.Message — the received GooglePubSub.Message instance • Array of GooglePubSub.Message instances |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has a single parameter, error, which will be null
on success, or an instance of GooglePubSub.Error.
Modifies the acknowledgement deadline for a specific message or messages. This method is useful to indicate that more time is needed to process a message by the subscriber, or to make the message available for redelivery if the processing was interrupted.
Parameter | Data Type | Required? | Description |
---|---|---|---|
message | Various types | Yes | The message(s) to be acknowledged. It can be: • String — The acknowledgment ID of the received message • Array of strings — An array of the acknowledgment IDs • GooglePubSub.Message — the received GooglePubSub.Message instance • Array of GooglePubSub.Message instances |
ackDeadlineSeconds | Integer | Yes | The new acknowledgement deadline, in seconds |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has a single parameter, error, which will be null
on success, or an instance of GooglePubSub.Error.
Allows your code to receive messages from a push subscription. The messages are automatically acknowledged by the library.
Parameter | Data Type | Required? | Description |
---|---|---|---|
projectId | String | Yes | The project’s ID |
oAuthTokenProvider | Object | Yes | The provider of access tokens suitable for Google Pub/Sub service requests authentication. See here for more information |
subscriptionName | String | Yes | The unique name of the subscription |
Checks if the subscription is configured with an appropriate push endpoint URL (based on URL of the agent where the library is running) and sets the specified handler function to be executed every time new messages are received from the Google Pub/Sub service.
If the subscription is not configured with an appropriate URL, the operation fails with a PUB_SUB_ERROR.LIBRARY_ERROR error.
Parameter | Data Type | Required? | Description |
---|---|---|---|
messagesHandler | Function | Yes | The function to be executed when new messages are received |
callback | Function | Optional | Executed once the operation is completed |
The messagesHandler function has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details. When the received messages have an incorrect format, PUB_SUB_ERROR.PUB_SUB_UNEXPECTED_RESPONSE error is reported, otherwise null if the received messages are correctly formatted |
messages | An array GooglePubSub.Message instances | The messages that have been received |
The method returns nothing. The result of the operation may be obtained via the callback function, which has a single parameter, error, which will be null
on success, or an instance of GooglePubSub.Error.
Represents a Google Identity and Access Management (IAM) policy and has the following public properties:
Parameter | Data Type | Required? | Description |
---|---|---|---|
version | Integer | Optional | The version of the policy. Default: 0 |
bindings | Array of tables | Optional | The bindings (see above) |
etag | String | Optional | An entity tag. See here for more information |
Provides Google Identity and Access Management (IAM) functionality for individual Google Pub/Sub resources (topics and subscriptions).
IAM and its features are described in details in the Google Cloud Identity and Access Management Overview
Gets the access control policy for the specified resource (topic or subscription).
Parameter | Data Type | Required? | Description |
---|---|---|---|
resourceName | String | Yes | The name of the required topic or subscription |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
policy | GooglePubSub.IAM.Policy | IAM policy obtained for the resource |
Sets the access control policy on the specified resource (topic or subscription). It replaces any previous policy.
Parameter | Data Type | Required? | Description |
---|---|---|---|
resourceName | String | Yes | The name of the required topic or subscription |
policy | GooglePubSub.IAM.Policy | Yes | The IAM policy to be applied |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
policy | GooglePubSub.IAM.Policy | The new IAM policy for the resource |
Tests the set of permissions for the specified resource (topic or subscription). If the resource does not exist, this operation returns an empty set of permissions, rather than a PUB_SUB_ERROR.PUB_SUB_REQUEST_FAILED error.
Parameter | Data Type | Required? | Description |
---|---|---|---|
resourceName | String | Yes | The name of the required topic or subscription |
permissions | String or array of string | Yes | The permission(s) to test. Permissions with wildcards such as * or pubsub.topics.* are not allowed. For a list of the available permissions see the Google Cloud Pub/Sub Access Control documentation |
callback | Function | Optional | Executed once the operation is completed |
The method returns nothing. The result of the operation may be obtained via the callback function, which has the following parameters:
Parameter | Data Type | Description |
---|---|---|
error | GooglePubSub.Error | Error details, or null if the operation succeeds |
permissions | Array of strings | A subset of the permissions set for the resource |
The Electric Imp Dev Center documents the latest version of the library. For past versions, please see the Electric Imp public GitHub repos listed below.
Version | Source Code | Notes |
---|---|---|
1.0.0 | GitHub | Initial release |
1.1.0 | GitHub | Remove AWS Lambda dependencies; uses OAuth-2.0 library 2.0.0 |
The GooglePubSub library is licensed under the MIT License