Reference documentation and code samples for the Cloud PubSub Client class Subscription.
A named resource representing the stream of messages from a single, specific topic, to be delivered to the subscribing application.
Example:
// Create subscription through a topic
use Google\Cloud\PubSub\PubSubClient;
$pubsub = new PubSubClient();
$topic = $pubsub->topic('my-new-topic');
$subscription = $topic->subscription('my-new-subscription');
// Create subscription through PubSubClient
use Google\Cloud\PubSub\PubSubClient;
$pubsub = new PubSubClient();
$subscription = $pubsub->subscription(
'my-new-subscription',
'my-new-topic'
);
// Consuming messages received via push with JWT Authentication.
use Google\Auth\AccessToken;
// Remove the `Bearer ` prefix from the token.
// If using another request manager such as Symfony HttpFoundation,
// use `Authorization` as the header name, e.g. `$request->headers->get('Authorization')`.
$jwt = explode(' ', $_SERVER['HTTP_AUTHORIZATION'])[1];
// Using the Access Token utility requires installation of the `phpseclib/phpseclib` dependency at version 2.
$accessTokenUtility = new AccessToken();
$payload = $accessTokenUtility->verify($jwt);
if (!$payload) {
throw new \RuntimeException('Could not verify token!');
}
echo 'Authenticated using ' . $payload['email'];
Methods
__construct
Create a Subscription.
The idiomatic way to use this class is through the PubSubClient or Topic, but you can instantiate it directly as well.
Parameters | |
---|---|
Name | Description |
connection |
Google\Cloud\PubSub\Connection\ConnectionInterface
The service connection object |
projectId |
string
The current project |
name |
string
The subscription name |
topicName |
string
The topic name the subscription is attached to |
encode |
bool
Whether messages are encrypted or not. |
info |
array
[optional] Subscription info. Used to pre-populate the object. |
name
Get the subscription name
Example:
echo $subscription->name();
Returns | |
---|---|
Type | Description |
string |
detached
Indicates whether the subscription is detached from its topic.
Detached subscriptions don't receive messages from their topic and don't
retain any backlog. Pull
and StreamingPull
requests will return
FAILED_PRECONDITION. If the subscription is a push subscription, pushes
to the endpoint will not be made.
Example:
$detached = $subscription->detached();
if ($detached) {
echo "The subscription is detached";
}
Parameter | |
---|---|
Name | Description |
options |
array
[optional] Configuration options. |
Returns | |
---|---|
Type | Description |
bool |
create
Execute a service request creating the subscription.
The suggested way of creating a subscription is by calling through {@see} or {@see}.
Returns subscription info in the format detailed in the documentation for a subscription.
NOTE: Some methods of instantiation of a Subscription do not supply a topic name. The topic name is required to create a subscription.
Example:
$topic = $pubsub->topic('my-new-topic');
$subscription = $topic->subscription('my-new-subscription');
$result = $subscription->create();
Parameters | |||||||||
---|---|---|---|---|---|---|---|---|---|
Name | Description | ||||||||
options |
array
Configuration Options | ||||||||
↳ ackDeadlineSeconds |
int
The maximum time after a subscriber receives a message before the subscriber should acknowledge the message. | ||||||||
↳ deadLetterPolicy |
array
A policy that specifies the conditions for dead lettering messages in this subscription. If deadLetterPolicy is not set, dead lettering is disabled. The Cloud Pub/Sub service account associated with this subscriptions's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to acknowledge messages on this subscription.
| ||||||||
↳ enableMessageOrdering |
bool
If true, messages published with the same | ||||||||
↳ expirationPolicy |
array
A policy that specifies the conditions for resource expiration (i.e., automatic resource deletion).
| ||||||||
↳ filter |
string
An expression written in the Pub/Sub filter language. If non-empty, then only messages whose | ||||||||
↳ messageRetentionDuration |
Duration|string
How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If | ||||||||
↳ pushConfig.attributes |
array
Endpoint configuration attributes. | ||||||||
↳ pushConfig.oidcToken |
array
If specified, Pub/Sub will generate and attach an OIDC JWT token as an
| ||||||||
↳ pushConfig.pushEndpoint |
string
A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use "https://example.com/push". | ||||||||
↳ retainAckedMessages |
bool
Indicates whether to retain acknowledged messages. | ||||||||
↳ retryPolicy |
array
A policy that specifies how Cloud Pub/Sub retries message delivery for this subscription. If not set, the default retry policy is applied. This generally means that messages will be retried as soon as possible for healthy subscribers. Retry Policy will be triggered on NACKs or acknowledgement deadline exceeded events for a given message. Retry Policies are implemented on a best effort basis At times, the delay between deliveries may not match the configuration. That is, the delay can be more or less than the configured backoff.
| ||||||||
↳ enableExactlyOnceDelivery |
bool
Indicates whether to enable 'Exactly Once Delivery' on the subscription. |
Returns | |
---|---|
Type | Description |
array | An array of subscription info |
update
Update the subscription.
Note that subscription name and topic are immutable properties and may not be modified.
Example:
$subscription->update([
'retainAckedMessages' => true
]);
// Updating labels and push config attributes with explicit update masks.
$subscription->update([
'labels' => [
'label-1' => 'value'
],
'pushConfig' => [
'attributes' => [
'x-goog-version' => 1
]
]
], [
'updateMask' => [
'labels',
'pushConfig.attributes'
]
]);
Parameters | |||||||||
---|---|---|---|---|---|---|---|---|---|
Name | Description | ||||||||
subscription |
array
The Subscription data. | ||||||||
↳ ackDeadlineSeconds |
int
The maximum time after a subscriber receives a message before the subscriber should acknowledge the message. | ||||||||
↳ deadLetterPolicy |
array
A policy that specifies the conditions for dead lettering messages in this subscription. If deadLetterPolicy is not set, dead lettering is disabled. The Cloud Pub/Sub service account associated with this subscriptions's parent project (i.e., service-{project_number}@gcp-sa-pubsub.iam.gserviceaccount.com) must have permission to acknowledge messages on this subscription.
| ||||||||
↳ enableMessageOrdering |
bool
If true, messages published with the same | ||||||||
↳ expirationPolicy |
array
A policy that specifies the conditions for resource expiration (i.e., automatic resource deletion).
| ||||||||
↳ messageRetentionDuration |
Duration|string
How long to retain unacknowledged messages in the subscription's backlog, from the moment a message is published. If | ||||||||
↳ pushConfig.attributes |
array
Endpoint configuration attributes. | ||||||||
↳ pushConfig.oidcToken |
array
If specified, Pub/Sub will generate and attach an OIDC JWT token as an
| ||||||||
↳ pushConfig.pushEndpoint |
string
A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use "https://example.com/push". | ||||||||
↳ retainAckedMessages |
bool
Indicates whether to retain acknowledged messages. | ||||||||
↳ retryPolicy |
array
A policy that specifies how Cloud Pub/Sub retries message delivery for this subscription. If not set, the default retry policy is applied. This generally means that messages will be retried as soon as possible for healthy subscribers. Retry Policy will be triggered on NACKs or acknowledgement deadline exceeded events for a given message. Retry Policies are implemented on a best effort basis At times, the delay between deliveries may not match the configuration. That is, the delay can be more or less than the configured backoff.
| ||||||||
↳ enableExactlyOnceDelivery |
bool
Indicates whether to enable 'Exactly Once Delivery' on the subscription. | ||||||||
options |
array
Configuration options. | ||||||||
↳ updateMask |
array
A list of field paths to be modified. Nested key names should be dot-separated, e.g. |
Returns | |
---|---|
Type | Description |
array | The subscription info. |
delete
Delete a subscription
Example:
$subscription->delete();
Parameter | |
---|---|
Name | Description |
options |
array
[optional] Configuration Options. |
Returns | |
---|---|
Type | Description |
void |
exists
Check if a subscription exists.
Service errors will NOT bubble up from this method. It will always return a boolean value. If you want to check for errors, use {@see}.
If you need to re-check the existence of a subscription that is already downloaded, call {@see} first to refresh the cached information.
Example:
if ($subscription->exists()) {
echo 'Subscription exists!';
}
Parameter | |
---|---|
Name | Description |
options |
array
[optional] Configuration Options |
Returns | |
---|---|
Type | Description |
bool |
info
Get info on a subscription
If the info is already cached on the object, it will return that result. To fetch a fresh result, use {@see}.
Example:
$info = $subscription->info();
echo $info['name']; // `projects/my-awesome-project/subscriptions/my-new-subscription`
Parameter | |
---|---|
Name | Description |
options |
array
[optional] Configuration Options |
Returns | |
---|---|
Type | Description |
array | Subscription data |
reload
Retrieve info on a subscription from the API.
To use the previously cached result (if it exists), use {@see}.
Example:
$subscription->reload();
$info = $subscription->info();
echo $info['name']; // `projects/my-awesome-project/subscriptions/my-new-subscription`
Parameter | |
---|---|
Name | Description |
options |
array
[optional] Configuration Options |
Returns | |
---|---|
Type | Description |
array | Subscription data |
pull
Retrieve new messages from the topic.
Example:
$messages = $subscription->pull();
foreach ($messages as $message) {
echo $message->data();
}
Parameters | |
---|---|
Name | Description |
options |
array
Configuration Options |
↳ returnImmediately |
bool
If true, the system will respond immediately, even if no messages are available. Otherwise, wait until new messages are available. Defaults to |
↳ maxMessages |
int
Limit the amount of messages pulled. Defaults to |
Returns | |
---|---|
Type | Description |
array<Google\Cloud\PubSub\Message> |
acknowledge
Acknowledge receipt of a message.
Use {@see} to acknowledge multiple messages at once.
Example:
$messages = $subscription->pull();
foreach ($messages as $message) {
$subscription->acknowledge($message);
}
$messages = $subscription->pull();
foreach ($messages as $message) {
$failedMsgs = $subscription->acknowledge($message, ['returnFailures' => true]);
// Either log or store the $failedMsgs to be retried later
}
Parameters | |
---|---|
Name | Description |
message |
Google\Cloud\PubSub\Message
A message object. |
options |
array
Configuration Options |
↳ returnFailures |
bool
If set, and if an acknowledgement is failed with a temporary failure code, it will be retried with an exponential delay. This will also make sure that the permanently failed message is returned to the caller. This is only true for a subscription with 'Exactly Once Delivery' enabled. Read more about EOD: https://cloud.google.com/pubsub/docs/exactly-once-delivery |
Returns | |
---|---|
Type | Description |
void|array |
acknowledgeBatch
Acknowledge receipt of multiple messages at once.
Use {@see} to acknowledge a single message.
Example:
$messages = $subscription->pull();
$subscription->acknowledgeBatch($messages);
$messages = $subscription->pull();
$failedMsgs = $subscription->acknowledgeBatch($messages, ['returnFailures' => true]);
// Either log or store the $failedMsgs to be retried later
Parameters | |
---|---|
Name | Description |
messages |
array<Google\Cloud\PubSub\Message>
An array of messages |
options |
array
Configuration Options |
↳ returnFailures |
bool
If set, and if a message is failed with a temporary failure code, it will be retried with an exponential delay. This will also make sure that the permanently failed message is returned to the caller. This is only true for a subscription with 'Exactly Once Delivery' enabled. Read more about EOD: https://cloud.google.com/pubsub/docs/exactly-once-delivery |
Returns | |
---|---|
Type | Description |
void|array |
modifyAckDeadline
Set the acknowledge deadline for a single ackId.
Use {@see} to modify the ack deadline for multiple messages at once.
Example:
$messages = $subscription->pull();
foreach ($messages as $message) {
$subscription->modifyAckDeadline($message, 3);
sleep(2);
// Now we'll acknowledge!
$subscription->acknowledge($message);
break;
}
Parameters | |
---|---|
Name | Description |
message |
Google\Cloud\PubSub\Message
A message object |
seconds |
int
The new ack deadline with respect to the time this request was sent to the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new ack deadline will expire 10 seconds after the ModifyAckDeadline call was made. Specifying zero may immediately make the message available for another pull request. |
options |
array
Configuration Options |
↳ returnFailures |
bool
If set, and if a message is failed with a temporary failure code, it will be retried with an exponential delay. This will also make sure that the permanently failed message is returned to the caller. This is only true for a subscription with 'Exactly Once Delivery' enabled. Read more about EOD: https://cloud.google.com/pubsub/docs/exactly-once-delivery |
Returns | |
---|---|
Type | Description |
void|array |
modifyAckDeadlineBatch
Set the acknowledge deadline for multiple ackIds.
Use {@see} to modify the ack deadline for a single message.
Example:
$messages = $subscription->pull();
// Set the ack deadline to three seconds from now for every message
$subscription->modifyAckDeadlineBatch($messages, 3);
// Delay execution, or make a sandwich or something.
sleep(2);
// Now we'll acknowledge
$subscription->acknowledgeBatch($messages);
$messages = $subscription->pull();
$failedMsgs = $subscription->modifyAckDeadlineBatch($messages, 3, ['returnFailures' => true]);
// Either log or store the $failedMsgs to be retried later
Parameters | |
---|---|
Name | Description |
messages |
array<Google\Cloud\PubSub\Message>
An array of messages |
seconds |
int
The new ack deadline with respect to the time this request was sent to the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new ack deadline will expire 10 seconds after the ModifyAckDeadline call was made. Specifying zero may immediately make the message available for another pull request. |
options |
array
Configuration Options |
↳ returnFailures |
bool
If set, and if a message is failed with a temporary failure code, it will be retried with an exponential delay. This will also make sure that the permanently failed message is returned to the caller. This is only true for a subscription with 'Exactly Once Delivery' enabled. Read more about EOD: https://cloud.google.com/pubsub/docs/exactly-once-delivery |
Returns | |
---|---|
Type | Description |
void|array |
modifyPushConfig
Set the push config for the subscription
Example:
$subscription->modifyPushConfig([
'pushEndpoint' => 'https://www.example.com/foo/bar'
]);
Parameters | |
---|---|
Name | Description |
pushConfig |
array
Push delivery configuration. See PushConfig for more details. |
↳ pushEndpoint |
string
A URL locating the endpoint to which messages should be pushed. For example, a Webhook endpoint might use "https://example.com/push". |
↳ attributes |
array
Endpoint configuration attributes. |
options |
array
[optional] Configuration Options |
Returns | |
---|---|
Type | Description |
void |
seekToTime
Seek to a given timestamp.
When you seek to a time, it has the effect of marking every message received before this time as acknowledged, and all messages received after the time as unacknowledged.
Please note that this method may not yet be available in your project.
Example:
$time = $pubsub->timestamp(new \DateTime('2017-04-01'));
$subscription->seekToTime($time);
Parameters | |
---|---|
Name | Description |
timestamp |
Google\Cloud\Core\Timestamp
The time to seek to. |
options |
array
[optional] Configuration options. |
Returns | |
---|---|
Type | Description |
void |
seekToSnapshot
Seek to a given snapshot.
When seeking to a snapshot, any message that had an "unacknowledged" state when the snapshot was created can be re-delivered.
Please note that this method may not yet be available in your project.
Example:
$snapshot = $pubsub->snapshot('my-snapshot');
$subscription->seekToSnapshot($snapshot);
Parameters | |
---|---|
Name | Description |
snapshot |
Google\Cloud\PubSub\Snapshot
The snapshot to seek to. |
options |
array
[optional] Configuration options. |
Returns | |
---|---|
Type | Description |
void |
detach
Detach the subscription from its topic.
All messages retained in the subscription are dropped. Subsequent Pull
requests will return FAILED_PRECONDITION. If the subscription is a push
subscription, pushes to the endpoint will stop.
Example:
$subscription->detach();
Parameter | |
---|---|
Name | Description |
options |
array
[optional] Configuration options. |
Returns | |
---|---|
Type | Description |
array |
iam
Manage the IAM policy for the current Subscription.
Example:
$iam = $subscription->iam();
Returns | |
---|---|
Type | Description |
Google\Cloud\Core\Iam\Iam |
__debugInfo
Present a nicer debug result to people using php 5.6 or greater.
Returns | |
---|---|
Type | Description |
array |
getMaxRetries
Getter for the private static variable
Returns | |
---|---|
Type | Description |
int |
Constants
MAX_MESSAGES
Value: 1000